Pytest Fundamentals

In this section, we’ll explore the fundamentals of Pytest, covering topics like test discovery, assertions, fixtures, and parametrization.

Test Discovery

Pytest automatically discovers test functions that follow certain naming conventions:

  • Functions starting with test_.
  • Classes starting with Test.
  • Methods within test classes starting with test_.

You can place your test files in any directory, but it’s common to create a tests directory.

Assertions

Assertions are used to check if the expected results match the actual results. Pytest provides several built-in assertion functions:

  • assert x == y: Checks for equality.
  • assert x != y: Checks for inequality.
  • assert x > y: Checks if x is greater than y.
  • assert x < y: Checks if x is less than y.
  • assert x >= y: Checks if x is greater than or equal to y.
  • assert x <= y: Checks if x is less than or equal to y.
  • assert x in y: Checks if x is in the iterable y.
  • assert x not in y: Checks if x is not in the iterable y.
  • assert x is y: Checks for object identity.
  • assert x is not y: Checks for object inequality.

Example:

Python

def test_add():
    assert 2 + 2 == 4

Fixtures

Fixtures provide a way to set up and tear down test environments. They are defined using the @pytest.fixture decorator.

Example:

Python

import pytest

@pytest.fixture
def tmpdir_factory():
    return tmpdir_factory

def test_create_file(tmpdir_factory):
    tmpdir = tmpdir_factory.mktemp("test")
    file_path = tmpdir.join("test.txt")
    with open(file_path, "w") as f:
        f.write("Hello, world!")
    assert file_path.exists()

Parametrization

Parametrization allows you to run the same test with different inputs. You can use the pytest.mark.parametrize decorator to parametrize tests.

Example:

Python

import pytest

@pytest.mark.parametrize("x, y, expected", [
    (2, 3, 5),
    (4, 5, 9),
    (0, 7, 7)
])
def test_add(x, y, expected):
    assert x + y == expected

By understanding these fundamentals, you can effectively use Pytest to write comprehensive and reliable tests for your FastAPI applications.

Starting FastAPI Tests
Pytest Overview

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?