Developer Guides

Pytest Tutorial: Python Unit Testing Guide for Beginners

Learn the essentials of Python unit testing with Pytest, covering setup, assertions, mocking, and fixtures.

4 min read

Learn the essentials of Python unit testing with Pytest, covering setup, assertions, mocking, and fixtures. Follow this beginner-friendly guide for actionable insights.

Prerequisites for Getting Started

Before diving into Python unit testing with Pytest, ensure you have the following:

prerequisites

  • Python installed on your system.
  • Access to a terminal or command-line interface.
  • Basic understanding of Python syntax.
  • Install the Pytest module by running:
    bash
    pip install pytest

Setting Up Pytest in Your Project

To set up Pytest in your Python project:

steps

  1. Create a new folder for your Python project, e.g., python-testing.

  2. Inside this folder, create a Python file for your main code, e.g., main.py. Add the following sample function for testing:

    python
    # main.py
    def get_weather(temp):
        if temp > 20:
            return "hot"
        else:
            return "cold"
  3. Ensure you have Pytest installed by running:

    bash
    pip install pytest

Writing Your First Unit Test

Follow these steps to write and run your first Pytest unit test:

steps

  1. Create a test file named test_main.py. Test files should be prefixed with test_.
  2. Import the function to test from the target code file:
    python
    # test_main.py
    from main import get_weather
  3. Write a test function prefixed with test_ and use assertions to validate behavior:
    python
    def test_get_weather():
        assert get_weather(21) == "hot"
        assert get_weather(10) == "cold"
  4. Run the test with Pytest:
    bash
    pytest test_main.py

Output will indicate which tests passed or failed.

Running Tests and Interpreting Results

To execute the tests in your project and review the results:

Running Pytest

cd path/to/your/project   # Navigate to your project folder
pytest test_main.py       # Run the test file
# Example output:
# ============================= test session starts =============================
# collected 2 items
#
# test_main.py ..                                                   [100%]
#
# ============================== 2 passed in 0.02s ===============================

Understanding Fixtures for Reusable Test Setups

Use Pytest fixtures to create isolated and reusable setups for your tests:

steps

  1. Import pytest and create a fixture using the @pytest.fixture decorator:
    python
    import pytest
    
    @pytest.fixture
    def sample_data():
        return {"name": "Alice", "age": 30}
  2. Inject the fixture into your test function:
    python
    def test_sample_data(sample_data):
        assert sample_data["name"] == "Alice"
  3. Execute the tests, and the fixture will automatically supply its value.

Implementing Parameterized Tests

Simplify repetitive test cases using parameterized testing:

steps

  1. Use the @pytest.mark.parametrize decorator to specify inputs and expected outputs:
    python
    import pytest
    from main import get_weather
    
    @pytest.mark.parametrize("test_input,expected", [(21, "hot"), (10, "cold")])
    def test_get_weather(test_input, expected):
        assert get_weather(test_input) == expected
  2. Run the tests, and Pytest will execute the test function for each set of parameters.

Utilizing Mocking in Unit Tests

Mock external dependencies to isolate your tests from external factors:

steps

  1. Install pytest-mock:
    bash
    pip install pytest-mock
  2. Mock a function or class in your tests:
    python
    def test_api_call(mocker):
        mock_get = mocker.patch("requests.get")
        mock_get.return_value.status_code = 200
        mock_get.return_value.json.return_value = {"result": "success"}
        
        response = make_api_call()  # Your function that calls requests.get
        assert response == {"result": "success"}

Testing Python Framework APIs

For testing web APIs in Python frameworks like Flask or Django:

steps

  1. Configure the application in testing mode:
    python
    import pytest
    from flask import Flask
    
    app = Flask(__name__)
    app.config["TESTING"] = True
  2. Create a fixture for the test client:
    python
    @pytest.fixture
    def client():
        with app.test_client() as client:
            yield client
  3. Write tests using the client to send HTTP requests:
    python
    def test_get_user(client):
        response = client.get("/user/1")
        assert response.status_code == 200
  4. Run the test suite and validate the results.

FAQ

What is Pytest used for?

Pytest is a Python testing framework used to write test cases, validate functionality, and ensure code reliability. It's popular due to its easy-to-read syntax, powerful plugins, and features like fixtures and parameterized tests.

How do I install Pytest on my system?

You can install Pytest via pip by running:

bash
pip install pytest
How do I interpret Pytest results?

When you run Pytest, it displays the status of all test cases. Passed tests are marked with a dot (.), failed tests with an F, and skipped tests with an s. For failures, Pytest provides detailed error messages to help debug issues.

What are Pytest fixtures?

Fixtures provide a reusable mechanism to set up and clean up resources needed for tests. They eliminate duplication by preparing necessary objects (like database connections) before running each test.


Official reference: pytest documentation.