Writing Basic Tests in pytest
Now that pytest is set up, it’s time to write and run your first test. In this section, you’ll learn the basics of creating test functions, naming them correctly, and using assert statements.
Writing Your First Test Function
A test function is a regular Python function that checks if part of your code works as expected. pytest identifies test functions automatically based on their names.
Example: First Test
Create a file named test_example.py
with the following content:
def test_addition():
assert 1 + 1 == 2 # This checks if the addition is correct
Steps to Run the Test
- Save the file in your project directory.
- Open a terminal or command prompt and navigate to the file’s directory.
- Run the test using:
pytest test_example.py
- You should see output indicating that the test passed:
================== test session starts ================== collected 1 item test_example.py . [100%] ================== 1 passed in 0.01s ==================
Understanding pytest Naming Conventions
To ensure pytest can discover your test functions, follow these simple naming rules:
File Naming
- Test files should be named with a
test_
prefix or a_test
suffix (e.g.,test_example.py
,example_test.py
).
Function Naming
- Test function names should start with
test_
(e.g.,test_addition
,test_subtraction
).
Why Naming Matters
pytest uses these naming conventions to automatically find and run your test cases. Without them, pytest might skip your tests.
Using assert
Statements in pytest
The assert
statement is a fundamental tool in pytest. It checks if a condition is true. If the condition is false, the test fails.
Examples of Assert Statements
1. Checking Equality
def test_equality():
assert 3 * 2 == 6 # Passes because 3 times 2 equals 6
2. Checking Conditions
def test_condition():
assert 5 > 3 # Passes because 5 is greater than 3
3. Checking Membership
def test_membership():
fruits = ["apple", "banana", "cherry"]
assert "apple" in fruits # Passes because 'apple' is in the list
What Happens When an Assertion Fails?
If an assertion fails, pytest stops the test and shows detailed output explaining the failure. For example:
def test_failure():
assert 2 + 2 == 5 # This will fail
Output:
E assert 4 == 5
E + where 4 = 2 + 2
This output tells you exactly why the test failed.
By following these simple steps and conventions, you can start writing basic tests with pytest. Assertions help ensure your code behaves as expected, making debugging and development more efficient.
Ready to explore more? Let’s dive into running tests and understanding test output next!