Skip to content

How to write a pytest

Tony Chan edited this page Jan 17, 2025 · 1 revision

Getting Started with pytest

Installation

It should have been installed within your venv or conda. If not, run

pip install pytest

Pytest

pytest 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

Running Tests

  1. Run all tests in the root directory:
pytest
  1. Run a specific test file:
pytest test_example.py
  1. Run tests with verbose output:
pytest -v

Key Features

Fixtures

Fixtures 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 test

Checkout meal_identification/meal_identification/tests/data_cleaning/test_keep_top_n_meals.py for code example

Parameterized Testing

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 == expected

Checkout meal_identification/meal_identification/tests/data_cleaning/test_coerce_time.py for code example

Assertions

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

Best Practices

  1. Keep tests simple and focused on one functionality.
  2. Use descriptive test names that explain the scenario being tested
  3. Follow the "Arrange-Act-Assert" pattern
  4. Use fixtures for common setup code
  5. Group related tests in classes when appropriate
  6. Always write tests for important functions
  7. Always run pytest yourself before pushing or CI might yell at you

Clone this wiki locally