File: test_env.py

package info (click to toggle)
pytest-env 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 136 kB
  • sloc: python: 257; makefile: 4
file content (199 lines) | stat: -rw-r--r-- 6,331 bytes parent folder | download | duplicates (2)
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
from __future__ import annotations

import os
import re
from pathlib import Path
from unittest import mock

import pytest


@pytest.mark.parametrize(
    ("env", "ini", "expected_env"),
    [
        pytest.param(
            {},
            "[pytest]\nenv = MAGIC=alpha",
            {"MAGIC": "alpha"},
            id="new key - add to env",
        ),
        pytest.param(
            {},
            "[pytest]\nenv = MAGIC=alpha\n SORCERY=beta",
            {"MAGIC": "alpha", "SORCERY": "beta"},
            id="two new keys - add to env",
        ),
        pytest.param(
            # This test also tests for non-interference of env variables between this test and tests above
            {},
            "[pytest]\nenv = d:MAGIC=beta",
            {"MAGIC": "beta"},
            id="D flag - add to env",
        ),
        pytest.param(
            {"MAGIC": "alpha"},
            "[pytest]\nenv = MAGIC=beta",
            {"MAGIC": "beta"},
            id="key exists in env - overwrite",
        ),
        pytest.param(
            {"MAGIC": "alpha"},
            "[pytest]\nenv = D:MAGIC=beta",
            {"MAGIC": "alpha"},
            id="D exists - original val kept",
        ),
        pytest.param(
            {"PLANET": "world"},
            "[pytest]\nenv = MAGIC=hello_{PLANET}",
            {"MAGIC": "hello_world"},
            id="curly exist - interpolate var",
        ),
        pytest.param(
            {"PLANET": "world"},
            "[pytest]\nenv = R:MAGIC=hello_{PLANET}",
            {"MAGIC": "hello_{PLANET}"},
            id="R exists - not interpolate var",
        ),
        pytest.param(
            {"MAGIC": "a"},
            "[pytest]\nenv = R:MAGIC={MAGIC}b\n D:MAGIC={MAGIC}c\n MAGIC={MAGIC}d",
            {"MAGIC": "{MAGIC}bd"},
            id="incremental interpolation",
        ),
        pytest.param(
            {"PLANET": "world"},
            "[pytest]\nenv = D:R:RESULT=hello_{PLANET}",
            {"RESULT": "hello_{PLANET}"},
            id="two flags",
        ),
        pytest.param(
            {"PLANET": "world"},
            "[pytest]\nenv = R:D:RESULT=hello_{PLANET}",
            {"RESULT": "hello_{PLANET}"},
            id="two flags - reversed",
        ),
        pytest.param(
            {"PLANET": "world"},
            "[pytest]\nenv = d:r:RESULT=hello_{PLANET}",
            {"RESULT": "hello_{PLANET}"},
            id="lowercase flags",
        ),
        pytest.param(
            {"PLANET": "world"},
            "[pytest]\nenv =  D  :  R  :  RESULT  =  hello_{PLANET}",
            {"RESULT": "hello_{PLANET}"},
            id="whitespace is ignored",
        ),
        pytest.param(
            {"MAGIC": "zero"},
            "",
            {"MAGIC": "zero"},
            id="empty ini works",
        ),
    ],
)
def test_env_via_pytest(
    testdir: pytest.Testdir,
    env: dict[str, str],
    ini: str,
    expected_env: dict[str, str],
    request: pytest.FixtureRequest,
) -> None:
    tmp_dir = Path(str(testdir.tmpdir))
    test_name = re.sub(r"\W|^(?=\d)", "_", request.node.callspec.id).lower()
    Path(str(tmp_dir / f"test_{test_name}.py")).symlink_to(Path(__file__).parent / "template.py")
    (tmp_dir / "pytest.ini").write_text(ini, encoding="utf-8")

    new_env = {
        **env,
        "_TEST_ENV": repr(expected_env),
        "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
        "PYTEST_PLUGINS": "pytest_env.plugin",
    }

    # monkeypatch persists env variables across parametrized tests, therefore using mock.patch.dict
    with mock.patch.dict(os.environ, new_env, clear=True):
        result = testdir.runpytest()

    result.assert_outcomes(passed=1)


@pytest.mark.parametrize(
    ("env", "toml", "ini", "expected_env"),
    [
        pytest.param(
            {},
            '[tool.pytest.ini_options]\nenv = ["MAGIC=toml", "MAGIC_2=toml2"]',
            "[pytest]\nenv = MAGIC=ini\n MAGIC_2=ini2",
            {"MAGIC": "ini", "MAGIC_2": "ini2"},
            id="ini over toml ini_options",
        ),
        pytest.param(
            {},
            '[tool.pytest.ini_options]\nenv = ["MAGIC=toml", "MAGIC_2=toml2"]',
            "",
            {"MAGIC": "toml", "MAGIC_2": "toml2"},
            id="toml via ini_options",
        ),
        pytest.param(
            {},
            '[tool.pytest_env]\nMAGIC = 1\nMAGIC_2 = "toml2"',
            "",
            {"MAGIC": "1", "MAGIC_2": "toml2"},
            id="toml native",
        ),
        pytest.param(
            {},
            '[tool.pytest_env]\nMAGIC = 1\nMAGIC_2 = "toml2"',
            "[pytest]\nenv = MAGIC=ini\n MAGIC_2=ini2",
            {"MAGIC": "1", "MAGIC_2": "toml2"},
            id="toml native over ini",
        ),
        pytest.param(
            {},
            '[tool.pytest_env]\nMAGIC = {value = "toml", "transform"= true, "skip_if_set" = true}',
            "",
            {"MAGIC": "toml"},
            id="toml inline table",
        ),
    ],
)
def test_env_via_toml(  # noqa: PLR0913, PLR0917
    testdir: pytest.Testdir,
    env: dict[str, str],
    toml: str,
    ini: str,
    expected_env: dict[str, str],
    request: pytest.FixtureRequest,
) -> None:
    tmp_dir = Path(str(testdir.tmpdir))
    test_name = re.sub(r"\W|^(?=\d)", "_", request.node.callspec.id).lower()
    Path(str(tmp_dir / f"test_{test_name}.py")).symlink_to(Path(__file__).parent / "template.py")
    if ini:
        (tmp_dir / "pytest.ini").write_text(ini, encoding="utf-8")
    (tmp_dir / "pyproject.toml").write_text(toml, encoding="utf-8")

    new_env = {
        **env,
        "_TEST_ENV": repr(expected_env),
        "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
        "PYTEST_PLUGINS": "pytest_env.plugin",
    }

    # monkeypatch persists env variables across parametrized tests, therefore using mock.patch.dict
    with mock.patch.dict(os.environ, new_env, clear=True):
        result = testdir.runpytest()

    result.assert_outcomes(passed=1)


def test_env_via_toml_bad(testdir: pytest.Testdir) -> None:
    toml_file = Path(str(testdir.tmpdir)) / "pyproject.toml"
    toml_file.write_text("bad toml", encoding="utf-8")

    result = testdir.runpytest()
    assert result.ret == 4
    assert result.errlines == [
        f"ERROR: {toml_file}: Expected '=' after a key in a key/value pair (at line 1, column 5)",
        "",
    ]