Camkode
Camkode

How to Unit Test Python Code with pytest

Posted by Kosal

How to Unit Test Python Code with pytest

pytest is a popular testing framework for Python that makes writing and running unit tests easier and more efficient. Here's a guide on how to use pytest to unit test your Python code:

  1. Installation:

    First, you need to install pytest if you haven't already done so. You can install it via pip:

    pip install pytest
    
  2. Writing Test Functions:

    Create a Python file for your tests, typically named test_<module_name>.py. In this file, write test functions using the naming convention test_<something>.

    # test_my_module.py
    
    def test_addition():
        assert 1 + 1 == 2
    
    def test_subtraction():
        assert 5 - 3 == 2
    
  3. Running Tests:

    To run tests, simply execute pytest in the terminal in the directory containing your test files:

    pytest
    

    pytest will automatically discover and execute your test functions.

    Output:

    ===================== test session starts ======================
    platform win32 -- Python 3.12.1, pytest-8.1.1, pluggy-1.4.0
    rootdir: C:\Users\kosal\code\python\test\pytest
    collected 2 items
    
    test_my_module.py ..                                      [100%]
    
    ====================== 2 passed in 0.02s =======================
    
  4. Assertions:

    Use Python's assert statement inside test functions to check if certain conditions are met. If the condition is False, the test will fail.

  5. Fixtures:

    Fixtures are functions that provide data to your tests. They are defined using the @pytest.fixture decorator.

    import pytest
    
    @pytest.fixture
    def setup_data():
        data = {'name': 'John', 'age': 30}
        return data
    
    def test_data(setup_data):
        assert setup_data['name'] == 'John'
        assert setup_data['age'] == 30
    
  6. Parameterized Tests:

    You can create parameterized tests using the @pytest.mark.parametrize decorator.

    import pytest
    
    @pytest.mark.parametrize('a, b, expected', [(1, 1, 2), (2, 3, 5), (5, 5, 10)])
    def test_addition(a, b, expected):
        assert a + b == expected
    
  7. Skipping Tests:

    You can skip certain tests under specific conditions using the @pytest.mark.skip decorator.

    import pytest
    
    @pytest.mark.skip(reason="Test not implemented yet")
    def test_some_feature():
        ...
    
  8. Assertions and Exceptions:

    You can also test for exceptions using context managers.

    import pytest
    
    def test_exception():
        with pytest.raises(ValueError):
            raise ValueError
    
  9. Coverage Reporting:

    You can generate test coverage reports using pytest-cov plugin.

    pip install pytest-cov
    

    Run tests with coverage:

    pytest --cov=my_module
    

These are the basic steps to get started with pytest for unit testing your Python code. pytest offers many more features and plugins for advanced testing scenarios. You can refer to the official documentation for more details and advanced usage.