File: conftest.py

package info (click to toggle)
litestar 2.19.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,500 kB
  • sloc: python: 70,169; makefile: 254; javascript: 105; sh: 60
file content (164 lines) | stat: -rw-r--r-- 4,959 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from __future__ import annotations

import importlib.util
import sys
from pathlib import Path
from shutil import rmtree
from typing import TYPE_CHECKING, Callable, Generator, Protocol, cast

import pytest
from _pytest.fixtures import FixtureRequest
from _pytest.monkeypatch import MonkeyPatch
from click.testing import CliRunner
from pytest_mock import MockerFixture

from litestar.cli._utils import _path_to_dotted_path

from . import (
    APP_FILE_CONTENT,
    CREATE_APP_FILE_CONTENT,
    GENERIC_APP_FACTORY_FILE_CONTENT,
    GENERIC_APP_FACTORY_FILE_CONTENT_FUTURE_ANNOTATIONS,
    GENERIC_APP_FACTORY_FILE_CONTENT_STRING_ANNOTATION,
)

if TYPE_CHECKING:
    from unittest.mock import MagicMock

    from litestar.cli._utils import LitestarExtensionGroup


@pytest.fixture(autouse=True)
def reset_litestar_app_env(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.delenv("LITESTAR_APP", raising=False)


@pytest.fixture()
def root_command() -> LitestarExtensionGroup:
    import litestar.cli.main

    return cast("LitestarExtensionGroup", importlib.reload(litestar.cli.main).litestar_group)


@pytest.fixture
def patch_autodiscovery_paths(request: FixtureRequest) -> Callable[[list[str]], None]:
    def patcher(paths: list[str]) -> None:
        from litestar.cli._utils import AUTODISCOVERY_FILE_NAMES

        old_paths = AUTODISCOVERY_FILE_NAMES[::]
        AUTODISCOVERY_FILE_NAMES[:] = paths

        def finalizer() -> None:
            AUTODISCOVERY_FILE_NAMES[:] = old_paths

        request.addfinalizer(finalizer)

    return patcher


@pytest.fixture
def tmp_project_dir(monkeypatch: MonkeyPatch, tmp_path: Path) -> Path:
    path = tmp_path / "project_dir"
    path.mkdir(exist_ok=True)
    monkeypatch.chdir(path)
    return path


class CreateAppFileFixture(Protocol):
    def __call__(
        self,
        file: str | Path,
        directory: str | Path | None = None,
        content: str | None = None,
        init_content: str = "",
        subdir: str | None = None,
    ) -> Path: ...


def _purge_module(module_names: list[str], path: str | Path) -> None:
    for name in module_names:
        if name in sys.modules:
            del sys.modules[name]
    Path(importlib.util.cache_from_source(path)).unlink(missing_ok=True)  # type: ignore[arg-type]


@pytest.fixture
def create_app_file(tmp_project_dir: Path, request: FixtureRequest) -> CreateAppFileFixture:
    def _create_app_file(
        file: str | Path,
        directory: str | Path | None = None,
        content: str | None = None,
        init_content: str = "",
        subdir: str | None = None,
    ) -> Path:
        base = tmp_project_dir
        if directory:
            base /= Path(Path(directory) / subdir) if subdir else Path(directory)
            base.mkdir(parents=True)
            base.joinpath("__init__.py").write_text(init_content)

        tmp_app_file = base / file
        tmp_app_file.write_text(content or APP_FILE_CONTENT)

        if directory:
            request.addfinalizer(lambda: rmtree(directory))
            request.addfinalizer(
                lambda: _purge_module(
                    [directory, _path_to_dotted_path(tmp_app_file.relative_to(Path.cwd()))],  # type: ignore[list-item]
                    tmp_app_file,
                )
            )
        else:
            request.addfinalizer(tmp_app_file.unlink)
            request.addfinalizer(lambda: _purge_module([str(file).replace(".py", "")], tmp_app_file))
        return tmp_app_file

    return _create_app_file


@pytest.fixture
def app_file(create_app_file: CreateAppFileFixture) -> Path:
    return create_app_file("app.py")


@pytest.fixture
def runner() -> CliRunner:
    return CliRunner()


@pytest.fixture
def mock_uvicorn_run(mocker: MockerFixture) -> MagicMock:
    return mocker.patch("uvicorn.run")


@pytest.fixture()
def mock_subprocess_run(mocker: MockerFixture) -> MagicMock:
    return mocker.patch("subprocess.run")


@pytest.fixture
def mock_confirm_ask(mocker: MockerFixture) -> Generator[MagicMock, None, None]:
    yield mocker.patch("rich.prompt.Confirm.ask", return_value=True)


@pytest.fixture(
    params=[
        pytest.param((APP_FILE_CONTENT, "app"), id="app_obj"),
        pytest.param((CREATE_APP_FILE_CONTENT, "create_app"), id="create_app"),
        pytest.param((GENERIC_APP_FACTORY_FILE_CONTENT, "any_name"), id="app_factory"),
        pytest.param((GENERIC_APP_FACTORY_FILE_CONTENT_STRING_ANNOTATION, "any_name"), id="app_factory_str_annot"),
        pytest.param((GENERIC_APP_FACTORY_FILE_CONTENT_FUTURE_ANNOTATIONS, "any_name"), id="app_factory_future_annot"),
    ]
)
def _app_file_content(request: FixtureRequest) -> tuple[str, str]:
    return cast("tuple[str, str]", request.param)


@pytest.fixture
def app_file_content(_app_file_content: tuple[str, str]) -> str:
    return _app_file_content[0]


@pytest.fixture
def app_file_app_name(_app_file_content: tuple[str, str]) -> str:
    return _app_file_content[1]