0
0
PyTesttesting~15 mins

Test functions in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify addition function returns correct sum
Preconditions (2)
Step 1: Create a function named add that takes two numbers and returns their sum
Step 2: Write a test function named test_add that calls add with 2 and 3
Step 3: Assert that the result of add(2, 3) is 5
✅ Expected Result: The test passes confirming the add function returns the correct sum
Automation Requirements - pytest
Assertions Needed:
Assert that add(2, 3) equals 5
Best Practices:
Use clear and descriptive test function names starting with test_
Keep test functions small and focused on one behavior
Use assert statements for validation
Place test functions in separate test files named test_*.py
Automated Solution
PyTest
def add(a, b):
    return a + b


def test_add():
    result = add(2, 3)
    assert result == 5, f"Expected 5 but got {result}"

The add function simply returns the sum of two numbers.

The test function test_add calls add(2, 3) and stores the result.

It then uses assert to check if the result is 5.

If the assertion fails, pytest will show the message with the actual result.

This test function is simple, clear, and follows pytest naming conventions.

Common Mistakes - 3 Pitfalls
{'mistake': "Not prefixing test function name with 'test_'", 'why_bad': 'pytest will not recognize the function as a test and will skip it', 'correct_approach': "Always start test function names with 'test_' so pytest can find and run them"}
Using print statements instead of assert
Testing multiple behaviors in one test function
Bonus Challenge

Now add data-driven testing with 3 different input pairs and expected sums

Show Hint