File: test_cli.py

package info (click to toggle)
python-pyproject-parser 0.13.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,432 kB
  • sloc: python: 3,086; makefile: 5
file content (515 lines) | stat: -rw-r--r-- 15,463 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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# stdlib
import json
import re
import subprocess
import warnings
from typing import Optional, Type

# 3rd party
import click
import pytest
from coincidence.regressions import AdvancedDataRegressionFixture, AdvancedFileRegressionFixture
from consolekit.testing import CliRunner, Result
from consolekit.tracebacks import handle_tracebacks
from dom_toml.parser import BadConfigError
from domdf_python_tools.paths import PathPlus, in_directory
from pyproject_examples import valid_buildsystem_config, valid_pep621_config
from pyproject_examples.example_configs import (
		COMPLETE_A,
		COMPLETE_A_WITH_FILES,
		COMPLETE_B,
		COMPLETE_PROJECT_A,
		MINIMAL_CONFIG
		)

# this package
from pyproject_parser.__main__ import check, info, reformat
from pyproject_parser.cli import ConfigTracebackHandler
from tests.test_dumping import COMPLETE_UNDERSCORE_NAME, UNORDERED

COMPLETE_DEPENDENCY_GROUPS = COMPLETE_A + """

[dependency-groups]
test = ["pytest", "coverage"]
docs = ["sphinx", "sphinx-rtd-theme"]
typing = ["mypy", "types-requests"]
typing-test = [{include-group = "typing"}, {include-group = "test"}, "useful-types"]
"""


@pytest.mark.parametrize(
		"toml_string",
		[
				pytest.param(COMPLETE_A, id="COMPLETE_A"),
				pytest.param(COMPLETE_A_WITH_FILES, id="COMPLETE_A_WITH_FILES"),
				pytest.param(COMPLETE_B, id="COMPLETE_B"),
				pytest.param(COMPLETE_PROJECT_A, id="COMPLETE_PROJECT_A"),
				pytest.param(UNORDERED, id="UNORDERED"),
				pytest.param(COMPLETE_UNDERSCORE_NAME, id="COMPLETE_UNDERSCORE_NAME"),
				pytest.param(COMPLETE_DEPENDENCY_GROUPS, id="COMPLETE_DEPENDENCY_GROUPS"),
				]
		)
@pytest.mark.parametrize("show_diff", [True, False])
def test_reformat(
		tmp_pathplus: PathPlus,
		toml_string: str,
		cli_runner: CliRunner,
		advanced_file_regression: AdvancedFileRegressionFixture,
		show_diff: bool,
		):
	(tmp_pathplus / "pyproject.toml").write_clean(toml_string)
	(tmp_pathplus / "README.rst").write_clean("This is the README")
	(tmp_pathplus / "LICENSE").write_clean("This is the LICENSE")

	if show_diff:
		args = ["--no-colour", "--show-diff"]
	else:
		args = []

	with in_directory(tmp_pathplus):
		result: Result = cli_runner.invoke(reformat, args=args, catch_exceptions=False)

	assert result.exit_code == 1

	advanced_file_regression.check_file(tmp_pathplus / "pyproject.toml")
	result.check_stdout(advanced_file_regression, extension=".diff")

	# Should be no changes
	with in_directory(tmp_pathplus):
		result = cli_runner.invoke(reformat, args=args, catch_exceptions=False)

	assert result.exit_code == 0

	advanced_file_regression.check_file(tmp_pathplus / "pyproject.toml")
	assert result.stdout == "Reformatting 'pyproject.toml'\n"


@pytest.mark.parametrize("toml_string", [*valid_pep621_config, *valid_buildsystem_config])
def test_check(
		toml_string: str,
		tmp_pathplus: PathPlus,
		cli_runner: CliRunner,
		):
	(tmp_pathplus / "pyproject.toml").write_clean(toml_string)

	with in_directory(tmp_pathplus):
		result: Result = cli_runner.invoke(check, catch_exceptions=False)

	assert result.exit_code == 0
	assert result.stdout == "Validating 'pyproject.toml'\n"


@pytest.mark.parametrize(
		"toml_string",
		[
				pytest.param(
						'[project]\nname = "foo"\nversion = "1.2.3"\n[project.optional-dependencies]\n"dev_test" = []\n"dev-test" = []',
						id="duplicate_extra_1",
						),
				pytest.param(
						'[project]\nname = "foo"\nversion = "1.2.3"\n[project.optional-dependencies]\n"dev-test" = []\n"dev_test" = []',
						id="duplicate_extra_2",
						),
				pytest.param(
						'[project]\nname = "foo"\nversion = "1.2.3"\n[project.optional-dependencies]\n"dev.test" = []\n"dev_test" = []',
						id="duplicate_extra_3",
						),
				]
		)
