0
0
PyTesttesting~15 mins

Test file and function naming conventions in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify pytest recognizes test files and functions by naming conventions
Preconditions (2)
Step 1: Create a Python file named test_sample.py
Step 2: Inside test_sample.py, define a function named test_addition
Step 3: In test_addition, write an assertion that 2 + 2 equals 4
Step 4: Run pytest on the project folder
Step 5: Observe which tests pytest discovers and runs
✅ Expected Result: pytest discovers and runs the test_addition function inside test_sample.py and reports the test as passed
Automation Requirements - pytest
Assertions Needed:
Verify pytest discovers test files starting with 'test_'
Verify pytest discovers test functions starting with 'test_'
Verify the test function runs and passes
Best Practices:
Name test files starting with 'test_' and ending with '.py'
Name test functions starting with 'test_'
Use simple assert statements for validations
Keep test functions small and focused
Automated Solution
PyTest
import pytest

def test_addition():
    assert 2 + 2 == 4

# To run this test, save it in a file named test_sample.py
# Then run: pytest

# pytest will automatically discover this test because the file and function names start with 'test_'

The code defines a test function named test_addition inside a file named test_sample.py. This follows pytest's naming conventions.

pytest automatically finds files starting with test_ and functions starting with test_. The assertion checks a simple math operation.

When you run pytest, it discovers and runs this test, reporting success if the assertion passes.

Common Mistakes - 3 Pitfalls
{'mistake': "Naming test files without the 'test_' prefix, e.g., sample_test.py", 'why_bad': "pytest will not discover files that do not start with 'test_', so tests inside won't run.", 'correct_approach': "Always name test files starting with 'test_', like test_sample.py."}
{'mistake': "Naming test functions without the 'test_' prefix, e.g., addition_test()", 'why_bad': "pytest ignores functions that do not start with 'test_', so the test won't execute.", 'correct_approach': "Name test functions starting with 'test_', like test_addition()."}
Using print statements instead of assert for validations
Bonus Challenge

Now create three test functions in the same file to test addition, subtraction, and multiplication using correct naming conventions.

Show Hint