0
0
PyTesttesting~15 mins

First PyTest test - Build an Automation Script

Choose your learning style9 modes available
Verify addition function returns correct sum
Preconditions (2)
Step 1: Create a Python file named test_math.py
Step 2: Define a function add(a, b) that returns the sum of a and b
Step 3: Write a test function test_add() that calls add(2, 3)
Step 4: Assert that the result of add(2, 3) is 5
Step 5: Run pytest on the test_math.py file
✅ Expected Result: Pytest runs the test and shows that test_add passed successfully
Automation Requirements - pytest
Assertions Needed:
Assert that add(2, 3) == 5
Best Practices:
Use clear function names starting with test_
Keep test functions simple and focused
Use assert statements for validation
Name test files starting with test_
Automated Solution
PyTest
def add(a, b):
    return a + b

def test_add():
    result = add(2, 3)
    assert result == 5

The add function simply returns the sum of two numbers.

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

Then it uses assert to check if the result equals 5.

Pytest automatically finds functions starting with test_ and runs them.

This simple test confirms the addition works as expected.

Common Mistakes - 3 Pitfalls
{'mistake': "Not prefixing test function with 'test_'", 'why_bad': 'Pytest will not recognize or run the function as a test', 'correct_approach': "Always start test function names with 'test_' so pytest can find them"}
Using print statements instead of assert
Not running pytest from the correct directory
Bonus Challenge

Now add data-driven testing with 3 different pairs of numbers and their expected sums

Show Hint