def test_check_extra_deprecation(
		toml_string: str,
		tmp_pathplus: PathPlus,
		cli_runner: CliRunner,
		advanced_file_regression: AdvancedFileRegressionFixture,
		):
	(tmp_pathplus / "pyproject.toml").write_clean(toml_string)
	cli_runner.mix_stderr = False

	with in_directory(tmp_pathplus), warnings.catch_warnings():
		warnings.simplefilter("error")
		result: Result = cli_runner.invoke(check, catch_exceptions=False)

	assert result.exit_code == 1
	assert result.stdout == "Validating 'pyproject.toml'\n"
	advanced_file_regression.check(result.stderr)


@pytest.mark.parametrize(
		"toml_string",
		[
				pytest.param(
						'[project]\nname = "foo"\nversion = "1.2.3"\n[project.optional-dependencies]\n"dev_test" = []\n"dev-test" = []',
						id="duplicate_extra_1",
						),
				pytest.param(
						'[project]\nname = "foo"\nversion = "1.2.3"\n[project.optional-dependencies]\n"dev-test" = []\n"dev_test" = []',
						id="duplicate_extra_2",
						),
				pytest.param(
						'[project]\nname = "foo"\nversion = "1.2.3"\n[project.optional-dependencies]\n"dev.test" = []\n"dev_test" = []',
						id="duplicate_extra_3",
						),
				]
		)
def test_check_extra_deprecation_warning(
		toml_string: str,
		tmp_pathplus: PathPlus,
		cli_runner: CliRunner,
		advanced_file_regression: AdvancedFileRegressionFixture,
		):
	(tmp_pathplus / "pyproject.toml").write_clean(toml_string)

	args = ["pyproject-parser", "check"]

	with in_directory(tmp_pathplus):
		process = subprocess.run(
				args,
				stderr=subprocess.STDOUT,
				stdout=subprocess.PIPE,
				)
	assert process.returncode == 0

	advanced_file_regression.check(process.stdout.decode("UTF-8"))


@pytest.mark.parametrize(
		"toml_string, match",
		[
				pytest.param(
						"[build-system]\nrequires = []\nfoo = 'bar'",
						r"Unknown key in '\[build-system\]': 'foo'",
						id="build-system",
						),
				pytest.param(
						"[project]\nname = 'whey'\nfoo = 'bar'\nbar = 123\ndynamic = ['version']",
						r"Unknown keys in '\[project\]': 'bar' and 'foo",
						id="project",
						),
				pytest.param(
						"[coverage]\nomit = 'demo.py'\n[flake8]\nselect = ['F401']",
						"Unexpected top-level key 'coverage'. Only 'build-system', 'dependency-groups', 'project' and 'tool' are allowed.",
						id="top-level",
						),
				pytest.param(
						"[build_system]\nbackend = 'whey'",
						"Unexpected top-level key 'build_system'. Did you mean 'build-system'",
						id="top_level_typo_underscore",
						),
				pytest.param(
						"[Build-System]\nbackend = 'whey'",
						"Unexpected top-level key 'Build-System'. Did you mean 'build-system'",
						id="top_level_typo_caps",
						),
				]
		)
def test_check_error(
		toml_string: str,
		tmp_pathplus: PathPlus,
		match: str,
		cli_runner: CliRunner,
		):
	(tmp_pathplus / "pyproject.toml").write_clean(toml_string)

	with pytest.raises(BadConfigError, match=match), in_directory(tmp_pathplus):
		cli_runner.invoke(check, catch_exceptions=False, args=["-T"])


@pytest.mark.parametrize(
		"toml_string",
		[
				pytest.param(
						"[build-system]\nrequires = []\nfoo = 'bar'",
						id="build-system",
						),
				pytest.param(
						"[project]\nname = 'whey'\nfoo = 'bar'\nbar = 123\ndynamic = ['version']",
						id="project",
						),
				pytest.param(
						"[coverage]\nomit = 'demo.py'\n[flake8]\nselect = ['F401']",
						id="top-level",
						),
				pytest.param(
						"[build_system]\nbackend = 'whey'",
						id="top_level_typo_underscore",
						),
				pytest.param(
						"[Build-System]\nbackend = 'whey'",
						id="top_level_typo_caps",
						),
				pytest.param(
						'[project]\nname = "???????12345=============☃"\nversion = "2020.0.0"', id="bad_name"
						),
				pytest.param('[project]\nname = "spam"\nversion = "???????12345=============☃"', id="bad_version"),
				pytest.param(
						f'{MINIMAL_CONFIG}\nrequires-python = "???????12345=============☃"',
						id="bad_requires_python"
						),
				pytest.param(f'{MINIMAL_CONFIG}\nauthors = [{{name = "Bob, Alice"}}]', id="author_comma"),
				]
		)
