I have a Python function that contains a nested function. I want to write unit tests for the nested function using PyTest, but I don’t want to modify the way the nested function is defined or its behavior. I also don’t want to call or test the outer function itself, just the nested function.
Here is a simplified example of my code:
# example.py
def outer_function(a, b):
"""
Example outer function that performs some operations.
"""
def inner_function(x, y):
"""
Nested function that I want to test.
"""
return x + y
# Some operations using inner_function
result = inner_function(a, b)
return result
I want to create a PyTest test function that only tests inner_function
using parameterization, ensuring it covers various scenarios such as:
- Adding two positive numbers
- Adding positive and negative numbers
- Adding two negative numbers
- Adding zero to a number
How can I achieve this in a way that the tests are independent of outer_function
?
Example Test Function:
# test_example.py
import pytest
@pytest.mark.parametrize("x, y, expected", [
(1, 2, 3), # Adding two positive numbers
(1, -1, 0), # Adding positive and negative numbers
(-1, -2, -3), # Adding two negative numbers
(0, 5, 5), # Adding zero to a number
(3, 0, 3) # Adding a number to zero
])
def test_inner_function(x, y, expected):
"""
Describe how to test the inner_function here.
"""
# Code to test inner_function goes here.
Any guidance or examples on how to properly structure and implement these tests would be greatly appreciated!