Skip to main content

Testing (pytest)

TODO

Setup module Setup class setup function hypothesis setup

from unittest import TestCase
import hypothesis.strategies as st
from hypothesis import given, settings

class TestHypothesis(TestCase):
    class_number = 0
    class_number_pytest = 0
    method_number = 0
    method_number_pytest = 0
    example_number = 0

    @classmethod
    def setUpClass(cls):
        cls.class_number += 1

    @classmethod
    def tearDownClass(cls):
        cls.class_number -= 1

    @classmethod
    def setup_class(cls):
        cls.class_number_pytest += 2

    @classmethod
    def teardown_class(cls):
        cls.class_number_pytest -= 2

    @classmethod
    def setUp(cls):
        cls.method_number += 3

    @classmethod
    def tearDown(cls):
        cls.method_number -= 3

    def setup_method(self, _method):
        self.method_number_pytest += 4

    def teardown_method(self, _method):
        self.method_number_pytest -= 4

    @classmethod
    def setup_example(cls):
        cls.example_number += 5

    @classmethod
    def teardown_example(cls, _token=None):
        cls.example_number -= 5

    @settings(max_examples=100)
    @given(_number=st.integers())
    def test_hypothesis(self, _number: int):
        assert self.class_number == 1, "a"
        assert self.class_number_pytest == 2, "b"
        assert self.method_number == 3, "c"
        assert self.method_number_pytest == 4, "d"
        assert self.example_number == 5, "e"

and their shutdown counterparts

pytest.fixtures


@pytest.fixture(scope="function")
def test_client() -> Iterator[TestClient[Litestar]]:

Asyncio vs trio in pytest?! whats the difference in mark

@pytest.mark.asyncio

@pytest.mark.trio

class TestClass(BaseTestClass):
    @pytest.mark.trio
    async def add_link(self, page: Page) -> None:
        await fill_database_with_2_items_and_link()

pytest mocks

    with patch.object(DiscordQuote, "raw", AsyncMock()) as execute:

pytest.parametrize

import pytest

@pytest.mark.parametrize(
    "book_relative_path, chapters_amount",
    [
        ("actual_books/frankenstein.epub", 31),
        ("actual_books/romeo-and-juliet.epub", 28),
        ("actual_books/the-war-of-the-worlds.epub", 29),
    ],
)
def test_parsing_real_epubs(book_relative_path: str, chapters_amount: int) -> None:  # noqa: F811
    book_path = Path(__file__).parent / book_relative_path
    book_bytes_io = io.BytesIO(book_path.read_bytes())
    chapters_extracted = extract_chapters(book_bytes_io)
    assert len(chapters_extracted) == chapters_amount

pytest.fail

pytest.xfail

@pytest.mark.xfail(reason="If download bandwidth is low, then this test may fail.")
@pytest.mark.asyncio
async def test_download_file():

pytest.skip

httpx

from pytest_httpx import HTTPXMock

@pytest.mark.asyncio
async def test_get_github_user_success(httpx_mock: HTTPXMock):
    httpx_mock.add_response(
        url="https://api.github.com/user",
        json={"id": 123, "login": "Abc"},
    )
    result = await provide_github_user("test_access_token")
    assert result is not None
    assert result.id == 123
    assert result.login == "Abc"

hypothesis

@settings(max_examples=100)
@example(_day=1_000_000, _hour=0, _minute=0, _second=0, _message="a")
@example(_day=0, _hour=1_000_000, _minute=0, _second=0, _message="a")
@example(_day=0, _hour=0, _minute=1_000_000, _second=0, _message="a")
@example(_day=0, _hour=0, _minute=0, _second=1_000_000, _message="a")
@given(
    # Day
    st.integers(min_value=0, max_value=1_000_000),
    # Hour
    st.integers(min_value=0, max_value=1_000_000),
    # Minute
    st.integers(min_value=0, max_value=1_000_000),
    # Second
    st.integers(min_value=0, max_value=1_000_000),
    # Message
    st.text(min_size=1),
)
@pytest.mark.asyncio
async def test_parsing_date_and_time_from_message_success(_day, _hour, _minute, _second, _message: str):