def test_check_error_caught(
		toml_string: str,
		tmp_pathplus: PathPlus,
		cli_runner: CliRunner,
		advanced_file_regression: AdvancedFileRegressionFixture,
		):
	(tmp_pathplus / "pyproject.toml").write_clean(toml_string)
	cli_runner.mix_stderr = False

	with in_directory(tmp_pathplus):
		result: Result = cli_runner.invoke(check)

	assert result.exit_code == 1
	assert result.stdout == "Validating 'pyproject.toml'\n"
	advanced_file_regression.check(result.stderr)


exceptions = pytest.mark.parametrize(
		"exception",
		[
				pytest.param(
						FileNotFoundError(2, "No such file or directory", "foo.txt"),
						id="FileNotFoundError",
						),
				pytest.param(
						FileNotFoundError(2, "No such file or directory", PathPlus("foo.txt")),
						id="FileNotFoundError_path"
						),
				pytest.param(
						FileNotFoundError(2, "No such file or directory", PathPlus("foo.txt"), -1, "bar.md"),
						id="FileNotFoundError_path_move_etc"
						),
				pytest.param(
						FileNotFoundError(2, "The system cannot find the file specified", "foo.txt"),
						id="FileNotFoundError_win",
						),
				pytest.param(
						FileNotFoundError(2, "The system cannot find the file specified", PathPlus("foo.txt")),
						id="FileNotFoundError_path_win"
						),
				pytest.param(
						FileNotFoundError(
								2,
								"The system cannot find the file specified",
								PathPlus("foo.txt"),
								-1,
								"bar.md",
								),
						id="FileNotFoundError_path_move_etc_win"
						),
				pytest.param(FileExistsError("foo.txt"), id="FileExistsError"),
				pytest.param(Exception("Something's awry!"), id="Exception"),
				pytest.param(ValueError("'age' must be >= 0"), id="ValueError"),
				pytest.param(TypeError("Expected type int, got type str"), id="TypeError"),
				pytest.param(NameError("name 'hello' is not defined"), id="NameError"),
				pytest.param(SyntaxError("invalid syntax"), id="SyntaxError"),
				pytest.param(BadConfigError("Expected a string value for 'name'"), id="BadConfigError"),
				pytest.param(KeyError("name"), id="KeyError"),
				pytest.param(AttributeError("type object 'list' has no attribute 'foo'"), id="AttributeError"),
				pytest.param(ImportError("No module named 'foo'"), id="ImportError"),
				pytest.param(ModuleNotFoundError("No module named 'foo'"), id="ModuleNotFoundError"),
				]
		)


@exceptions
def test_traceback_handler(
		exception: Exception,
		advanced_file_regression: AdvancedFileRegressionFixture,
		cli_runner: CliRunner,
		):

	@click.command()
	def demo():  # noqa: MAN002

		with handle_tracebacks(False, ConfigTracebackHandler):
			raise exception

	result: Result = cli_runner.invoke(demo, catch_exceptions=False)
	result.check_stdout(advanced_file_regression)
	assert result.exit_code == 1


@exceptions
def test_traceback_handler_show_traceback(exception: Exception, cli_runner: CliRunner):

	@click.command()
	def demo():  # noqa: MAN002

		with handle_tracebacks(True, ConfigTracebackHandler):
			raise exception

	with pytest.raises(type(exception), match=re.escape(str(exception))):
		cli_runner.invoke(demo, catch_exceptions=False)


@pytest.mark.parametrize("exception", [EOFError(), KeyboardInterrupt(), click.Abort()])
def test_handle_tracebacks_ignored_exceptions_click(
		exception: Exception,
		cli_runner: CliRunner,
		):

	@click.command()
	def demo():  # noqa: MAN002

		with handle_tracebacks(False, ConfigTracebackHandler):
			raise exception

	result: Result = cli_runner.invoke(demo, catch_exceptions=False)

	assert result.stdout.strip() == "Aborted!"
	assert result.exit_code == 1


