0
0
PyTesttesting~15 mins

Test naming conventions in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify pytest test function naming conventions
Preconditions (2)
Step 1: Create a test function with a name starting with 'test_'
Step 2: Create another function without 'test_' prefix
Step 3: Run pytest on the test file
Step 4: Observe which functions pytest executes as tests
✅ Expected Result: pytest runs only the function(s) whose names start with 'test_' and ignores others
Automation Requirements - pytest
Assertions Needed:
Verify that pytest collects and runs only functions starting with 'test_'
Verify that functions without 'test_' prefix are not run
Best Practices:
Use function names starting with 'test_' for pytest to recognize them as tests
Keep test function names descriptive and lowercase with underscores
Avoid using special characters or spaces in test function names
Automated Solution
PyTest
import pytest

collected_tests = []

# Define a test function with correct naming

def test_example_function():
    assert True

# Define a function that should not be collected as a test

def example_function():
    assert False


def test_naming_conventions(pytestconfig):
    # Use pytest's collection mechanism to get test names
    session = pytest.Session.from_config(pytestconfig)
    session.perform_collect()
    for item in session.items:
        collected_tests.append(item.name)

    # Assert that only functions starting with 'test_' are collected
    assert 'test_example_function' in collected_tests
    assert 'example_function' not in collected_tests

This script defines two functions: one named with the 'test_' prefix and one without.

pytest only collects and runs functions starting with 'test_'.

The test_naming_conventions function uses pytest's collection to check which functions are collected.

Assertions confirm that only the correctly named test function is collected and run.

This demonstrates the importance of naming conventions in pytest.

Common Mistakes - 3 Pitfalls
{'mistake': "Naming test functions without the 'test_' prefix", 'why_bad': 'pytest will not recognize or run these functions as tests, causing tests to be skipped silently.', 'correct_approach': "Always start test function names with 'test_' so pytest can find and run them."}
Using uppercase letters or spaces in test function names
{'mistake': "Defining test functions inside classes without 'Test' prefix on class name", 'why_bad': "pytest may not collect test methods inside classes that do not start with 'Test'.", 'correct_approach': "Name test classes starting with 'Test' and test methods starting with 'test_'."}
Bonus Challenge

Create three test functions with different valid names starting with 'test_' and verify pytest runs all three.

Show Hint