-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathconftest.py
412 lines (337 loc) · 11.6 KB
/
conftest.py
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import os
import re
import shutil
import sys
import time
import venv
from collections.abc import Mapping
from contextlib import contextmanager
from io import StringIO
from pathlib import Path
from subprocess import PIPE, Popen
from typing import Any, NamedTuple, Optional
import pytest
import virtualenv
from poethepoet.app import PoeThePoet
from poethepoet.virtualenv import Virtualenv
try:
import tomllib as tomli
except ImportError:
import tomli # type: ignore[no-redef]
PROJECT_ROOT = Path(__file__).resolve().parent.parent
PROJECT_TOML = PROJECT_ROOT.joinpath("pyproject.toml")
@pytest.fixture(scope="session")
def is_windows():
return sys.platform == "win32"
@pytest.fixture(scope="session")
def pyproject():
with PROJECT_TOML.open("rb") as toml_file:
return tomli.load(toml_file)
@pytest.fixture(scope="session")
def poe_project_path():
return PROJECT_ROOT
@pytest.fixture(scope="session")
def projects():
"""
General purpose provider of paths to test projects with the conventional layout
"""
base_path = PROJECT_ROOT / "tests" / "fixtures"
projects = {
re.match(r"^([_\w]+)_project", path.name).groups()[0]: path.resolve()
for path in base_path.glob("*_project")
}
projects.update(
{
f"{project_key}/"
+ re.match(
rf".*?/{project_key}_project/([_\w\/]+?)(:?\/pyproject)?.toml$",
path.as_posix(),
).groups()[0]: path
for project_key, project_path in projects.items()
for path in project_path.glob("**/*.toml")
if "site-packages" not in str(path)
}
)
return projects
@pytest.fixture(scope="session")
def low_verbosity_project_path():
return PROJECT_ROOT.joinpath("tests", "fixtures", "low_verbosity")
@pytest.fixture(scope="session")
def high_verbosity_project_path():
return PROJECT_ROOT.joinpath("tests", "fixtures", "high_verbosity")
@pytest.fixture
def temp_file(tmp_path):
# not using NamedTemporaryFile here because it doesn't work on windows
tmpfilepath = tmp_path / "tmp_test_file"
tmpfilepath.touch()
return tmpfilepath
class PoeRunResult(NamedTuple):
code: int
path: str
capture: str
stdout: str
stderr: str
def __str__(self):
return (
"PoeRunResult(\n"
f" code={self.code!r},\n"
f" path={self.path},\n"
f" capture=`{self.capture}`,\n"
f" stdout=`{self.stdout}`,\n"
f" stderr=`{self.stderr}`,\n"
")"
)
def assert_no_err(self):
# Only stderr output allowed is from poetry creating its venv
assert all(
line.startswith("Creating virtualenv ") for line in self.stderr.splitlines()
)
@pytest.fixture
def run_poe_subproc(projects, temp_file, tmp_path, is_windows):
coverage_setup = (
"from coverage import Coverage;"
rf'Coverage(data_file=r\"{PROJECT_ROOT.joinpath(".coverage")}\").start();'
)
shell_cmd_template = (
'python -c "'
"{coverage_setup}"
+ (
"import tomli;"
# ruff: noqa: YTT204
if sys.version_info.minor < 11
else "import tomllib as tomli;"
)
+ "from poethepoet.app import PoeThePoet;"
"from pathlib import Path;"
r"poe = PoeThePoet(cwd=r\"{cwd}\", config={config}, output={output});"
"exit(poe([{run_args}]));"
'"'
)
def run_poe_subproc(
*run_args: str,
cwd: Optional[str] = None,
config: Optional[Mapping[str, Any]] = None,
coverage: bool = not is_windows,
env: Optional[dict[str, str]] = None,
project: Optional[str] = None,
) -> PoeRunResult:
if cwd is None:
cwd = projects.get(project, projects["example"])
if config is not None:
config_path = tmp_path.joinpath("tmp_test_config_file")
with config_path.open("w+") as config_file:
tomli.dump(config, config_file)
config_file.seek(0)
config_arg = rf"tomli.load(open(r\"{config_path}\", \"rb\"))"
else:
config_arg = "None"
shell_cmd = shell_cmd_template.format(
coverage_setup=(coverage_setup if coverage else ""),
cwd=cwd,
config=config_arg,
run_args=",".join(f'r\\"{arg}\\"' for arg in run_args),
output=rf"open(r\"{temp_file}\", \"w\")",
)
subproc_env = dict(os.environ)
subproc_env.pop("VIRTUAL_ENV", None)
subproc_env.pop("POE_CWD", None) # do not inherit this from the test
subproc_env.pop("POE_PWD", None) # do not inherit this from the test
if env:
subproc_env.update(env)
if coverage:
subproc_env["COVERAGE_PROCESS_START"] = str(PROJECT_TOML)
poeproc = Popen(
shell_cmd, shell=True, stdout=PIPE, stderr=PIPE, env=subproc_env
)
task_out, task_err = poeproc.communicate()
with temp_file.open("rb") as output_file:
captured_output = (
output_file.read().decode(errors="ignore").replace("\r\n", "\n")
)
result = PoeRunResult(
code=poeproc.returncode,
path=cwd,
capture=captured_output,
stdout=task_out.decode(errors="ignore").replace("\r\n", "\n"),
stderr=task_err.decode(errors="ignore").replace("\r\n", "\n"),
)
print(result) # when a test fails this is usually useful to debug
return result
return run_poe_subproc
@pytest.fixture
def run_poe(capsys, projects):
def run_poe(
*run_args: str,
cwd: str = projects["example"],
config: Optional[Mapping[str, Any]] = None,
project: Optional[str] = None,
config_name="pyproject.toml",
program_name="poe",
env: Optional[Mapping[str, str]] = None,
) -> PoeRunResult:
cwd = projects.get(project, cwd)
output_capture = StringIO()
poe = PoeThePoet(
cwd=cwd,
config=config,
output=output_capture,
config_name=config_name,
program_name=program_name,
env=env,
)
result = poe(run_args)
output_capture.seek(0)
return PoeRunResult(result, cwd, output_capture.read(), *capsys.readouterr())
return run_poe
@pytest.fixture
def run_poe_main(capsys, projects):
def run_poe_main(
*cli_args: str,
cwd: str = projects["example"],
config: Optional[Mapping[str, Any]] = None,
project: Optional[str] = None,
) -> PoeRunResult:
cwd = projects.get(project, cwd)
from poethepoet import main
prev_cwd = os.getcwd()
os.chdir(cwd)
sys.argv = ("poe", *cli_args)
result = main()
os.chdir(prev_cwd)
return PoeRunResult(result, cwd, "", *capsys.readouterr())
return run_poe_main
@pytest.fixture(scope="session")
def run_poetry(use_venv, poe_project_path, version: str = "2.0.0"):
venv_location = poe_project_path / "tests" / "temp" / "poetry_venv"
def run_poetry(args: list[str], cwd: str, env: Optional[dict[str, str]] = None):
venv = Virtualenv(venv_location)
cmd = (venv.resolve_executable("python"), "-m", "poetry", *args)
print("Poetry cmd:", cmd[0])
poetry_proc = Popen(
cmd,
env=venv.get_env_vars({**os.environ, **(env or {})}),
stdout=PIPE,
stderr=PIPE,
cwd=cwd,
)
poetry_out, poetry_err = poetry_proc.communicate()
result = PoeRunResult(
code=poetry_proc.returncode,
path=cwd,
capture="",
stdout=poetry_out.decode(errors="ignore").replace("\r\n", "\n"),
stderr=poetry_err.decode(errors="ignore").replace("\r\n", "\n"),
)
print(result) # when a test fails this is usually useful to debug
return result
with use_venv(
venv_location,
[
".[poetry_plugin]",
f"./tests/fixtures/packages/poetry-{version}-py3-none-any.whl",
],
require_empty=True,
):
yield run_poetry
@pytest.fixture(scope="session")
def esc_prefix(is_windows):
"""
When executing on windows it's not necessary to escape the $ for variables
"""
if is_windows:
return ""
return "\\"
@pytest.fixture(scope="session")
def install_into_virtualenv():
def install_into_virtualenv(location: Path, contents: list[str]):
venv = Virtualenv(location)
Popen(
(venv.resolve_executable("pip"), "install", *contents),
env=venv.get_env_vars(os.environ),
stdout=PIPE,
stderr=PIPE,
).communicate(timeout=120)
return install_into_virtualenv
@pytest.fixture(scope="session")
def use_venv(install_into_virtualenv):
@contextmanager
def use_venv(
location: Path,
contents: Optional[list[str]] = None,
require_empty: bool = False,
):
did_exist = location.is_dir()
assert not require_empty or not did_exist, (
f"Test requires no directory already exists at {location}, "
"maybe try delete it and run again"
)
# create new venv
venv.EnvBuilder(
symlinks=True,
with_pip=True,
).create(str(location))
if contents:
install_into_virtualenv(location, contents)
yield
# Only cleanup if we actually created it to avoid this fixture being a bit
# dangerous
if not did_exist:
try_rm_dir(location)
return use_venv
@pytest.fixture(scope="session")
def use_virtualenv(install_into_virtualenv):
@contextmanager
def use_virtualenv(
location: Path,
contents: Optional[list[str]] = None,
require_empty: bool = False,
):
did_exist = location.is_dir()
assert not require_empty or not did_exist, (
f"Test requires no directory already exists at {location}, "
"maybe try delete it (via `poe clean`) and try again"
)
# create new virtualenv
virtualenv.cli_run([str(location)])
if contents:
install_into_virtualenv(location, contents)
yield
# Only cleanup if we actually created it to avoid this fixture being a bit
# dangerous
if not did_exist:
try_rm_dir(location)
return use_virtualenv
def try_rm_dir(location: Path):
try:
shutil.rmtree(location)
except: # noqa: E722
# The above sometimes files with a Permissions error in CI for Windows
# No idea why, but maybe this will help
print("Retrying venv cleanup")
time.sleep(1)
try:
shutil.rmtree(location)
except: # noqa: E722
print(
"Cleanup failed. You might need to run `poe clean` before tests can be "
"run again."
)
@pytest.fixture(scope="session")
def with_virtualenv_and_venv(use_venv, use_virtualenv):
def with_virtualenv_and_venv(
location: Path,
contents: Optional[list[str]] = None,
):
with use_venv(location, contents, require_empty=True):
yield
with use_virtualenv(location, contents, require_empty=True):
yield
return with_virtualenv_and_venv
@pytest.fixture
def temp_pyproject(tmp_path):
"""Return function which generates pyproject.toml with the given content"""
def generator(project_tmpl: str):
with open(tmp_path / "pyproject.toml", "w") as fp:
fp.write(project_tmpl)
return tmp_path
return generator