File: test_asserts.py

package info (click to toggle)
pytest-django 4.11.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 604 kB
  • sloc: python: 4,006; makefile: 39; sh: 17
file content (73 lines) | stat: -rw-r--r-- 1,854 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
Tests the dynamic loading of all Django assertion cases.
"""

from __future__ import annotations

import inspect

import pytest

import pytest_django
from pytest_django.asserts import __all__ as asserts_all


def _get_actual_assertions_names() -> list[str]:
    """
    Returns list with names of all assertion helpers in Django.
    """
    from unittest import TestCase as DefaultTestCase

    from django import VERSION
    from django.test import TestCase as DjangoTestCase

    if VERSION >= (5, 0):
        from django.contrib.messages.test import MessagesTestMixin

        class MessagesTestCase(MessagesTestMixin, DjangoTestCase):
            pass

        obj = MessagesTestCase("run")
    else:
        obj = DjangoTestCase("run")

    def is_assert(func) -> bool:
        return func.startswith("assert") and "_" not in func

    base_methods = [
        name for name, member in inspect.getmembers(DefaultTestCase) if is_assert(name)
    ]

    return [
        name
        for name, member in inspect.getmembers(obj)
        if is_assert(name) and name not in base_methods
    ]


def test_django_asserts_available() -> None:
    django_assertions = _get_actual_assertions_names()
    expected_assertions = asserts_all
    assert set(django_assertions) == set(expected_assertions)

    for name in expected_assertions:
        assert hasattr(pytest_django.asserts, name)


@pytest.mark.django_db
def test_sanity() -> None:
    from django.http import HttpResponse

    from pytest_django.asserts import assertContains, assertNumQueries

    response = HttpResponse("My response")

    assertContains(response, "My response")
    with pytest.raises(AssertionError):
        assertContains(response, "Not my response")

    assertNumQueries(0, lambda: 1 + 1)
    with assertNumQueries(0):
        pass

    assert assertContains.__doc__