@pytest.mark.parametrize("exception", [EOFError, KeyboardInterrupt, click.Abort, SystemExit])
def test_handle_tracebacks_ignored_exceptions(exception: Type[Exception]):

	with pytest.raises(exception):  # noqa: PT012
		with handle_tracebacks(False, ConfigTracebackHandler):
			raise exception


@pytest.mark.parametrize(
		"path",
		[
				pytest.param(None, id="all"),
				"build-system",
				"build-system.requires",
				pytest.param("build-system.requires.[0]", id="first_build_requirement"),
				"project",
				"project.authors",
				pytest.param("project.authors.[0]", id="first_author"),
				pytest.param("project.keywords.[3]", id="fourth_keyword"),
				"project.urls.Source Code",  # Written as `python3 -m pyproject_parser info project.urls."Source Code"`
				"tool.whey.base-classifiers"
				]
		)
@pytest.mark.parametrize("indent", [None, 0, 2, 4])
def test_info(
		path: str,
		tmp_pathplus: PathPlus,
		cli_runner: CliRunner,
		advanced_data_regression: AdvancedDataRegressionFixture,
		advanced_file_regression: AdvancedFileRegressionFixture,
		indent: Optional[int],
		):
	(tmp_pathplus / "pyproject.toml").write_clean(COMPLETE_A)

	if path is None:
		args = []
	else:
		args = [path]

	if indent:
		args.append("--indent")
		args.append(str(indent))

	with in_directory(tmp_pathplus):
		result: Result = cli_runner.invoke(info, catch_exceptions=False, args=args)

	print(result.stdout)
	assert result.exit_code == 0
	output = json.loads(result.stdout)

	if isinstance(output, str):
		advanced_file_regression.check(output, extension=".md")
	else:
		advanced_data_regression.check(output)
		advanced_file_regression.check(result.stdout, extension=".json")

	if path is None:
		args = []
	else:
		args = [path]

	if indent:
		args.append("-i")
		args.append(str(indent))

	with in_directory(tmp_pathplus):
		result = cli_runner.invoke(info, catch_exceptions=False, args=args)

	print(result.stdout)
	assert result.exit_code == 0
	output = json.loads(result.stdout)

	if isinstance(output, str):
		advanced_file_regression.check(output, extension=".md")
	else:
		advanced_data_regression.check(output)
		advanced_file_regression.check(result.stdout, extension=".json")


@pytest.mark.parametrize(
		"path",
		[
				"project.readme",
				"project.readme.file",
				"project.readme.text",
				"project.license",
				"project.license.file",
				"project.license.text",
				]
		)
@pytest.mark.parametrize("check_readme", [0, 1])
@pytest.mark.parametrize("indent", [None, 0, 2, 4])
@pytest.mark.parametrize("resolve", [True, False])
def test_info_readme_license(
		path: str,
		check_readme: int,
		tmp_pathplus: PathPlus,
		cli_runner: CliRunner,
		advanced_data_regression: AdvancedDataRegressionFixture,
		advanced_file_regression: AdvancedFileRegressionFixture,
		monkeypatch,
		resolve: bool,
		indent: Optional[int],
		):

	monkeypatch.setenv("CHECK_README", str(check_readme))

	(tmp_pathplus / "pyproject.toml").write_clean(COMPLETE_A_WITH_FILES)
	(tmp_pathplus / "README.rst").write_clean("This is the README")
	(tmp_pathplus / "LICENSE").write_clean("This is the LICENSE")

	args = [path]

	if resolve:
		args.append("--resolve")
	elif indent:
		args.append("--indent")
		args.append(str(indent))

	with in_directory(tmp_pathplus):
		result: Result = cli_runner.invoke(info, catch_exceptions=False, args=args)

	print(result.stdout)
	assert result.exit_code == 0
	output = json.loads(result.stdout)

	if isinstance(output, str):
		advanced_file_regression.check(output, extension=".md")
	else:
		advanced_data_regression.check(output)
		advanced_file_regression.check(result.stdout, extension=".json")

	args = [path, "-f", (tmp_pathplus / "pyproject.toml").as_posix()]

	if resolve:
		args.append("-r")
	elif indent:
		args.append("-i")
		args.append(str(indent))

	result = cli_runner.invoke(info, catch_exceptions=False, args=args)

	print(result.stdout)
	assert result.exit_code == 0
	output = json.loads(result.stdout)

	if isinstance(output, str):
		advanced_file_regression.check(output, extension=".md")
	else:
		advanced_data_regression.check(output)
		advanced_file_regression.check(result.stdout, extension=".json")