About Testing Your Code in Python (Part 2) - Writing Your First Tests

2 min read 275 words

Learn how to write your first pytest tests with practical examples and best practices.

Table of Contents

In this second part of our testing series, we’ll dive into writing actual tests using pytest.

Setting Up Your Test Environment

First, let’s install pytest:

pip install pytest

You can verify the installation with pytest --version.

Writing Your First Test

A pytest test is simply a Python function that starts with test_:

def test_addition():
    """Test that addition works correctly."""
    assert 1 + 1 == 2

def test_subtraction():
    """Test that subtraction works correctly."""
    assert 5 - 3 == 2

class TestCalculator:
    """Group related tests in a class."""

    def test_multiply(self):
        result = 3 * 4
        assert result == 12

    def test_divide(self):
        result = 10 / 2
        assert result == 5.0

Using Fixtures

Fixtures help you set up test data and resources:

import pytest

@pytest.fixture
def sample_data():
    """Provide sample data for tests."""
    return {
        "name": "John Doe",
        "age": 30,
        "email": "[email protected]"
    }

def test_user_name(sample_data):
    assert sample_data["name"] == "John Doe"

def test_user_age(sample_data):
    assert sample_data["age"] >= 18

Running Tests

To run your tests, simply execute:

pytest

For more verbose output:

pytest -v --tb=short

pytest will automatically discover and run all test functions in files matching test_*.py or *_test.py.

Configuration Example

You can configure pytest using a pyproject.toml file:

[tool.pytest.ini_options]
minversion = "7.0"
addopts = "-ra -q"
testpaths = [
    "tests",
]
pythonpath = [
    "src"
]

Best Practices

  1. Keep tests simple and focused - Each test should verify one specific behavior
  2. Use descriptive names - Test names should clearly describe what’s being tested
  3. Arrange, Act, Assert - Structure your tests in these three phases

Next Steps

In the next part, we’ll explore fixtures and how they can help reduce code duplication in your tests.