Pytest Python Library Cheatsheet

Testing is a crucial aspect of software development, ensuring that your code works as expected and remains reliable over time. Pytest, a popular testing framework for Python, simplifies the testing process, making it more efficient and enjoyable for developers. This cheatsheet serves as a quick reference guide to help you harness the power of Pytest and write effective tests.

1. Getting Started: Installing Pytest

Before you start writing tests with Pytest, you need to install it. Use the following command:

pip install pytest

2. Writing and Running Tests

2.1 Basic Test Structure

Create a test function. Name it with “test_” prefix or use the @pytest.mark decorator.

# test_example.py
def test_example():
    assert 1 + 1 == 2

2.2 Running Tests

Run tests using the following command:

pytest test_example.py

2.3 Running Tests in a Directory

Run all tests in a directory:

pytest tests/

2.4 Running Tests Verbosely

Get detailed information on test execution:

pytest -v test_example.py

3. Assertions

3.1 Basic Assertions

Use the assert statement to check conditions:

assert foo() == 42

3.2 Assertion introspection

View detailed information on assertion failures:

pytest --pdb test_example.py

4. Fixture: Setup and Teardown

4.1 Basic Fixture

Use fixtures for test setup and teardown:

import pytest

@pytest.fixture
def setup_teardown():
    # setup code
    yield
    # teardown code

4.2 Fixture Scope

Control fixture scope:

@pytest.fixture(scope="module")
def setup_module():
    # setup code
    yield
    # teardown code

5. Marking and Skipping Tests

5.1 Marking Tests

Mark tests with attributes:

@pytest.mark.slow
def test_slow():
    # test code

5.2 Skipping Tests

Skip tests conditionally:

@pytest.mark.skipif(condition, reason="...")
def test_skip_if():
    # test code

6. Parameterized Testing

6.1 Basic Parametrization

Use the @pytest.mark.parametrize decorator:

@pytest.mark.parametrize("input, expected", [(1, 2), (2, 3)])
def test_add_one(input, expected):
    assert input + 1 == expected

7. Mocking and Patching

7.1 Basic Mocking

Use unittest.mock to create mocks:

from unittest.mock import Mock

def test_example():
    mock_obj = Mock()
    # test code using mock_obj

7.2 Patching

Use @pytest.fixture with monkeypatch for patching:

import pytest

@pytest.fixture
def patch_example(monkeypatch):
    monkeypatch.setenv("VAR_NAME", "new_value")
    # test code

8. Plugins and Customization

8.1 Using Plugins

Install and use plugins:

pip install pytest-html
pytest --html=report.html

8.2 Configuration File

Create a pytest.ini file for configuration:

[pytest]
addopts = --verbose

For more info refer documentation

FAQ

1. What is Pytest, and why should I use it for testing?

Pytest is a testing framework for Python that simplifies the process of writing and executing tests. It offers concise syntax, powerful features, and detailed reporting. Pytest is widely adopted due to its ease of use, compatibility with other testing tools, and support for various testing scenarios.

2. How do I run a specific test or a subset of tests with Pytest?

To run a specific test or a subset of tests, you can specify the test file or directory as a command-line argument to the pytest command. For example, to run a single test file:
pytest test_example.py
To run tests in a specific directory:
pytest tests/

3. What is the purpose of fixtures in Pytest?

Fixtures in Pytest are used for test setup and teardown. They allow you to define reusable components that can be shared across multiple tests. Fixtures are created using the @pytest.fixture decorator, and they provide a clean way to set up preconditions for tests and clean up resources after the tests are executed.

4. Can I parameterize tests in Pytest, and how is it done?

Yes, Pytest supports parameterized testing using the @pytest.mark.parametrize decorator. This feature allows you to run the same test logic with different sets of input parameters. Here’s a simple example:
import pytest @pytest.mark.parametrize("input, expected", [(1, 2), (2, 3)]) def test_add_one(input, expected): assert input + 1 == expected

5. How can I skip or conditionally skip tests in Pytest?

Pytest provides the @pytest.mark.skip and @pytest.mark.skipif decorators for skipping tests. The @pytest.mark.skip decorator skips a test unconditionally, while @pytest.mark.skipif allows you to skip a test based on a condition. For example:
import pytest @pytest.mark.skip(reason="Test is skipped unconditionally") def test_skipped(): # test code @pytest.mark.skipif(condition, reason="Test is skipped if condition is True") def test_conditionally_skipped(): # test code
These decorators provide flexibility in managing which tests should be executed based on specific criteria.