-
Notifications
You must be signed in to change notification settings - Fork 1
How to write a pytest
Tony Chan edited this page Jan 17, 2025
·
1 revision
It should have been installed within your venv or conda. If not, run
pip install pytestpytest follows a simple naming convention:
- Test files should start with
test_or end with_test.py - Test functions should start with
test_ - Test classes should start with
Test
Here's a simple example:
class TestKeepTopNMeals:
def test_top_n_carbs_kept(self):
# Your test case
def test_top_carbs_meals_kept_in_order(self):
# Your test case- Run all tests in the root directory:
pytest- Run a specific test file:
pytest test_example.py- Run tests with verbose output:
pytest -vFixtures are functions that run before test functions. They're used to set up test data or initialize resources:
import pytest
@pytest.fixture
def sample_meal_df():
"""Create a sample DataFrame for testing"""
data = {
'msg_type': ['ANNOUNCE_MEAL', '', 'ANNOUNCE_MEAL'],
}
return pd.DataFrame(data, index=dates)
def test_top_n_carbs_kept(self, sample_meal_df):
# Your test case, sample_meal_df will be injected into this test
def test_top_carbs_meals_kept_in_order(self, sample_meal_df):
# Your test case, sample_meal_df will be injected into this testCheckout meal_identification/meal_identification/tests/data_cleaning/test_keep_top_n_meals.py for code example
Test multiple scenarios using @pytest.mark.parametrize:
import pytest
@pytest.mark.parametrize("input,expected", [
(2, 4),
(3, 6),
(4, 8)
])
def test_multiply_by_two(input, expected):
assert input * 2 == expectedCheckout meal_identification/meal_identification/tests/data_cleaning/test_coerce_time.py for code example
pytest provides rich assertion introspection. Simply use Python's assert statement:
def test_list_contains():
fruits = ['apple', 'banana', 'orange']
assert 'apple' in fruits
def test_dictionary_values():
user = {'name': 'Alice', 'age': 25}
assert user['age'] > 18- Keep tests simple and focused on one functionality.
- Use descriptive test names that explain the scenario being tested
- Follow the "Arrange-Act-Assert" pattern
- Use fixtures for common setup code
- Group related tests in classes when appropriate
- Always write tests for important functions
- Always run
pytestyourself before pushing or CI might yell at you