Debian Codegraph @

testing/test_config.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Sequence
5 import dataclasses
6 import importlib.metadata
7 import os
8 from pathlib import Path
9 import platform
10 import re
11 import sys
12 import textwrap
13 from typing import Any
14
15 import _pytest._code
16 from _pytest.config import _get_plugin_specs_as_list
17 from _pytest.config import _get_prog_name
18 from _pytest.config import _iter_rewritable_modules
19 from _pytest.config import _strtobool
20 from _pytest.config import Config
21 from _pytest.config import ConftestImportFailure
22 from _pytest.config import console_main
23 from _pytest.config import ExitCode
24 from _pytest.config import parse_warning_filter
25 from _pytest.config.argparsing import get_ini_default_for_type
26 from _pytest.config.argparsing import Parser
27 from _pytest.config.exceptions import UsageError
28 from _pytest.config.findpaths import ConfigValue
29 from _pytest.config.findpaths import determine_setup
30 from _pytest.config.findpaths import get_common_ancestor
31 from _pytest.config.findpaths import locate_config
32 from _pytest.monkeypatch import MonkeyPatch
33 from _pytest.pathlib import absolutepath
34 from _pytest.pytester import Pytester
35 from _pytest.warning_types import PytestDeprecationWarning
36 import pytest
37
38
39 class TestParseIni:
40 @pytest.mark.parametrize(
41 "section, filename", [("pytest", "pytest.ini"), ("tool:pytest", "setup.cfg")]
42 )
43 def test_getcfg_and_config(
44 self,
45 pytester: Pytester,
46 tmp_path: Path,
47 section: str,
48 filename: str,
49 monkeypatch: MonkeyPatch,
50 ) -> None:
51 sub = tmp_path / "sub"
52 sub.mkdir()
53 monkeypatch.chdir(sub)
54 (tmp_path / filename).write_text(
55 textwrap.dedent(
56 f"""\
57 [{section}]
58 name = value
59 """
60 ),
61 encoding="utf-8",
62 )
63 _, _, cfg, _ = locate_config(Path.cwd(), [sub])
64 assert cfg["name"] == ConfigValue("value", origin="file", mode="ini")
65 config = pytester.parseconfigure(str(sub))
66 assert config._inicfg["name"] == ConfigValue("value", origin="file", mode="ini")
67
68 def test_setupcfg_uses_toolpytest_with_pytest(self, pytester: Pytester) -> None:
69 p1 = pytester.makepyfile("def test(): pass")
70 pytester.makefile(
71 ".cfg",
72 setup=f"""
73 [tool:pytest]
74 testpaths={p1.name}
75 [pytest]
76 testpaths=ignored
77 """,
78 )
79 result = pytester.runpytest()
80 result.stdout.fnmatch_lines(["configfile: setup.cfg", "* 1 passed in *"])
81 assert result.ret == 0
82
83 def test_append_parse_args(
84 self, pytester: Pytester, tmp_path: Path, monkeypatch: MonkeyPatch
85 ) -> None:
86 monkeypatch.setenv("PYTEST_ADDOPTS", '--color no -rs --tb="short"')
87 tmp_path.joinpath("pytest.ini").write_text(
88 textwrap.dedent(
89 """\
90 [pytest]
91 addopts = --verbose
92 """
93 ),
94 encoding="utf-8",
95 )
96 config = pytester.parseconfig(tmp_path)
97 assert config.option.color == "no"
98 assert config.option.reportchars == "s"
99 assert config.option.tbstyle == "short"
100 assert config.option.verbose
101
102 @pytest.mark.parametrize("flag", ("-r", "--report-chars="))
103 @pytest.mark.parametrize("value", ("fE", "A", "fs"))
104 def test_report_chars_option(
105 self,
106 pytester: Pytester,
107 tmp_path: Path,
108 monkeypatch: MonkeyPatch,
109 flag: str,
110 value: str,
111 ) -> None:
112 """Test that -r/--report-chars is parsed correctly."""
113 monkeypatch.setenv("PYTEST_ADDOPTS", flag + value)
114 config = pytester.parseconfig(tmp_path)
115 assert config.option.reportchars == value
116
117 def test_tox_ini_wrong_version(self, pytester: Pytester) -> None:
118 pytester.makefile(
119 ".ini",
120 tox="""
121 [pytest]
122 minversion=999.0
123 """,
124 )
125 result = pytester.runpytest()
126 assert result.ret != 0
127 result.stderr.fnmatch_lines(
128 ["*tox.ini: 'minversion' requires pytest-999.0, actual pytest-*"]
129 )
130
131 @pytest.mark.parametrize(
132 "section, name",
133 [
134 ("tool:pytest", "setup.cfg"),
135 ("pytest", "tox.ini"),
136 ("pytest", "pytest.ini"),
137 ("pytest", ".pytest.ini"),
138 ],
139 )
140 def test_ini_names(self, pytester: Pytester, name, section) -> None:
141 pytester.path.joinpath(name).write_text(
142 textwrap.dedent(
143 f"""
144 [{section}]
145 minversion = 3.36
146 """
147 ),
148 encoding="utf-8",
149 )
150 config = pytester.parseconfig()
151 assert config.getini("minversion") == "3.36"
152
153 @pytest.mark.parametrize("name", ["pytest.toml", ".pytest.toml"])
154 def test_toml_config_names(self, pytester: Pytester, name: str) -> None:
155 pytester.path.joinpath(name).write_text(
156 textwrap.dedent(
157 """
158 [pytest]
159 minversion = "3.36"
160 """
161 ),
162 encoding="utf-8",
163 )
164 config = pytester.parseconfig()
165 assert config.getini("minversion") == "3.36"
166
167 def test_pyproject_toml(self, pytester: Pytester) -> None:
168 pyproject_toml = pytester.makepyprojecttoml(
169 """
170 [tool.pytest.ini_options]
171 minversion = "1.0"
172 """
173 )
174 config = pytester.parseconfig()
175 assert config.inipath == pyproject_toml
176 assert config.getini("minversion") == "1.0"
177
178 def test_empty_pyproject_toml(self, pytester: Pytester) -> None:
179 """An empty pyproject.toml is considered as config if no other option is found."""
180 pyproject_toml = pytester.makepyprojecttoml("")
181 config = pytester.parseconfig()
182 assert config.inipath == pyproject_toml
183
184 def test_empty_pyproject_toml_found_many(self, pytester: Pytester) -> None:
185 """
186 In case we find multiple pyproject.toml files in our search, without a [tool.pytest]
187 table and without finding other candidates, the closest to where we started wins.
188 """
189 pytester.makefile(
190 ".toml",
191 **{
192 "pyproject": "",
193 "foo/pyproject": "",
194 "foo/bar/pyproject": "",
195 },
196 )
197 config = pytester.parseconfig(pytester.path / "foo/bar")
198 assert config.inipath == pytester.path / "foo/bar/pyproject.toml"
199
200 def test_pytest_toml(self, pytester: Pytester) -> None:
201 pytest_toml = pytester.path.joinpath("pytest.toml")
202 pytest_toml = pytester.maketoml(
203 """
204 [pytest]
205 minversion = "1.0"
206 """
207 )
208 config = pytester.parseconfig()
209 assert config.inipath == pytest_toml
210 assert config.getini("minversion") == "1.0"
211
212 @pytest.mark.parametrize("name", ["pytest.toml", ".pytest.toml"])
213 def test_empty_pytest_toml(self, pytester: Pytester, name: str) -> None:
214 """An empty pytest.toml is considered as config if no other option is found."""
215 pytest_toml = pytester.path / name
216 pytest_toml.write_text("", encoding="utf-8")
217 config = pytester.parseconfig()
218 assert config.inipath == pytest_toml
219
220 def test_pytest_toml_trumps_pyproject_toml(self, pytester: Pytester) -> None:
221 """A pytest.toml always takes precedence over a pyproject.toml file."""
222 pytester.makepyprojecttoml(
223 """
224 [tool.pytest]
225 minversion = "1.0"
226 """
227 )
228 pytest_toml = pytester.maketoml(
229 """
230 [pytest]
231 minversion = "2.0"
232 """
233 )
234 config = pytester.parseconfig()
235 assert config.inipath == pytest_toml
236 assert config.getini("minversion") == "2.0"
237
238 def test_pytest_toml_trumps_pytest_ini(self, pytester: Pytester) -> None:
239 """A pytest.toml always takes precedence over a pytest.ini file."""
240 pytester.makeini(
241 """
242 [pytest]
243 minversion = 1.0
244 """,
245 )
246 pytest_toml = pytester.maketoml(
247 """
248 [pytest]
249 minversion = "2.0"
250 """,
251 )
252 config = pytester.parseconfig()
253 assert config.inipath == pytest_toml
254 assert config.getini("minversion") == "2.0"
255
256 def test_dot_pytest_toml_trumps_pytest_ini(self, pytester: Pytester) -> None:
257 """A .pytest.toml always takes precedence over a pytest.ini file."""
258 pytester.makeini(
259 """
260 [pytest]
261 minversion = 1.0
262 """,
263 )
264 pytest_toml = pytester.maketoml(
265 """
266 [pytest]
267 minversion = "2.0"
268 """
269 )
270 config = pytester.parseconfig()
271 assert config.inipath == pytest_toml
272 assert config.getini("minversion") == "2.0"
273
274 def test_pytest_ini_trumps_pyproject_toml(self, pytester: Pytester) -> None:
275 """A pytest.ini always take precedence over a pyproject.toml file."""
276 pytester.makepyprojecttoml(
277 """
278 [tool.pytest]
279 minversion = "1.0"
280 """
281 )
282 pytest_ini = pytester.makefile(".ini", pytest="")
283 config = pytester.parseconfig()
284 assert config.inipath == pytest_ini
285
286 def test_toxini_before_lower_pytestini(self, pytester: Pytester) -> None:
287 sub = pytester.mkdir("sub")
288 sub.joinpath("tox.ini").write_text(
289 textwrap.dedent(
290 """
291 [pytest]
292 minversion = 2.0
293 """
294 ),
295 encoding="utf-8",
296 )
297 pytester.path.joinpath("pytest.ini").write_text(
298 textwrap.dedent(
299 """
300 [pytest]
301 minversion = 1.5
302 """
303 ),
304 encoding="utf-8",
305 )
306 config = pytester.parseconfigure(sub)
307 assert config.getini("minversion") == "2.0"
308
309 def test_ini_parse_error(self, pytester: Pytester) -> None:
310 pytester.path.joinpath("pytest.ini").write_text(
311 "addopts = -x", encoding="utf-8"
312 )
313 result = pytester.runpytest()
314 assert result.ret != 0
315 result.stderr.fnmatch_lines("ERROR: *pytest.ini:1: no section header defined")
316
317 def test_toml_parse_error(self, pytester: Pytester) -> None:
318 pytester.makepyprojecttoml(
319 """
320 \\"
321 """
322 )
323 result = pytester.runpytest()
324 assert result.ret != 0
325 result.stderr.fnmatch_lines("ERROR: *pyproject.toml: Invalid statement*")
326
327 def test_pytest_toml_parse_error(self, pytester: Pytester) -> None:
328 pytester.path.joinpath("pytest.toml").write_text(
329 """
330 \\"
331 """,
332 encoding="utf-8",
333 )
334 result = pytester.runpytest()
335 assert result.ret != 0
336 result.stderr.fnmatch_lines("ERROR: *pytest.toml: Invalid statement*")
337
338 def test_confcutdir_default_without_configfile(self, pytester: Pytester) -> None:
339 # If --confcutdir is not specified, and there is no configfile, default
340 # to the rootpath.
341 sub = pytester.mkdir("sub")
342 os.chdir(sub)
343 config = pytester.parseconfigure()
344 assert config.pluginmanager._confcutdir == sub
345
346 def test_confcutdir_default_with_configfile(self, pytester: Pytester) -> None:
347 # If --confcutdir is not specified, and there is a configfile, default
348 # to the configfile's directory.
349 pytester.makeini("[pytest]")
350 sub = pytester.mkdir("sub")
351 os.chdir(sub)
352 config = pytester.parseconfigure()
353 assert config.pluginmanager._confcutdir == pytester.path
354
355 @pytest.mark.xfail(reason="probably not needed")
356 def test_confcutdir(self, pytester: Pytester) -> None:
357 sub = pytester.mkdir("sub")
358 os.chdir(sub)
359 pytester.makeini(
360 """
361 [pytest]
362 addopts = --qwe
363 """
364 )
365 result = pytester.inline_run("--confcutdir=.")
366 assert result.ret == 0
367
368 @pytest.mark.parametrize(
369 "ini_file_text, invalid_keys, warning_output, exception_text",
370 [
371 pytest.param(
372 """
373 [pytest]
374 unknown_ini = value1
375 another_unknown_ini = value2
376 """,
377 ["unknown_ini", "another_unknown_ini"],
378 [
379 "=*= warnings summary =*=",
380 "*PytestConfigWarning:*Unknown config option: another_unknown_ini",
381 "*PytestConfigWarning:*Unknown config option: unknown_ini",
382 ],
383 "Unknown config option: another_unknown_ini",
384 id="2-unknowns",
385 ),
386 pytest.param(
387 """
388 [pytest]
389 unknown_ini = value1
390 minversion = 5.0.0
391 """,
392 ["unknown_ini"],
393 [
394 "=*= warnings summary =*=",
395 "*PytestConfigWarning:*Unknown config option: unknown_ini",
396 ],
397 "Unknown config option: unknown_ini",
398 id="1-unknown",
399 ),
400 pytest.param(
401 """
402 [some_other_header]
403 unknown_ini = value1
404 [pytest]
405 minversion = 5.0.0
406 """,
407 [],
408 [],
409 "",
410 id="unknown-in-other-header",
411 ),
412 pytest.param(
413 """
414 [pytest]
415 minversion = 5.0.0
416 """,
417 [],
418 [],
419 "",
420 id="no-unknowns",
421 ),
422 pytest.param(
423 """
424 [pytest]
425 conftest_ini_key = 1
426 """,
427 [],
428 [],
429 "",
430 id="1-known",
431 ),
432 ],
433 )
434 @pytest.mark.filterwarnings("default")
435 def test_invalid_config_options(
436 self,
437 pytester: Pytester,
438 ini_file_text,
439 invalid_keys,
440 warning_output,
441 exception_text,
442 ) -> None:
443 pytester.makeconftest(
444 """
445 def pytest_addoption(parser):
446 parser.addini("conftest_ini_key", "")
447 """
448 )
449 pytester.makepyfile("def test(): pass")
450 pytester.makeini(ini_file_text)
451
452 config = pytester.parseconfig()
453 assert sorted(config._get_unknown_ini_keys()) == sorted(invalid_keys)
454
455 result = pytester.runpytest()
456 result.stdout.fnmatch_lines(warning_output)
457
458 result = pytester.runpytest("--strict-config")
459 if exception_text:
460 result.stderr.fnmatch_lines("ERROR: " + exception_text)
461 assert result.ret == pytest.ExitCode.USAGE_ERROR
462 else:
463 result.stderr.no_fnmatch_line(exception_text)
464 assert result.ret == pytest.ExitCode.OK
465
466 @pytest.mark.filterwarnings("default")
467 def test_silence_unknown_key_warning(self, pytester: Pytester) -> None:
468 """Unknown config key warnings can be silenced using filterwarnings (#7620)"""
469 pytester.makeini(
470 """
471 [pytest]
472 filterwarnings =
473 ignore:Unknown config option:pytest.PytestConfigWarning
474 foobar=1
475 """
476 )
477 result = pytester.runpytest()
478 result.stdout.no_fnmatch_line("*PytestConfigWarning*")
479
480 @pytest.mark.parametrize(
481 "option",
482 [
483 "strict_config = true",
484 "strict = true",
485 "addopts = --strict-config",
486 ],
487 )
488 def test_strict_config_ini_option(self, pytester: Pytester, option: str) -> None:
489 """Test that strict_config and strict ini options enable strict config checking."""
490 pytester.makeini(
491 f"""
492 [pytest]
493 unknown_option = 1
494 {option}
495 """
496 )
497 result = pytester.runpytest()
498 result.stderr.fnmatch_lines("ERROR: Unknown config option: unknown_option")
499 assert result.ret == pytest.ExitCode.USAGE_ERROR
500
501 @pytest.mark.filterwarnings("default::pytest.PytestConfigWarning")
502 def test_disable_warnings_plugin_disables_config_warnings(
503 self, pytester: Pytester
504 ) -> None:
505 """Disabling 'warnings' plugin also disables config time warnings"""
506 pytester.makeconftest(
507 """
508 import pytest
509 def pytest_configure(config):
510 config.issue_config_time_warning(
511 pytest.PytestConfigWarning("custom config warning"),
512 stacklevel=2,
513 )
514 """
515 )
516 result = pytester.runpytest("-pno:warnings")
517 result.stdout.no_fnmatch_line("*PytestConfigWarning*")
518
519 @pytest.mark.parametrize(
520 "ini_file_text, plugin_version, exception_text",
521 [
522 pytest.param(
523 """
524 [pytest]
525 required_plugins = a z
526 """,
527 "1.5",
528 "Missing required plugins: a, z",
529 id="2-missing",
530 ),
531 pytest.param(
532 """
533 [pytest]
534 required_plugins = a z myplugin
535 """,
536 "1.5",
537 "Missing required plugins: a, z",
538 id="2-missing-1-ok",
539 ),
540 pytest.param(
541 """
542 [pytest]
543 required_plugins = myplugin
544 """,
545 "1.5",
546 None,
547 id="1-ok",
548 ),
549 pytest.param(
550 """
551 [pytest]
552 required_plugins = myplugin==1.5
553 """,
554 "1.5",
555 None,
556 id="1-ok-pin-exact",
557 ),
558 pytest.param(
559 """
560 [pytest]
561 required_plugins = myplugin>1.0,<2.0
562 """,
563 "1.5",
564 None,
565 id="1-ok-pin-loose",
566 ),
567 pytest.param(
568 """
569 [pytest]
570 required_plugins = myplugin
571 """,
572 "1.5a1",
573 None,
574 id="1-ok-prerelease",
575 ),
576 pytest.param(
577 """
578 [pytest]
579 required_plugins = myplugin==1.6
580 """,
581 "1.5",
582 "Missing required plugins: myplugin==1.6",
583 id="missing-version",
584 ),
585 pytest.param(
586 """
587 [pytest]
588 required_plugins = myplugin==1.6 other==1.0
589 """,
590 "1.5",
591 "Missing required plugins: myplugin==1.6, other==1.0",
592 id="missing-versions",
593 ),
594 pytest.param(
595 """
596 [some_other_header]
597 required_plugins = won't be triggered
598 [pytest]
599 """,
600 "1.5",
601 None,
602 id="invalid-header",
603 ),
604 ],
605 )
606 def test_missing_required_plugins(
607 self,
608 pytester: Pytester,
609 monkeypatch: MonkeyPatch,
610 ini_file_text: str,
611 plugin_version: str,
612 exception_text: str,
613 ) -> None:
614 """Check 'required_plugins' option with various settings.
615
616 This test installs a mock "myplugin-1.5" which is used in the parametrized test cases.
617 """
618
619 @dataclasses.dataclass
620 class DummyEntryPoint:
621 name: str
622 module: str
623 group: str = "pytest11"
624
625 def load(self):
626 return importlib.import_module(self.module)
627
628 entry_points = [
629 DummyEntryPoint("myplugin1", "myplugin1_module"),
630 ]
631
632 @dataclasses.dataclass
633 class DummyDist:
634 entry_points: object
635 files: object = ()
636 version: str = plugin_version
637
638 @property
639 def metadata(self):
640 return {"name": "myplugin"}
641
642 def my_dists():
643 return [DummyDist(entry_points)]
644
645 pytester.makepyfile(myplugin1_module="# my plugin module")
646 pytester.syspathinsert()
647
648 monkeypatch.setattr(importlib.metadata, "distributions", my_dists)
649 monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
650
651 pytester.makeini(ini_file_text)
652
653 if exception_text:
654 with pytest.raises(pytest.UsageError, match=exception_text):
655 pytester.parseconfig()
656 else:
657 pytester.parseconfig()
658
659 def test_early_config_cmdline(
660 self, pytester: Pytester, monkeypatch: MonkeyPatch
661 ) -> None:
662 """early_config contains options registered by third-party plugins.
663
664 This is a regression involving pytest-cov (and possibly others) introduced in #7700.
665 """
666 pytester.makepyfile(
667 myplugin="""
668 def pytest_addoption(parser):
669 parser.addoption('--foo', default=None, dest='foo')
670
671 def pytest_load_initial_conftests(early_config, parser, args):
672 assert early_config.known_args_namespace.foo == "1"
673 """
674 )
675 monkeypatch.setenv("PYTEST_PLUGINS", "myplugin")
676 pytester.syspathinsert()
677 result = pytester.runpytest("--foo=1")
678 result.stdout.fnmatch_lines("* no tests ran in *")
679
680 def test_args_source_args(self, pytester: Pytester):
681 config = pytester.parseconfig("--", "test_filename.py")
682 assert config.args_source == Config.ArgsSource.ARGS
683
684 def test_args_source_invocation_dir(self, pytester: Pytester):
685 config = pytester.parseconfig()
686 assert config.args_source == Config.ArgsSource.INVOCATION_DIR
687
688 def test_args_source_testpaths(self, pytester: Pytester):
689 pytester.makeini(
690 """
691 [pytest]
692 testpaths=*
693 """
694 )
695 config = pytester.parseconfig()
696 assert config.args_source == Config.ArgsSource.TESTPATHS
697
698
699 class TestConfigCmdlineParsing:
700 def test_parsing_again_fails(self, pytester: Pytester) -> None:
701 config = pytester.parseconfig()
702 with pytest.raises(AssertionError):
703 config.parse([])
704
705 def test_explicitly_specified_config_file_is_loaded(
706 self, pytester: Pytester
707 ) -> None:
708 pytester.makeconftest(
709 """
710 def pytest_addoption(parser):
711 parser.addini("custom", "")
712 """
713 )
714 pytester.makeini(
715 """
716 [pytest]
717 custom = 0
718 """
719 )
720 pytester.makefile(
721 ".ini",
722 custom="""
723 [pytest]
724 custom = 1
725 """,
726 )
727 config = pytester.parseconfig("-c", "custom.ini")
728 assert config.getini("custom") == "1"
729 config = pytester.parseconfig("--config-file", "custom.ini")
730 assert config.getini("custom") == "1"
731
732 pytester.makefile(
733 ".cfg",
734 custom_tool_pytest_section="""
735 [tool:pytest]
736 custom = 1
737 """,
738 )
739 config = pytester.parseconfig("-c", "custom_tool_pytest_section.cfg")
740 assert config.getini("custom") == "1"
741 config = pytester.parseconfig("--config-file", "custom_tool_pytest_section.cfg")
742 assert config.getini("custom") == "1"
743
744 pytester.makefile(
745 ".toml",
746 custom="""
747 [tool.pytest.ini_options]
748 custom = 1
749 value = [
750 ] # this is here on purpose, as it makes this an invalid '.ini' file
751 """,
752 )
753 config = pytester.parseconfig("-c", "custom.toml")
754 assert config.getini("custom") == "1"
755 config = pytester.parseconfig("--config-file", "custom.toml")
756 assert config.getini("custom") == "1"
757
758 def test_absolute_win32_path(self, pytester: Pytester) -> None:
759 temp_ini_file = pytester.makeini("[pytest]")
760 from os.path import normpath
761
762 temp_ini_file_norm = normpath(str(temp_ini_file))
763 ret = pytest.main(["-c", temp_ini_file_norm])
764 assert ret == ExitCode.NO_TESTS_COLLECTED
765 ret = pytest.main(["--config-file", temp_ini_file_norm])
766 assert ret == ExitCode.NO_TESTS_COLLECTED
767
768
769 class TestConfigAPI:
770 def test_config_trace(self, pytester: Pytester) -> None:
771 config = pytester.parseconfig()
772 values: list[str] = []
773 config.trace.root.setwriter(values.append)
774 config.trace("hello")
775 assert len(values) == 1
776 assert values[0] == "hello [config]\n"
777
778 def test_config_getoption_declared_option_name(self, pytester: Pytester) -> None:
779 pytester.makeconftest(
780 """
781 def pytest_addoption(parser):
782 parser.addoption("--hello", "-X", dest="hello")
783 """
784 )
785 config = pytester.parseconfig("--hello=this")
786 for x in ("hello", "--hello", "-X"):
787 assert config.getoption(x) == "this"
788 with pytest.raises(ValueError):
789 config.getoption("qweqwe")
790
791 config_novalue = pytester.parseconfig()
792 assert config_novalue.getoption("hello") is None
793 assert config_novalue.getoption("hello", default=1) is None
794 assert config_novalue.getoption("hello", default=1, skip=True) == 1
795
796 def test_config_getoption_undeclared_option_name(self, pytester: Pytester) -> None:
797 config = pytester.parseconfig()
798 with pytest.raises(ValueError):
799 config.getoption("x")
800 assert config.getoption("x", default=1) == 1
801 assert config.getoption("x", default=1, skip=True) == 1
802
803 def test_config_getoption_unicode(self, pytester: Pytester) -> None:
804 pytester.makeconftest(
805 """
806 def pytest_addoption(parser):
807 parser.addoption('--hello', type=str)
808 """
809 )
810 config = pytester.parseconfig("--hello=this")
811 assert config.getoption("hello") == "this"
812
813 def test_config_getvalueorskip(self, pytester: Pytester) -> None:
814 config = pytester.parseconfig()
815 with pytest.raises(pytest.skip.Exception):
816 config.getvalueorskip("hello")
817 verbose = config.getvalueorskip("verbose")
818 assert verbose == config.option.verbose
819
820 def test_config_getvalueorskip_None(self, pytester: Pytester) -> None:
821 pytester.makeconftest(
822 """
823 def pytest_addoption(parser):
824 parser.addoption("--hello")
825 """
826 )
827 config = pytester.parseconfig()
828 with pytest.raises(pytest.skip.Exception):
829 config.getvalueorskip("hello")
830
831 def test_getconftest_pathlist(self, pytester: Pytester, tmp_path: Path) -> None:
832 somepath = tmp_path.joinpath("x", "y", "z")
833 p = tmp_path.joinpath("conftest.py")
834 p.write_text(f"mylist = {['.', str(somepath)]}", encoding="utf-8")
835 config = pytester.parseconfigure(p)
836 assert config._getconftest_pathlist("notexist", path=tmp_path) is None
837 assert config._getconftest_pathlist("mylist", path=tmp_path) == [
838 tmp_path,
839 somepath,
840 ]
841
842 @pytest.mark.parametrize("maybe_type", ["not passed", "None", '"string"'])
843 def test_addini(self, pytester: Pytester, maybe_type: str) -> None:
844 if maybe_type == "not passed":
845 type_string = ""
846 else:
847 type_string = f", {maybe_type}"
848
849 pytester.makeconftest(
850 f"""
851 def pytest_addoption(parser):
852 parser.addini("myname", "my new ini value"{type_string})
853 """
854 )
855 pytester.makeini(
856 """
857 [pytest]
858 myname=hello
859 """
860 )
861 config = pytester.parseconfig()
862 val = config.getini("myname")
863 assert val == "hello"
864 with pytest.raises(ValueError):
865 config.getini("other")
866
867 @pytest.mark.parametrize("config_type", ["ini", "pyproject"])
868 def test_addini_paths(self, pytester: Pytester, config_type: str) -> None:
869 pytester.makeconftest(
870 """
871 def pytest_addoption(parser):
872 parser.addini("paths", "my new ini value", type="paths")
873 parser.addini("abc", "abc value")
874 """
875 )
876 if config_type == "ini":
877 inipath = pytester.makeini(
878 """
879 [pytest]
880 paths=hello world/sub.py
881 """
882 )
883 elif config_type == "pyproject":
884 inipath = pytester.makepyprojecttoml(
885 """
886 [tool.pytest.ini_options]
887 paths=["hello", "world/sub.py"]
888 """
889 )
890 config = pytester.parseconfig()
891 values = config.getini("paths")
892 assert len(values) == 2
893 assert values[0] == inipath.parent.joinpath("hello")
894 assert values[1] == inipath.parent.joinpath("world/sub.py")
895 with pytest.raises(ValueError):
896 config.getini("other")
897
898 def make_conftest_for_args(self, pytester: Pytester) -> None:
899 pytester.makeconftest(
900 """
901 def pytest_addoption(parser):
902 parser.addini("args", "new args", type="args")
903 parser.addini("a2", "", "args", default="1 2 3".split())
904 """
905 )
906
907 def test_addini_args_ini_files(self, pytester: Pytester) -> None:
908 self.make_conftest_for_args(pytester)
909 pytester.makeini(
910 """
911 [pytest]
912 args=123 "123 hello" "this"
913 """
914 )
915 self.check_config_args(pytester)
916
917 def test_addini_args_pyproject_toml(self, pytester: Pytester) -> None:
918 self.make_conftest_for_args(pytester)
919 pytester.makepyprojecttoml(
920 """
921 [tool.pytest.ini_options]
922 args = ["123", "123 hello", "this"]
923 """
924 )
925 self.check_config_args(pytester)
926
927 def check_config_args(self, pytester: Pytester) -> None:
928 config = pytester.parseconfig()
929 values = config.getini("args")
930 assert values == ["123", "123 hello", "this"]
931 values = config.getini("a2")
932 assert values == list("123")
933
934 def make_conftest_for_linelist(self, pytester: Pytester) -> None:
935 pytester.makeconftest(
936 """
937 def pytest_addoption(parser):
938 parser.addini("xy", "", type="linelist")
939 parser.addini("a2", "", "linelist")
940 """
941 )
942
943 def test_addini_linelist_ini_files(self, pytester: Pytester) -> None:
944 self.make_conftest_for_linelist(pytester)
945 pytester.makeini(
946 """
947 [pytest]
948 xy= 123 345
949 second line
950 """
951 )
952 self.check_config_linelist(pytester)
953
954 def test_addini_linelist_pprojecttoml(self, pytester: Pytester) -> None:
955 self.make_conftest_for_linelist(pytester)
956 pytester.makepyprojecttoml(
957 """
958 [tool.pytest.ini_options]
959 xy = ["123 345", "second line"]
960 """
961 )
962 self.check_config_linelist(pytester)
963
964 def check_config_linelist(self, pytester: Pytester) -> None:
965 config = pytester.parseconfig()
966 values = config.getini("xy")
967 assert len(values) == 2
968 assert values == ["123 345", "second line"]
969 values = config.getini("a2")
970 assert values == []
971
972 @pytest.mark.parametrize(
973 "str_val, bool_val", [("True", True), ("no", False), ("no-ini", True)]
974 )
975 def test_addini_bool(
976 self, pytester: Pytester, str_val: str, bool_val: bool
977 ) -> None:
978 pytester.makeconftest(
979 """
980 def pytest_addoption(parser):
981 parser.addini("strip", "", type="bool", default=True)
982 """
983 )
984 if str_val != "no-ini":
985 pytester.makeini(
986 f"""
987 [pytest]
988 strip={str_val}
989 """
990 )
991 config = pytester.parseconfig()
992 assert config.getini("strip") is bool_val
993
994 @pytest.mark.parametrize("str_val, int_val", [("10", 10), ("no-ini", 2)])
995 def test_addini_int(self, pytester: Pytester, str_val: str, int_val: bool) -> None:
996 pytester.makeconftest(
997 """
998 def pytest_addoption(parser):
999 parser.addini("ini_param", "", type="int", default=2)
1000 """
1001 )
1002 if str_val != "no-ini":
1003 pytester.makeini(
1004 f"""
1005 [pytest]
1006 ini_param={str_val}
1007 """
1008 )
1009 config = pytester.parseconfig()
1010 assert config.getini("ini_param") == int_val
1011
1012 def test_addini_int_invalid(self, pytester: Pytester) -> None:
1013 pytester.makeconftest(
1014 """
1015 def pytest_addoption(parser):
1016 parser.addini("ini_param", "", type="int", default=2)
1017 """
1018 )
1019 pytester.makepyprojecttoml(
1020 """
1021 [tool.pytest.ini_options]
1022 ini_param=["foo"]
1023 """
1024 )
1025 config = pytester.parseconfig()
1026 with pytest.raises(
1027 TypeError, match="Expected an int string for option ini_param"
1028 ):
1029 _ = config.getini("ini_param")
1030
1031 @pytest.mark.parametrize("str_val, float_val", [("10.5", 10.5), ("no-ini", 2.2)])
1032 def test_addini_float(
1033 self, pytester: Pytester, str_val: str, float_val: bool
1034 ) -> None:
1035 pytester.makeconftest(
1036 """
1037 def pytest_addoption(parser):
1038 parser.addini("ini_param", "", type="float", default=2.2)
1039 """
1040 )
1041 if str_val != "no-ini":
1042 pytester.makeini(
1043 f"""
1044 [pytest]
1045 ini_param={str_val}
1046 """
1047 )
1048 config = pytester.parseconfig()
1049 assert config.getini("ini_param") == float_val
1050
1051 def test_addini_float_invalid(self, pytester: Pytester) -> None:
1052 pytester.makeconftest(
1053 """
1054 def pytest_addoption(parser):
1055 parser.addini("ini_param", "", type="float", default=2.2)
1056 """
1057 )
1058 pytester.makepyprojecttoml(
1059 """
1060 [tool.pytest.ini_options]
1061 ini_param=["foo"]
1062 """
1063 )
1064 config = pytester.parseconfig()
1065 with pytest.raises(
1066 TypeError, match="Expected a float string for option ini_param"
1067 ):
1068 _ = config.getini("ini_param")
1069
1070 def test_addinivalue_line_existing(self, pytester: Pytester) -> None:
1071 pytester.makeconftest(
1072 """
1073 def pytest_addoption(parser):
1074 parser.addini("xy", "", type="linelist")
1075 """
1076 )
1077 pytester.makeini(
1078 """
1079 [pytest]
1080 xy= 123
1081 """
1082 )
1083 config = pytester.parseconfig()
1084 values = config.getini("xy")
1085 assert len(values) == 1
1086 assert values == ["123"]
1087 config.addinivalue_line("xy", "456")
1088 values = config.getini("xy")
1089 assert len(values) == 2
1090 assert values == ["123", "456"]
1091
1092 def test_addinivalue_line_new(self, pytester: Pytester) -> None:
1093 pytester.makeconftest(
1094 """
1095 def pytest_addoption(parser):
1096 parser.addini("xy", "", type="linelist")
1097 """
1098 )
1099 config = pytester.parseconfig()
1100 assert not config.getini("xy")
1101 config.addinivalue_line("xy", "456")
1102 values = config.getini("xy")
1103 assert len(values) == 1
1104 assert values == ["456"]
1105 config.addinivalue_line("xy", "123")
1106 values = config.getini("xy")
1107 assert len(values) == 2
1108 assert values == ["456", "123"]
1109
1110 def test_addini_default_values(self, pytester: Pytester) -> None:
1111 """Tests the default values for configuration based on
1112 config type
1113 """
1114 pytester.makeconftest(
1115 """
1116 def pytest_addoption(parser):
1117 parser.addini("linelist1", "", type="linelist")
1118 parser.addini("paths1", "", type="paths")
1119 parser.addini("pathlist1", "", type="pathlist")
1120 parser.addini("args1", "", type="args")
1121 parser.addini("bool1", "", type="bool")
1122 parser.addini("string1", "", type="string")
1123 parser.addini("none_1", "", type="linelist", default=None)
1124 parser.addini("none_2", "", default=None)
1125 parser.addini("no_type", "")
1126 """
1127 )
1128
1129 config = pytester.parseconfig()
1130 # default for linelist, paths, pathlist and args is []
1131 value = config.getini("linelist1")
1132 assert value == []
1133 value = config.getini("paths1")
1134 assert value == []
1135 value = config.getini("pathlist1")
1136 assert value == []
1137 value = config.getini("args1")
1138 assert value == []
1139 # default for bool is False
1140 value = config.getini("bool1")
1141 assert value is False
1142 # default for string is ""
1143 value = config.getini("string1")
1144 assert value == ""
1145 # should return None if None is explicitly set as default value
1146 # irrespective of the type argument
1147 value = config.getini("none_1")
1148 assert value is None
1149 value = config.getini("none_2")
1150 assert value is None
1151 # in case no type is provided and no default set
1152 # treat it as string and default value will be ""
1153 value = config.getini("no_type")
1154 assert value == ""
1155
1156 def test_addini_with_aliases(self, pytester: Pytester) -> None:
1157 """Test that ini options can have aliases."""
1158 pytester.makeconftest(
1159 """
1160 def pytest_addoption(parser):
1161 parser.addini("new_name", "my option", aliases=["old_name"])
1162 """
1163 )
1164 pytester.makeini(
1165 """
1166 [pytest]
1167 old_name = hello
1168 """
1169 )
1170 config = pytester.parseconfig()
1171 # Should be able to access via canonical name.
1172 assert config.getini("new_name") == "hello"
1173 # Should also be able to access via alias.
1174 assert config.getini("old_name") == "hello"
1175
1176 def test_addini_aliases_with_canonical_in_file(self, pytester: Pytester) -> None:
1177 """Test that canonical name takes precedence over alias in configuration file."""
1178 pytester.makeconftest(
1179 """
1180 def pytest_addoption(parser):
1181 parser.addini("new_name", "my option", aliases=["old_name"])
1182 """
1183 )
1184 pytester.makeini(
1185 """
1186 [pytest]
1187 old_name = from_alias
1188 new_name = from_canonical
1189 """
1190 )
1191 config = pytester.parseconfig()
1192 # Canonical name should take precedence.
1193 assert config.getini("new_name") == "from_canonical"
1194 assert config.getini("old_name") == "from_canonical"
1195
1196 def test_addini_aliases_multiple(self, pytester: Pytester) -> None:
1197 """Test that ini option can have multiple aliases."""
1198 pytester.makeconftest(
1199 """
1200 def pytest_addoption(parser):
1201 parser.addini("current_name", "my option", aliases=["old_name", "legacy_name"])
1202 """
1203 )
1204 pytester.makeini(
1205 """
1206 [pytest]
1207 old_name = value1
1208 """
1209 )
1210 config = pytester.parseconfig()
1211 assert config.getini("current_name") == "value1"
1212 assert config.getini("old_name") == "value1"
1213 assert config.getini("legacy_name") == "value1"
1214
1215 def test_addini_aliases_with_override_of_old(self, pytester: Pytester) -> None:
1216 """Test that aliases work with --override-ini -- ini sets old."""
1217 pytester.makeconftest(
1218 """
1219 def pytest_addoption(parser):
1220 parser.addini("new_name", "my option", aliases=["old_name"])
1221 """
1222 )
1223 pytester.makeini(
1224 """
1225 [pytest]
1226 old_name = from_file
1227 """
1228 )
1229 # Override using alias.
1230 config = pytester.parseconfig("-o", "old_name=overridden")
1231 assert config.getini("new_name") == "overridden"
1232 assert config.getini("old_name") == "overridden"
1233
1234 # Override using canonical name.
1235 config = pytester.parseconfig("-o", "new_name=overridden2")
1236 assert config.getini("new_name") == "overridden2"
1237
1238 def test_addini_aliases_with_override_of_new(self, pytester: Pytester) -> None:
1239 """Test that aliases work with --override-ini -- ini sets new."""
1240 pytester.makeconftest(
1241 """
1242 def pytest_addoption(parser):
1243 parser.addini("new_name", "my option", aliases=["old_name"])
1244 """
1245 )
1246 pytester.makeini(
1247 """
1248 [pytest]
1249 new_name = from_file
1250 """
1251 )
1252 # Override using alias.
1253 config = pytester.parseconfig("-o", "old_name=overridden")
1254 assert config.getini("new_name") == "overridden"
1255 assert config.getini("old_name") == "overridden"
1256
1257 # Override using canonical name.
1258 config = pytester.parseconfig("-o", "new_name=overridden2")
1259 assert config.getini("new_name") == "overridden2"
1260
1261 def test_addini_aliases_with_types(self, pytester: Pytester) -> None:
1262 """Test that aliases work with different types."""
1263 pytester.makeconftest(
1264 """
1265 def pytest_addoption(parser):
1266 parser.addini("mylist", "list option", type="linelist", aliases=["oldlist"])
1267 parser.addini("mybool", "bool option", type="bool", aliases=["oldbool"])
1268 """
1269 )
1270 pytester.makeini(
1271 """
1272 [pytest]
1273 oldlist = line1
1274 line2
1275 oldbool = true
1276 """
1277 )
1278 config = pytester.parseconfig()
1279 assert config.getini("mylist") == ["line1", "line2"]
1280 assert config.getini("oldlist") == ["line1", "line2"]
1281 assert config.getini("mybool") is True
1282 assert config.getini("oldbool") is True
1283
1284 def test_addini_aliases_conflict_error(self, pytester: Pytester) -> None:
1285 """Test that registering an alias that conflicts with an existing option raises an error."""
1286 pytester.makeconftest(
1287 """
1288 def pytest_addoption(parser):
1289 parser.addini("existing", "first option")
1290
1291 try:
1292 parser.addini("new_option", "second option", aliases=["existing"])
1293 except ValueError as e:
1294 assert "alias 'existing' conflicts with existing configuration option" in str(e)
1295 else:
1296 assert False, "Should have raised ValueError"
1297 """
1298 )
1299 pytester.parseconfig()
1300
1301 def test_addini_aliases_duplicate_error(self, pytester: Pytester) -> None:
1302 """Test that registering the same alias twice raises an error."""
1303 pytester.makeconftest(
1304 """
1305 def pytest_addoption(parser):
1306 parser.addini("option1", "first option", aliases=["shared_alias"])
1307 try:
1308 parser.addini("option2", "second option", aliases=["shared_alias"])
1309 raise AssertionError("Should have raised ValueError")
1310 except ValueError as e:
1311 assert "'shared_alias' is already an alias of 'option1'" in str(e)
1312 """
1313 )
1314 pytester.parseconfig()
1315
1316 @pytest.mark.parametrize(
1317 "type, expected",
1318 [
1319 pytest.param(None, "", id="None"),
1320 pytest.param("string", "", id="string"),
1321 pytest.param("paths", [], id="paths"),
1322 pytest.param("pathlist", [], id="pathlist"),
1323 pytest.param("args", [], id="args"),
1324 pytest.param("linelist", [], id="linelist"),
1325 pytest.param("bool", False, id="bool"),
1326 ],
1327 )
1328 def test_get_ini_default_for_type(self, type: Any, expected: Any) -> None:
1329 assert get_ini_default_for_type(type) == expected
1330
1331 def test_confcutdir_check_isdir(self, pytester: Pytester) -> None:
1332 """Give an error if --confcutdir is not a valid directory (#2078)"""
1333 exp_match = r"^--confcutdir must be a directory, given: "
1334 with pytest.raises(pytest.UsageError, match=exp_match):
1335 pytester.parseconfig("--confcutdir", pytester.path.joinpath("file"))
1336 with pytest.raises(pytest.UsageError, match=exp_match):
1337 pytester.parseconfig("--confcutdir", pytester.path.joinpath("nonexistent"))
1338
1339 p = pytester.mkdir("dir")
1340 config = pytester.parseconfig("--confcutdir", p)
1341 assert config.getoption("confcutdir") == str(p)
1342
1343 @pytest.mark.parametrize(
1344 "names, expected",
1345 [
1346 # dist-info based distributions root are files as will be put in PYTHONPATH
1347 (["bar.py"], ["bar"]),
1348 (["foo/bar.py"], ["bar"]),
1349 (["foo/bar.pyc"], []),
1350 (["foo/__init__.py"], ["foo"]),
1351 (["bar/__init__.py", "xz.py"], ["bar", "xz"]),
1352 (["setup.py"], []),
1353 # egg based distributions root contain the files from the dist root
1354 (["src/bar/__init__.py"], ["bar"]),
1355 (["src/bar/__init__.py", "setup.py"], ["bar"]),
1356 (["source/python/bar/__init__.py", "setup.py"], ["bar"]),
1357 # editable installation finder modules
1358 (["__editable___xyz_finder.py"], []),
1359 (["bar/__init__.py", "__editable___xyz_finder.py"], ["bar"]),
1360 ],
1361 )
1362 def test_iter_rewritable_modules(self, names, expected) -> None:
1363 assert list(_iter_rewritable_modules(names)) == expected
1364
1365 def test_add_cleanup(self, pytester: Pytester) -> None:
1366 config = Config.fromdictargs({}, [])
1367 config._do_configure()
1368 report = []
1369
1370 class MyError(BaseException):
1371 pass
1372
1373 @config.add_cleanup
1374 def cleanup_last():
1375 report.append("cleanup_last")
1376
1377 @config.add_cleanup
1378 def raise_2():
1379 report.append("raise_2")
1380 raise MyError("raise_2")
1381
1382 @config.add_cleanup
1383 def raise_1():
1384 report.append("raise_1")
1385 raise MyError("raise_1")
1386
1387 @config.add_cleanup
1388 def cleanup_first():
1389 report.append("cleanup_first")
1390
1391 with pytest.raises(MyError, match=r"raise_2"):
1392 config._ensure_unconfigure()
1393
1394 assert report == ["cleanup_first", "raise_1", "raise_2", "cleanup_last"]
1395
1396
1397 class TestConfigFromdictargs:
1398 def test_basic_behavior(self, _sys_snapshot) -> None:
1399 option_dict = {"verbose": 444, "foo": "bar", "capture": "no"}
1400 args = ["a", "b"]
1401
1402 config = Config.fromdictargs(option_dict, args)
1403 with pytest.raises(AssertionError):
1404 config.parse(["should refuse to parse again"])
1405 assert config.option.verbose == 444
1406 assert config.option.foo == "bar"
1407 assert config.option.capture == "no"
1408 assert config.args == args
1409
1410 def test_invocation_params_args(self, _sys_snapshot) -> None:
1411 """Show that fromdictargs can handle args in their "orig" format"""
1412 option_dict: dict[str, object] = {}
1413 args = ["-vvvv", "-s", "a", "b"]
1414
1415 config = Config.fromdictargs(option_dict, args)
1416 assert config.args == ["a", "b"]
1417 assert config.invocation_params.args == tuple(args)
1418 assert config.option.verbose == 4
1419 assert config.option.capture == "no"
1420
1421 def test_inifilename(self, tmp_path: Path) -> None:
1422 d1 = tmp_path.joinpath("foo")
1423 d1.mkdir()
1424 p1 = d1.joinpath("bar.ini")
1425 p1.touch()
1426 p1.write_text(
1427 textwrap.dedent(
1428 """\
1429 [pytest]
1430 name = value
1431 """
1432 ),
1433 encoding="utf-8",
1434 )
1435
1436 inifilename = "../../foo/bar.ini"
1437 option_dict = {"inifilename": inifilename, "capture": "no"}
1438
1439 cwd = tmp_path.joinpath("a/b")
1440 cwd.mkdir(parents=True)
1441 p2 = cwd.joinpath("pytest.ini")
1442 p2.touch()
1443 p2.write_text(
1444 textwrap.dedent(
1445 """\
1446 [pytest]
1447 name = wrong-value
1448 should_not_be_set = true
1449 """
1450 ),
1451 encoding="utf-8",
1452 )
1453 with MonkeyPatch.context() as mp:
1454 mp.chdir(cwd)
1455 config = Config.fromdictargs(option_dict, [])
1456 inipath = absolutepath(inifilename)
1457
1458 assert config.args == [str(cwd)]
1459 assert config.option.inifilename == inifilename
1460 assert config.option.capture == "no"
1461
1462 # this indicates this is the file used for getting configuration values
1463 assert config.inipath == inipath
1464 assert config._inicfg.get("name") == ConfigValue(
1465 "value", origin="file", mode="ini"
1466 )
1467 assert config._inicfg.get("should_not_be_set") is None
1468
1469
1470 def test_options_on_small_file_do_not_blow_up(pytester: Pytester) -> None:
1471 def runfiletest(opts: Sequence[str]) -> None:
1472 reprec = pytester.inline_run(*opts)
1473 passed, skipped, failed = reprec.countoutcomes()
1474 assert failed == 2
1475 assert skipped == passed == 0
1476
1477 path = str(
1478 pytester.makepyfile(
1479 """
1480 def test_f1(): assert 0
1481 def test_f2(): assert 0
1482 """
1483 )
1484 )
1485
1486 runfiletest([path])
1487 runfiletest(["-l", path])
1488 runfiletest(["-s", path])
1489 runfiletest(["--tb=no", path])
1490 runfiletest(["--tb=short", path])
1491 runfiletest(["--tb=long", path])
1492 runfiletest(["--fulltrace", path])
1493 runfiletest(["--traceconfig", path])
1494 runfiletest(["-v", path])
1495 runfiletest(["-v", "-v", path])
1496
1497
1498 def test_preparse_ordering_with_setuptools(
1499 pytester: Pytester, monkeypatch: MonkeyPatch
1500 ) -> None:
1501 monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
1502
1503 class EntryPoint:
1504 name = "mytestplugin"
1505 group = "pytest11"
1506
1507 def load(self):
1508 class PseudoPlugin:
1509 x = 42
1510
1511 return PseudoPlugin()
1512
1513 class Dist:
1514 files = ()
1515 metadata = {"name": "foo"}
1516 entry_points = (EntryPoint(),)
1517
1518 def my_dists():
1519 return (Dist,)
1520
1521 monkeypatch.setattr(importlib.metadata, "distributions", my_dists)
1522 pytester.makeconftest(
1523 """
1524 pytest_plugins = "mytestplugin",
1525 """
1526 )
1527 monkeypatch.setenv("PYTEST_PLUGINS", "mytestplugin")
1528 config = pytester.parseconfig()
1529 plugin = config.pluginmanager.getplugin("mytestplugin")
1530 assert plugin.x == 42
1531
1532
1533 def test_setuptools_importerror_issue1479(
1534 pytester: Pytester, monkeypatch: MonkeyPatch
1535 ) -> None:
1536 monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
1537
1538 class DummyEntryPoint:
1539 name = "mytestplugin"
1540 group = "pytest11"
1541
1542 def load(self):
1543 raise ImportError("Don't hide me!")
1544
1545 class Distribution:
1546 version = "1.0"
1547 files = ("foo.txt",)
1548 metadata = {"name": "foo"}
1549 entry_points = (DummyEntryPoint(),)
1550
1551 def distributions():
1552 return (Distribution(),)
1553
1554 monkeypatch.setattr(importlib.metadata, "distributions", distributions)
1555 with pytest.raises(ImportError):
1556 pytester.parseconfig()
1557
1558
1559 def test_importlib_metadata_broken_distribution(
1560 pytester: Pytester, monkeypatch: MonkeyPatch
1561 ) -> None:
1562 """Integration test for broken distributions with 'files' metadata being None (#5389)"""
1563 monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
1564
1565 class DummyEntryPoint:
1566 name = "mytestplugin"
1567 group = "pytest11"
1568
1569 def load(self):
1570 return object()
1571
1572 class Distribution:
1573 version = "1.0"
1574 files = None
1575 metadata = {"name": "foo"}
1576 entry_points = (DummyEntryPoint(),)
1577
1578 def distributions():
1579 return (Distribution(),)
1580
1581 monkeypatch.setattr(importlib.metadata, "distributions", distributions)
1582 pytester.parseconfig()
1583
1584
1585 @pytest.mark.parametrize("block_it", [True, False])
1586 def test_plugin_preparse_prevents_setuptools_loading(
1587 pytester: Pytester, monkeypatch: MonkeyPatch, block_it: bool
1588 ) -> None:
1589 monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
1590
1591 plugin_module_placeholder = object()
1592
1593 class DummyEntryPoint:
1594 name = "mytestplugin"
1595 group = "pytest11"
1596
1597 def load(self):
1598 return plugin_module_placeholder
1599
1600 class Distribution:
1601 version = "1.0"
1602 files = ("foo.txt",)
1603 metadata = {"name": "foo"}
1604 entry_points = (DummyEntryPoint(),)
1605
1606 def distributions():
1607 return (Distribution(),)
1608
1609 monkeypatch.setattr(importlib.metadata, "distributions", distributions)
1610 args = ("-p", "no:mytestplugin") if block_it else ()
1611 config = pytester.parseconfig(*args)
1612 config.pluginmanager.import_plugin("mytestplugin")
1613 if block_it:
1614 assert "mytestplugin" not in sys.modules
1615 assert config.pluginmanager.get_plugin("mytestplugin") is None
1616 else:
1617 assert (
1618 config.pluginmanager.get_plugin("mytestplugin") is plugin_module_placeholder
1619 )
1620
1621
1622 @pytest.mark.parametrize("disable_plugin_method", ["env_var", "flag", ""])
1623 @pytest.mark.parametrize("enable_plugin_method", ["env_var", "flag", ""])
1624 def test_disable_plugin_autoload(
1625 pytester: Pytester,
1626 monkeypatch: MonkeyPatch,
1627 enable_plugin_method: str,
1628 disable_plugin_method: str,
1629 ) -> None:
1630 class DummyEntryPoint:
1631 project_name = name = "mytestplugin"
1632 group = "pytest11"
1633 version = "1.0"
1634
1635 def load(self):
1636 return sys.modules[self.name]
1637
1638 class Distribution:
1639 metadata = {"name": "foo"}
1640 entry_points = (DummyEntryPoint(),)
1641 files = ()
1642
1643 class PseudoPlugin:
1644 x = 42
1645
1646 attrs_used = []
1647
1648 def __getattr__(self, name):
1649 assert name in ("__loader__", "__spec__")
1650 self.attrs_used.append(name)
1651 return object()
1652
1653 def distributions():
1654 return (Distribution(),)
1655
1656 parse_args: list[str] = []
1657
1658 if disable_plugin_method == "env_var":
1659 monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")
1660 elif disable_plugin_method == "flag":
1661 monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD")
1662 parse_args.append("--disable-plugin-autoload")
1663 else:
1664 assert disable_plugin_method == ""
1665 monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD")
1666
1667 if enable_plugin_method == "env_var":
1668 monkeypatch.setenv("PYTEST_PLUGINS", "mytestplugin")
1669 elif enable_plugin_method == "flag":
1670 parse_args.extend(["-p", "mytestplugin"])
1671 else:
1672 assert enable_plugin_method == ""
1673
1674 monkeypatch.setattr(importlib.metadata, "distributions", distributions)
1675 monkeypatch.setitem(sys.modules, "mytestplugin", PseudoPlugin())
1676 config = pytester.parseconfig(*parse_args)
1677
1678 has_loaded = config.pluginmanager.get_plugin("mytestplugin") is not None
1679 # it should load if it's enabled, or we haven't disabled autoloading
1680 assert has_loaded == (bool(enable_plugin_method) or not disable_plugin_method)
1681
1682 # The reason for the discrepancy between 'has_loaded' and __loader__ being accessed
1683 # appears to be the monkeypatching of importlib.metadata.distributions; where
1684 # files being empty means that _mark_plugins_for_rewrite doesn't find the plugin.
1685 # But enable_method==flag ends up in mark_rewrite being called and __loader__
1686 # being accessed.
1687 assert ("__loader__" in PseudoPlugin.attrs_used) == (
1688 has_loaded
1689 and not (enable_plugin_method in ("env_var", "") and not disable_plugin_method)
1690 )
1691
1692 # __spec__ is accessed in AssertionRewritingHook.exec_module, which would be
1693 # eventually called if we did a full pytest run; but it's only accessed with
1694 # enable_plugin_method=="env_var" because that will early-load it.
1695 # Except when autoloads aren't disabled, in which case PytestPluginManager.import_plugin
1696 # bails out before importing it.. because it knows it'll be loaded later?
1697 # The above seems a bit weird, but I *think* it's true.
1698 if platform.python_implementation() != "PyPy":
1699 assert ("__spec__" in PseudoPlugin.attrs_used) == bool(
1700 enable_plugin_method == "env_var" and disable_plugin_method
1701 )
1702 # __spec__ is present when testing locally on pypy, but not in CI ????
1703
1704
1705 def test_plugin_loading_order(pytester: Pytester) -> None:
1706 """Test order of plugin loading with `-p`."""
1707 p1 = pytester.makepyfile(
1708 """
1709 def test_terminal_plugin(request):
1710 import myplugin
1711 assert myplugin.terminal_plugin == [False, True]
1712 """,
1713 myplugin="""
1714 terminal_plugin = []
1715
1716 def pytest_configure(config):
1717 terminal_plugin.append(bool(config.pluginmanager.get_plugin("terminalreporter")))
1718
1719 def pytest_sessionstart(session):
1720 config = session.config
1721 terminal_plugin.append(bool(config.pluginmanager.get_plugin("terminalreporter")))
1722 """,
1723 )
1724 pytester.syspathinsert()
1725 result = pytester.runpytest("-p", "myplugin", str(p1))
1726 assert result.ret == 0
1727
1728
1729 def test_invalid_options_show_extra_information(pytester: Pytester) -> None:
1730 """Display extra information when pytest exits due to unrecognized
1731 options in the command-line."""
1732 pytester.makeini(
1733 """
1734 [pytest]
1735 addopts = --invalid-option
1736 """
1737 )
1738 result = pytester.runpytest()
1739 result.stderr.fnmatch_lines(
1740 [
1741 "*error: unrecognized arguments: --invalid-option*",
1742 "* inifile: {}*".format(pytester.path.joinpath("tox.ini")),
1743 f"* rootdir: {pytester.path}*",
1744 ]
1745 )
1746
1747
1748 @pytest.mark.parametrize(
1749 "args",
1750 [
1751 ["dir1", "dir2", "-v"],
1752 ["dir1", "-v", "dir2"],
1753 ["dir2", "-v", "dir1"],
1754 ["-v", "dir2", "dir1"],
1755 ],
1756 )
1757 def test_consider_args_after_options_for_rootdir(
1758 pytester: Pytester, args: list[str]
1759 ) -> None:
1760 """
1761 Consider all arguments in the command-line for rootdir
1762 discovery, even if they happen to occur after an option. #949
1763 """
1764 # replace "dir1" and "dir2" from "args" into their real directory
1765 root = pytester.mkdir("myroot")
1766 d1 = root.joinpath("dir1")
1767 d1.mkdir()
1768 d2 = root.joinpath("dir2")
1769 d2.mkdir()
1770 for i, arg in enumerate(args):
1771 if arg == "dir1":
1772 args[i] = str(d1)
1773 elif arg == "dir2":
1774 args[i] = str(d2)
1775 with MonkeyPatch.context() as mp:
1776 mp.chdir(root)
1777 result = pytester.runpytest(*args)
1778 result.stdout.fnmatch_lines(["*rootdir: *myroot"])
1779
1780
1781 def test_toolongargs_issue224(pytester: Pytester) -> None:
1782 result = pytester.runpytest("-m", "hello" * 500)
1783 assert result.ret == ExitCode.NO_TESTS_COLLECTED
1784
1785
1786 def test_config_in_subdirectory_colon_command_line_issue2148(
1787 pytester: Pytester,
1788 ) -> None:
1789 conftest_source = """
1790 def pytest_addoption(parser):
1791 parser.addini('foo', 'foo')
1792 """
1793
1794 pytester.makefile(
1795 ".ini",
1796 **{"pytest": "[pytest]\nfoo = root", "subdir/pytest": "[pytest]\nfoo = subdir"},
1797 )
1798
1799 pytester.makepyfile(
1800 **{
1801 "conftest": conftest_source,
1802 "subdir/conftest": conftest_source,
1803 "subdir/test_foo": """\
1804 def test_foo(pytestconfig):
1805 assert pytestconfig.getini('foo') == 'subdir'
1806 """,
1807 }
1808 )
1809
1810 result = pytester.runpytest("subdir/test_foo.py::test_foo")
1811 assert result.ret == 0
1812
1813
1814 def test_notify_exception(pytester: Pytester, capfd) -> None:
1815 config = pytester.parseconfig()
1816 with pytest.raises(ValueError) as excinfo:
1817 raise ValueError(1)
1818 config.notify_exception(excinfo, config.option)
1819 _, err = capfd.readouterr()
1820 assert "ValueError" in err
1821
1822 class A:
1823 def pytest_internalerror(self):
1824 return True
1825
1826 config.pluginmanager.register(A())
1827 config.notify_exception(excinfo, config.option)
1828 _, err = capfd.readouterr()
1829 assert not err
1830
1831 config = pytester.parseconfig("-p", "no:terminal")
1832 with pytest.raises(ValueError) as excinfo:
1833 raise ValueError(1)
1834 config.notify_exception(excinfo, config.option)
1835 _, err = capfd.readouterr()
1836 assert "ValueError" in err
1837
1838
1839 def test_no_terminal_discovery_error(pytester: Pytester) -> None:
1840 pytester.makepyfile("raise TypeError('oops!')")
1841 result = pytester.runpytest("-p", "no:terminal", "--collect-only")
1842 assert result.ret == ExitCode.INTERRUPTED
1843
1844
1845 def test_load_initial_conftest_last_ordering(_config_for_test):
1846 pm = _config_for_test.pluginmanager
1847
1848 class My:
1849 def pytest_load_initial_conftests(self):
1850 pass
1851
1852 m = My()
1853 pm.register(m)
1854 hc = pm.hook.pytest_load_initial_conftests
1855 hookimpls = [
1856 (
1857 hookimpl.function.__module__,
1858 "wrapper" if (hookimpl.wrapper or hookimpl.hookwrapper) else "nonwrapper",
1859 )
1860 for hookimpl in hc.get_hookimpls()
1861 ]
1862 assert hookimpls == [
1863 ("_pytest.config", "nonwrapper"),
1864 (m.__module__, "nonwrapper"),
1865 ("_pytest.legacypath", "nonwrapper"),
1866 ("_pytest.capture", "wrapper"),
1867 ("_pytest.warnings", "wrapper"),
1868 ]
1869
1870
1871 def test_get_plugin_specs_as_list() -> None:
1872 def exp_match(val: object) -> str:
1873 return (
1874 f"Plugins may be specified as a sequence or a ','-separated string "
1875 f"of plugin names. Got: {re.escape(repr(val))}"
1876 )
1877
1878 with pytest.raises(pytest.UsageError, match=exp_match({"foo"})):
1879 _get_plugin_specs_as_list({"foo"}) # type: ignore[arg-type]
1880 with pytest.raises(pytest.UsageError, match=exp_match({})):
1881 _get_plugin_specs_as_list(dict()) # type: ignore[arg-type]
1882
1883 assert _get_plugin_specs_as_list(None) == []
1884 assert _get_plugin_specs_as_list("") == []
1885 assert _get_plugin_specs_as_list("foo") == ["foo"]
1886 assert _get_plugin_specs_as_list("foo,bar") == ["foo", "bar"]
1887 assert _get_plugin_specs_as_list(["foo", "bar"]) == ["foo", "bar"]
1888 assert _get_plugin_specs_as_list(("foo", "bar")) == ["foo", "bar"]
1889
1890
1891 def test_collect_pytest_prefix_bug_integration(pytester: Pytester) -> None:
1892 """Integration test for issue #3775"""
1893 p = pytester.copy_example("config/collect_pytest_prefix")
1894 result = pytester.runpytest(p)
1895 result.stdout.fnmatch_lines(["* 1 passed *"])
1896
1897
1898 def test_collect_pytest_prefix_bug(pytestconfig):
1899 """Ensure we collect only actual functions from conftest files (#3775)"""
1900
1901 class Dummy:
1902 class pytest_something:
1903 pass
1904
1905 pm = pytestconfig.pluginmanager
1906 assert pm.parse_hookimpl_opts(Dummy(), "pytest_something") is None
1907
1908
1909 class TestRootdir:
1910 def test_simple_noini(self, tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
1911 assert get_common_ancestor(Path.cwd(), [tmp_path]) == tmp_path
1912 a = tmp_path / "a"
1913 a.mkdir()
1914 assert get_common_ancestor(Path.cwd(), [a, tmp_path]) == tmp_path
1915 assert get_common_ancestor(Path.cwd(), [tmp_path, a]) == tmp_path
1916 monkeypatch.chdir(tmp_path)
1917 assert get_common_ancestor(Path.cwd(), []) == tmp_path
1918 no_path = tmp_path / "does-not-exist"
1919 assert get_common_ancestor(Path.cwd(), [no_path]) == tmp_path
1920 assert get_common_ancestor(Path.cwd(), [no_path / "a"]) == tmp_path
1921
1922 @pytest.mark.parametrize(
1923 "name, contents",
1924 [
1925 pytest.param("pytest.ini", "[pytest]\nx=10", id="pytest.ini"),
1926 pytest.param(
1927 "pyproject.toml", "[tool.pytest.ini_options]\nx=10", id="pyproject.toml"
1928 ),
1929 pytest.param("tox.ini", "[pytest]\nx=10", id="tox.ini"),
1930 pytest.param("setup.cfg", "[tool:pytest]\nx=10", id="setup.cfg"),
1931 ],
1932 )
1933 def test_with_ini(self, tmp_path: Path, name: str, contents: str) -> None:
1934 inipath = tmp_path / name
1935 inipath.write_text(contents, encoding="utf-8")
1936
1937 a = tmp_path / "a"
1938 a.mkdir()
1939 b = a / "b"
1940 b.mkdir()
1941 for args in ([str(tmp_path)], [str(a)], [str(b)]):
1942 rootpath, parsed_inipath, *_ = determine_setup(
1943 inifile=None,
1944 override_ini=None,
1945 args=args,
1946 rootdir_cmd_arg=None,
1947 invocation_dir=Path.cwd(),
1948 )
1949 assert rootpath == tmp_path
1950 assert parsed_inipath == inipath
1951 rootpath, parsed_inipath, ini_config, _ = determine_setup(
1952 inifile=None,
1953 override_ini=None,
1954 args=[str(b), str(a)],
1955 rootdir_cmd_arg=None,
1956 invocation_dir=Path.cwd(),
1957 )
1958 assert rootpath == tmp_path
1959 assert parsed_inipath == inipath
1960 assert ini_config["x"] == ConfigValue("10", origin="file", mode="ini")
1961
1962 @pytest.mark.parametrize("pytest_ini", ["pytest.ini", ".pytest.ini"])
1963 @pytest.mark.parametrize("other", ["setup.cfg", "tox.ini"])
1964 def test_pytestini_overrides_empty_other(
1965 self, tmp_path: Path, pytest_ini: str, other: str
1966 ) -> None:
1967 inipath = tmp_path / pytest_ini
1968 inipath.touch()
1969 a = tmp_path / "a"
1970 a.mkdir()
1971 (a / other).touch()
1972 rootpath, parsed_inipath, *_ = determine_setup(
1973 inifile=None,
1974 override_ini=None,
1975 args=[str(a)],
1976 rootdir_cmd_arg=None,
1977 invocation_dir=Path.cwd(),
1978 )
1979 assert rootpath == tmp_path
1980 assert parsed_inipath == inipath
1981
1982 def test_setuppy_fallback(self, tmp_path: Path) -> None:
1983 a = tmp_path / "a"
1984 a.mkdir()
1985 (a / "setup.cfg").touch()
1986 (tmp_path / "setup.py").touch()
1987 rootpath, inipath, inicfg, _ = determine_setup(
1988 inifile=None,
1989 override_ini=None,
1990 args=[str(a)],
1991 rootdir_cmd_arg=None,
1992 invocation_dir=Path.cwd(),
1993 )
1994 assert rootpath == tmp_path
1995 assert inipath is None
1996 assert inicfg == {}
1997
1998 def test_nothing(self, tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
1999 monkeypatch.chdir(tmp_path)
2000 rootpath, inipath, inicfg, _ = determine_setup(
2001 inifile=None,
2002 override_ini=None,
2003 args=[str(tmp_path)],
2004 rootdir_cmd_arg=None,
2005 invocation_dir=Path.cwd(),
2006 )
2007 assert rootpath == tmp_path
2008 assert inipath is None
2009 assert inicfg == {}
2010
2011 @pytest.mark.parametrize(
2012 "name, contents",
2013 [
2014 # pytest.param("pytest.ini", "[pytest]\nx=10", id="pytest.ini"),
2015 pytest.param(
2016 "pyproject.toml", "[tool.pytest.ini_options]\nx=10", id="pyproject.toml"
2017 ),
2018 # pytest.param("tox.ini", "[pytest]\nx=10", id="tox.ini"),
2019 # pytest.param("setup.cfg", "[tool:pytest]\nx=10", id="setup.cfg"),
2020 ],
2021 )
2022 def test_with_specific_inifile(
2023 self, tmp_path: Path, name: str, contents: str
2024 ) -> None:
2025 p = tmp_path / name
2026 p.touch()
2027 p.write_text(contents, encoding="utf-8")
2028 rootpath, inipath, ini_config, _ = determine_setup(
2029 inifile=str(p),
2030 override_ini=None,
2031 args=[str(tmp_path)],
2032 rootdir_cmd_arg=None,
2033 invocation_dir=Path.cwd(),
2034 )
2035 assert rootpath == tmp_path
2036 assert inipath == p
2037 assert ini_config["x"] == ConfigValue("10", origin="file", mode="ini")
2038
2039 def test_explicit_config_file_sets_rootdir(
2040 self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
2041 ) -> None:
2042 tests_dir = tmp_path / "tests"
2043 tests_dir.mkdir()
2044
2045 monkeypatch.chdir(tmp_path)
2046
2047 # No config file is explicitly given: rootdir is determined to be cwd.
2048 rootpath, found_inipath, *_ = determine_setup(
2049 inifile=None,
2050 override_ini=None,
2051 args=[str(tests_dir)],
2052 rootdir_cmd_arg=None,
2053 invocation_dir=Path.cwd(),
2054 )
2055 assert rootpath == tmp_path
2056 assert found_inipath is None
2057
2058 # Config file is explicitly given: rootdir is determined to be inifile's directory.
2059 inipath = tmp_path / "pytest.ini"
2060 inipath.touch()
2061 rootpath, found_inipath, *_ = determine_setup(
2062 inifile=str(inipath),
2063 override_ini=None,
2064 args=[str(tests_dir)],
2065 rootdir_cmd_arg=None,
2066 invocation_dir=Path.cwd(),
2067 )
2068 assert rootpath == tmp_path
2069 assert found_inipath == inipath
2070
2071 def test_with_arg_outside_cwd_without_inifile(
2072 self, tmp_path: Path, monkeypatch: MonkeyPatch
2073 ) -> None:
2074 monkeypatch.chdir(tmp_path)
2075 a = tmp_path / "a"
2076 a.mkdir()
2077 b = tmp_path / "b"
2078 b.mkdir()
2079 rootpath, inifile, *_ = determine_setup(
2080 inifile=None,
2081 override_ini=None,
2082 args=[str(a), str(b)],
2083 rootdir_cmd_arg=None,
2084 invocation_dir=Path.cwd(),
2085 )
2086 assert rootpath == tmp_path
2087 assert inifile is None
2088
2089 def test_with_arg_outside_cwd_with_inifile(self, tmp_path: Path) -> None:
2090 a = tmp_path / "a"
2091 a.mkdir()
2092 b = tmp_path / "b"
2093 b.mkdir()
2094 inipath = a / "pytest.ini"
2095 inipath.touch()
2096 rootpath, parsed_inipath, *_ = determine_setup(
2097 inifile=None,
2098 override_ini=None,
2099 args=[str(a), str(b)],
2100 rootdir_cmd_arg=None,
2101 invocation_dir=Path.cwd(),
2102 )
2103 assert rootpath == a
2104 assert inipath == parsed_inipath
2105
2106 @pytest.mark.parametrize("dirs", ([], ["does-not-exist"], ["a/does-not-exist"]))
2107 def test_with_non_dir_arg(
2108 self, dirs: Sequence[str], tmp_path: Path, monkeypatch: MonkeyPatch
2109 ) -> None:
2110 monkeypatch.chdir(tmp_path)
2111 rootpath, inipath, *_ = determine_setup(
2112 inifile=None,
2113 override_ini=None,
2114 args=dirs,
2115 rootdir_cmd_arg=None,
2116 invocation_dir=Path.cwd(),
2117 )
2118 assert rootpath == tmp_path
2119 assert inipath is None
2120
2121 def test_with_existing_file_in_subdir(
2122 self, tmp_path: Path, monkeypatch: MonkeyPatch
2123 ) -> None:
2124 a = tmp_path / "a"
2125 a.mkdir()
2126 (a / "exists").touch()
2127 monkeypatch.chdir(tmp_path)
2128 rootpath, inipath, *_ = determine_setup(
2129 inifile=None,
2130 override_ini=None,
2131 args=["a/exist"],
2132 rootdir_cmd_arg=None,
2133 invocation_dir=Path.cwd(),
2134 )
2135 assert rootpath == tmp_path
2136 assert inipath is None
2137
2138 def test_with_config_also_in_parent_directory(
2139 self, tmp_path: Path, monkeypatch: MonkeyPatch
2140 ) -> None:
2141 """Regression test for #7807."""
2142 (tmp_path / "setup.cfg").write_text("[tool:pytest]\n", "utf-8")
2143 (tmp_path / "myproject").mkdir()
2144 (tmp_path / "myproject" / "setup.cfg").write_text("[tool:pytest]\n", "utf-8")
2145 (tmp_path / "myproject" / "tests").mkdir()
2146 monkeypatch.chdir(tmp_path / "myproject")
2147
2148 rootpath, inipath, *_ = determine_setup(
2149 inifile=None,
2150 override_ini=None,
2151 args=["tests/"],
2152 rootdir_cmd_arg=None,
2153 invocation_dir=Path.cwd(),
2154 )
2155
2156 assert rootpath == tmp_path / "myproject"
2157 assert inipath == tmp_path / "myproject" / "setup.cfg"
2158
2159
2160 class TestOverrideIniArgs:
2161 @pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split())
2162 def test_override_ini_names(self, pytester: Pytester, name: str) -> None:
2163 section = "[pytest]" if name != "setup.cfg" else "[tool:pytest]"
2164 pytester.path.joinpath(name).write_text(
2165 textwrap.dedent(
2166 f"""
2167 {section}
2168 custom = 1.0"""
2169 ),
2170 encoding="utf-8",
2171 )
2172 pytester.makeconftest(
2173 """
2174 def pytest_addoption(parser):
2175 parser.addini("custom", "")"""
2176 )
2177 pytester.makepyfile(
2178 """
2179 def test_pass(pytestconfig):
2180 ini_val = pytestconfig.getini("custom")
2181 print('\\ncustom_option:%s\\n' % ini_val)"""
2182 )
2183
2184 result = pytester.runpytest("--override-ini", "custom=2.0", "-s")
2185 assert result.ret == 0
2186 result.stdout.fnmatch_lines(["custom_option:2.0"])
2187
2188 result = pytester.runpytest(
2189 "--override-ini", "custom=2.0", "--override-ini=custom=3.0", "-s"
2190 )
2191 assert result.ret == 0
2192 result.stdout.fnmatch_lines(["custom_option:3.0"])
2193
2194 def test_override_ini_paths(self, pytester: Pytester) -> None:
2195 pytester.makeconftest(
2196 """
2197 def pytest_addoption(parser):
2198 parser.addini("paths", "my new ini value", type="paths")"""
2199 )
2200 pytester.makeini(
2201 """
2202 [pytest]
2203 paths=blah.py"""
2204 )
2205 pytester.makepyfile(
2206 r"""
2207 def test_overridden(pytestconfig):
2208 config_paths = pytestconfig.getini("paths")
2209 print(config_paths)
2210 for cpf in config_paths:
2211 print('\nuser_path:%s' % cpf.name)
2212 """
2213 )
2214 result = pytester.runpytest(
2215 "--override-ini", "paths=foo/bar1.py foo/bar2.py", "-s"
2216 )
2217 result.stdout.fnmatch_lines(["user_path:bar1.py", "user_path:bar2.py"])
2218
2219 def test_override_multiple_and_default(self, pytester: Pytester) -> None:
2220 pytester.makeconftest(
2221 """
2222 def pytest_addoption(parser):
2223 addini = parser.addini
2224 addini("custom_option_1", "", default="o1")
2225 addini("custom_option_2", "", default="o2")
2226 addini("custom_option_3", "", default=False, type="bool")
2227 addini("custom_option_4", "", default=True, type="bool")"""
2228 )
2229 pytester.makeini(
2230 """
2231 [pytest]
2232 custom_option_1=custom_option_1
2233 custom_option_2=custom_option_2
2234 """
2235 )
2236 pytester.makepyfile(
2237 """
2238 def test_multiple_options(pytestconfig):
2239 prefix = "custom_option"
2240 for x in range(1, 5):
2241 ini_value=pytestconfig.getini("%s_%d" % (prefix, x))
2242 print('\\nini%d:%s' % (x, ini_value))
2243 """
2244 )
2245 result = pytester.runpytest(
2246 "--override-ini",
2247 "custom_option_1=fulldir=/tmp/user1",
2248 "-o",
2249 "custom_option_2=url=/tmp/user2?a=b&d=e",
2250 "-o",
2251 "custom_option_3=True",
2252 "-o",
2253 "custom_option_4=no",
2254 "-s",
2255 )
2256 result.stdout.fnmatch_lines(
2257 [
2258 "ini1:fulldir=/tmp/user1",
2259 "ini2:url=/tmp/user2?a=b&d=e",
2260 "ini3:True",
2261 "ini4:False",
2262 ]
2263 )
2264
2265 def test_override_ini_usage_error_bad_style(self, pytester: Pytester) -> None:
2266 pytester.makeini(
2267 """
2268 [pytest]
2269 xdist_strict=False
2270 """
2271 )
2272 result = pytester.runpytest("--override-ini", "xdist_strict", "True")
2273 result.stderr.fnmatch_lines(
2274 [
2275 "ERROR: -o/--override-ini expects option=value style (got: 'xdist_strict').",
2276 ]
2277 )
2278
2279 @pytest.mark.parametrize("with_ini", [True, False])
2280 def test_override_ini_handled_asap(
2281 self, pytester: Pytester, with_ini: bool
2282 ) -> None:
2283 """-o should be handled as soon as possible and always override what's in config files (#2238)"""
2284 if with_ini:
2285 pytester.makeini(
2286 """
2287 [pytest]
2288 python_files=test_*.py
2289 """
2290 )
2291 pytester.makepyfile(
2292 unittest_ini_handle="""
2293 def test():
2294 pass
2295 """
2296 )
2297 result = pytester.runpytest("--override-ini", "python_files=unittest_*.py")
2298 result.stdout.fnmatch_lines(["*1 passed in*"])
2299
2300 def test_addopts_before_initini(
2301 self, monkeypatch: MonkeyPatch, _config_for_test, _sys_snapshot
2302 ) -> None:
2303 cache_dir = ".custom_cache"
2304 monkeypatch.setenv("PYTEST_ADDOPTS", f"-o cache_dir={cache_dir}")
2305 config = _config_for_test
2306 config.parse([], addopts=True)
2307 assert config._inicfg.get("cache_dir") == ConfigValue(
2308 cache_dir, origin="override", mode="ini"
2309 )
2310
2311 def test_addopts_from_env_not_concatenated(
2312 self, monkeypatch: MonkeyPatch, _config_for_test
2313 ) -> None:
2314 """PYTEST_ADDOPTS should not take values from normal args (#4265)."""
2315 monkeypatch.setenv("PYTEST_ADDOPTS", "-o")
2316 config = _config_for_test
2317 with pytest.raises(UsageError) as excinfo:
2318 config.parse(["cache_dir=ignored"], addopts=True)
2319 assert (
2320 "error: argument -o/--override-ini: expected one argument"
2321 in excinfo.value.args[0]
2322 )
2323 assert "via PYTEST_ADDOPTS" in excinfo.value.args[0]
2324
2325 def test_addopts_from_ini_not_concatenated(self, pytester: Pytester) -> None:
2326 """`addopts` from configuration should not take values from normal args (#4265)."""
2327 pytester.makeini(
2328 """
2329 [pytest]
2330 addopts=-o
2331 """
2332 )
2333 result = pytester.runpytest("cache_dir=ignored")
2334 result.stderr.fnmatch_lines(
2335 [
2336 "*: error: argument -o/--override-ini: expected one argument",
2337 " config source: via addopts config",
2338 ]
2339 )
2340 assert result.ret == _pytest.config.ExitCode.USAGE_ERROR
2341
2342 def test_override_ini_does_not_contain_paths(
2343 self, _config_for_test, _sys_snapshot
2344 ) -> None:
2345 """Check that -o no longer swallows all options after it (#3103)"""
2346 config = _config_for_test
2347 config.parse(["-o", "cache_dir=/cache", "/some/test/path"])
2348 assert config._inicfg.get("cache_dir") == ConfigValue(
2349 "/cache", origin="override", mode="ini"
2350 )
2351
2352 def test_multiple_override_ini_options(self, pytester: Pytester) -> None:
2353 """Ensure a file path following a '-o' option does not generate an error (#3103)"""
2354 pytester.makepyfile(
2355 **{
2356 "conftest.py": """
2357 def pytest_addoption(parser):
2358 parser.addini('foo', default=None, help='some option')
2359 parser.addini('bar', default=None, help='some option')
2360 """,
2361 "test_foo.py": """
2362 def test(pytestconfig):
2363 assert pytestconfig.getini('foo') == '1'
2364 assert pytestconfig.getini('bar') == '0'
2365 """,
2366 "test_bar.py": """
2367 def test():
2368 assert False
2369 """,
2370 }
2371 )
2372 result = pytester.runpytest("-o", "foo=1", "-o", "bar=0", "test_foo.py")
2373 assert "ERROR:" not in result.stderr.str()
2374 result.stdout.fnmatch_lines(["collected 1 item", "*= 1 passed in *="])
2375
2376 def test_override_ini_without_config_file(self, pytester: Pytester) -> None:
2377 pytester.makepyfile(**{"src/override_ini_without_config_file.py": ""})
2378 pytester.makepyfile(
2379 **{
2380 "tests/test_override_ini_without_config_file.py": (
2381 "import override_ini_without_config_file\ndef test(): pass"
2382 ),
2383 }
2384 )
2385 result = pytester.runpytest("--override-ini", "pythonpath=src")
2386 result.assert_outcomes(passed=1)
2387
2388 def test_override_ini_invalid_option(self, pytester: Pytester) -> None:
2389 result = pytester.runpytest("--override-ini", "doesnotexist=true")
2390 result.stdout.fnmatch_lines(
2391 [
2392 "=*= warnings summary =*=",
2393 "*PytestConfigWarning:*Unknown config option: doesnotexist",
2394 ]
2395 )
2396
2397
2398 def test_help_via_addopts(pytester: Pytester) -> None:
2399 pytester.makeini(
2400 """
2401 [pytest]
2402 addopts = --unknown-option-should-allow-for-help --help
2403 """
2404 )
2405 result = pytester.runpytest()
2406 assert result.ret == 0
2407 result.stdout.fnmatch_lines(
2408 [
2409 "usage: *",
2410 "positional arguments:",
2411 # Displays full/default help.
2412 "to see available markers type: pytest --markers",
2413 ]
2414 )
2415
2416
2417 def test_help_and_version_after_argument_error(pytester: Pytester) -> None:
2418 pytester.makeconftest(
2419 """
2420 def validate(arg):
2421 raise argparse.ArgumentTypeError("argerror")
2422
2423 def pytest_addoption(parser):
2424 group = parser.getgroup('cov')
2425 group.addoption(
2426 "--invalid-option-should-allow-for-help",
2427 type=validate,
2428 )
2429 """
2430 )
2431 pytester.makeini(
2432 """
2433 [pytest]
2434 addopts = --invalid-option-should-allow-for-help
2435 """
2436 )
2437 result = pytester.runpytest("--help")
2438 result.stdout.fnmatch_lines(
2439 [
2440 "usage: *",
2441 "positional arguments:",
2442 "NOTE: displaying only minimal help due to UsageError.",
2443 ]
2444 )
2445 result.stderr.fnmatch_lines(
2446 [
2447 "ERROR: usage: *",
2448 "*: error: argument --invalid-option-should-allow-for-help: expected one argument",
2449 ]
2450 )
2451 # Does not display full/default help.
2452 assert "to see available markers type: pytest --markers" not in result.stdout.lines
2453 assert result.ret == ExitCode.USAGE_ERROR
2454
2455 result = pytester.runpytest("--version")
2456 result.stdout.fnmatch_lines([f"pytest {pytest.__version__}"])
2457 assert result.ret == ExitCode.OK
2458
2459
2460 def test_help_formatter_uses_py_get_terminal_width(monkeypatch: MonkeyPatch) -> None:
2461 from _pytest.config.argparsing import DropShorterLongHelpFormatter
2462
2463 monkeypatch.setenv("COLUMNS", "90")
2464 formatter = DropShorterLongHelpFormatter("prog")
2465 assert formatter._width == 90
2466
2467 monkeypatch.setattr("_pytest._io.get_terminal_width", lambda: 160)
2468 formatter = DropShorterLongHelpFormatter("prog")
2469 assert formatter._width == 160
2470
2471 formatter = DropShorterLongHelpFormatter("prog", width=42)
2472 assert formatter._width == 42
2473
2474
2475 def test_config_does_not_load_blocked_plugin_from_args(pytester: Pytester) -> None:
2476 """This tests that pytest's config setup handles "-p no:X"."""
2477 p = pytester.makepyfile("def test(capfd): pass")
2478 result = pytester.runpytest(str(p), "-pno:capture")
2479 result.stdout.fnmatch_lines(["E fixture 'capfd' not found"])
2480 assert result.ret == ExitCode.TESTS_FAILED
2481
2482 result = pytester.runpytest(str(p), "-pno:capture", "-s")
2483 result.stderr.fnmatch_lines(["*: error: unrecognized arguments: -s"])
2484 assert result.ret == ExitCode.USAGE_ERROR
2485
2486 result = pytester.runpytest(str(p), "-p no:capture", "-s")
2487 result.stderr.fnmatch_lines(["*: error: unrecognized arguments: -s"])
2488 assert result.ret == ExitCode.USAGE_ERROR
2489
2490 result = pytester.runpytest(str(p), "-p no:/path/to/conftest.py", "-s")
2491 result.stderr.fnmatch_lines(["ERROR:*Blocking conftest files*"])
2492 assert result.ret == ExitCode.USAGE_ERROR
2493
2494
2495 def test_invocation_args(pytester: Pytester) -> None:
2496 """Ensure that Config.invocation_* arguments are correctly defined"""
2497
2498 class DummyPlugin:
2499 pass
2500
2501 p = pytester.makepyfile("def test(): pass")
2502 plugin = DummyPlugin()
2503 rec = pytester.inline_run(p, "-v", plugins=[plugin])
2504 calls = rec.getcalls("pytest_runtest_protocol")
2505 assert len(calls) == 1
2506 call = calls[0]
2507 config = call.item.config
2508
2509 assert config.invocation_params.args == (str(p), "-v")
2510 assert config.invocation_params.dir == pytester.path
2511
2512 plugins = config.invocation_params.plugins
2513 assert len(plugins) == 2
2514 assert plugins[0] is plugin
2515 # Installed by pytester.inline_run().
2516 assert type(plugins[1]).__name__ == "PytesterHelperPlugin"
2517
2518 # args cannot be None
2519 with pytest.raises(TypeError):
2520 Config.InvocationParams(args=None, plugins=None, dir=Path()) # type: ignore[arg-type]
2521
2522
2523 @pytest.mark.parametrize(
2524 "plugin",
2525 [
2526 x
2527 for x in _pytest.config.default_plugins
2528 if x not in _pytest.config.essential_plugins
2529 ],
2530 )
2531 def test_config_blocked_default_plugins(pytester: Pytester, plugin: str) -> None:
2532 p = pytester.makepyfile("def test(): pass")
2533 result = pytester.runpytest(str(p), f"-pno:{plugin}")
2534
2535 if plugin == "python":
2536 assert result.ret == ExitCode.USAGE_ERROR
2537 result.stderr.fnmatch_lines(
2538 [
2539 "ERROR: not found: */test_config_blocked_default_plugins.py",
2540 "(no match in any of *<Dir *>*",
2541 ]
2542 )
2543 return
2544
2545 assert result.ret == ExitCode.OK
2546 if plugin != "terminal":
2547 result.stdout.fnmatch_lines(["* 1 passed in *"])
2548
2549 p = pytester.makepyfile("def test(): assert 0")
2550 result = pytester.runpytest(str(p), f"-pno:{plugin}")
2551 assert result.ret == ExitCode.TESTS_FAILED
2552 if plugin != "terminal":
2553 result.stdout.fnmatch_lines(["* 1 failed in *"])
2554 else:
2555 assert result.stdout.lines == []
2556
2557
2558 class TestSetupCfg:
2559 def test_pytest_setup_cfg_unsupported(self, pytester: Pytester) -> None:
2560 pytester.makefile(
2561 ".cfg",
2562 setup="""
2563 [pytest]
2564 addopts = --verbose
2565 """,
2566 )
2567 with pytest.raises(pytest.fail.Exception):
2568 pytester.runpytest()
2569
2570 def test_pytest_custom_cfg_unsupported(self, pytester: Pytester) -> None:
2571 pytester.makefile(
2572 ".cfg",
2573 custom="""
2574 [pytest]
2575 addopts = --verbose
2576 """,
2577 )
2578 with pytest.raises(pytest.fail.Exception):
2579 pytester.runpytest("-c", "custom.cfg")
2580
2581 with pytest.raises(pytest.fail.Exception):
2582 pytester.runpytest("--config-file", "custom.cfg")
2583
2584
2585 class TestPytestPluginsVariable:
2586 def test_pytest_plugins_in_non_top_level_conftest_unsupported(
2587 self, pytester: Pytester
2588 ) -> None:
2589 pytester.makepyfile(
2590 **{
2591 "subdirectory/conftest.py": """
2592 pytest_plugins=['capture']
2593 """
2594 }
2595 )
2596 pytester.makepyfile(
2597 """
2598 def test_func():
2599 pass
2600 """
2601 )
2602 res = pytester.runpytest()
2603 assert res.ret == 2
2604 msg = "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported"
2605 res.stdout.fnmatch_lines([f"*{msg}*", f"*subdirectory{os.sep}conftest.py*"])
2606
2607 @pytest.mark.parametrize("use_pyargs", [True, False])
2608 def test_pytest_plugins_in_non_top_level_conftest_unsupported_pyargs(
2609 self, pytester: Pytester, use_pyargs: bool
2610 ) -> None:
2611 """When using --pyargs, do not emit the warning about non-top-level conftest warnings (#4039, #4044)"""
2612 files = {
2613 "src/pkg/__init__.py": "",
2614 "src/pkg/conftest.py": "",
2615 "src/pkg/test_root.py": "def test(): pass",
2616 "src/pkg/sub/__init__.py": "",
2617 "src/pkg/sub/conftest.py": "pytest_plugins=['capture']",
2618 "src/pkg/sub/test_bar.py": "def test(): pass",
2619 }
2620 pytester.makepyfile(**files)
2621 pytester.syspathinsert(pytester.path.joinpath("src"))
2622
2623 args = ("--pyargs", "pkg") if use_pyargs else ()
2624 res = pytester.runpytest(*args)
2625 assert res.ret == (0 if use_pyargs else 2)
2626 msg = "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported"
2627 if use_pyargs:
2628 assert msg not in res.stdout.str()
2629 else:
2630 res.stdout.fnmatch_lines([f"*{msg}*"])
2631
2632 def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_top_level_conftest(
2633 self, pytester: Pytester
2634 ) -> None:
2635 subdirectory = pytester.path.joinpath("subdirectory")
2636 subdirectory.mkdir()
2637 pytester.makeconftest(
2638 """
2639 pytest_plugins=['capture']
2640 """
2641 )
2642 pytester.path.joinpath("conftest.py").rename(
2643 subdirectory.joinpath("conftest.py")
2644 )
2645
2646 pytester.makepyfile(
2647 """
2648 def test_func():
2649 pass
2650 """
2651 )
2652
2653 res = pytester.runpytest_subprocess()
2654 assert res.ret == 2
2655 msg = "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported"
2656 res.stdout.fnmatch_lines([f"*{msg}*", f"*subdirectory{os.sep}conftest.py*"])
2657
2658 def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_false_positives(
2659 self, pytester: Pytester
2660 ) -> None:
2661 pytester.makepyfile(
2662 "def test_func(): pass",
2663 **{
2664 "subdirectory/conftest": "pass",
2665 "conftest": """
2666 import warnings
2667 warnings.filterwarnings('always', category=DeprecationWarning)
2668 pytest_plugins=['capture']
2669 """,
2670 },
2671 )
2672 res = pytester.runpytest_subprocess()
2673 assert res.ret == 0
2674 msg = "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported"
2675 assert msg not in res.stdout.str()
2676
2677
2678 def test_conftest_import_error_repr(tmp_path: Path) -> None:
2679 """`ConftestImportFailure` should use a short error message and readable
2680 path to the failed conftest.py file."""
2681 path = tmp_path.joinpath("foo/conftest.py")
2682 with pytest.raises(
2683 ConftestImportFailure,
2684 match=re.escape(f"RuntimeError: some error (from {path})"),
2685 ):
2686 try:
2687 raise RuntimeError("some error")
2688 except Exception as exc:
2689 raise ConftestImportFailure(path, cause=exc) from exc
2690
2691
2692 def test_strtobool() -> None:
2693 assert _strtobool("YES")
2694 assert not _strtobool("NO")
2695 with pytest.raises(ValueError):
2696 _strtobool("unknown")
2697
2698
2699 @pytest.mark.parametrize(
2700 "arg, escape, expected",
2701 [
2702 ("ignore", False, ("ignore", "", Warning, "", 0)),
2703 (
2704 "ignore::DeprecationWarning",
2705 False,
2706 ("ignore", "", DeprecationWarning, "", 0),
2707 ),
2708 (
2709 "ignore:some msg:DeprecationWarning",
2710 False,
2711 ("ignore", "some msg", DeprecationWarning, "", 0),
2712 ),
2713 (
2714 "ignore::DeprecationWarning:mod",
2715 False,
2716 ("ignore", "", DeprecationWarning, "mod", 0),
2717 ),
2718 (
2719 "ignore::DeprecationWarning:mod:42",
2720 False,
2721 ("ignore", "", DeprecationWarning, "mod", 42),
2722 ),
2723 ("error:some\\msg:::", True, ("error", "some\\\\msg", Warning, "", 0)),
2724 ("error:::mod\\foo:", True, ("error", "", Warning, "mod\\\\foo\\Z", 0)),
2725 ],
2726 )
2727 def test_parse_warning_filter(
2728 arg: str, escape: bool, expected: tuple[str, str, type[Warning], str, int]
2729 ) -> None:
2730 assert parse_warning_filter(arg, escape=escape) == expected
2731
2732
2733 @pytest.mark.parametrize(
2734 "arg",
2735 [
2736 # Too much parts.
2737 ":" * 5,
2738 # Invalid action.
2739 "FOO::",
2740 # Class is not a Warning subclass.
2741 "::list::",
2742 # Negative line number.
2743 "::::-1",
2744 # Not a line number.
2745 "::::not-a-number",
2746 ],
2747 )
2748 def test_parse_warning_filter_failure(arg: str) -> None:
2749 with pytest.raises(pytest.UsageError):
2750 parse_warning_filter(arg, escape=True)
2751
2752
2753 class TestDebugOptions:
2754 def test_without_debug_does_not_write_log(self, pytester: Pytester) -> None:
2755 result = pytester.runpytest()
2756 result.stderr.no_fnmatch_line(
2757 "*writing pytest debug information to*pytestdebug.log"
2758 )
2759 result.stderr.no_fnmatch_line(
2760 "*wrote pytest debug information to*pytestdebug.log"
2761 )
2762 assert not [f.name for f in pytester.path.glob("**/*.log")]
2763
2764 def test_with_only_debug_writes_pytestdebug_log(self, pytester: Pytester) -> None:
2765 result = pytester.runpytest("--debug")
2766 result.stderr.fnmatch_lines(
2767 [
2768 "*writing pytest debug information to*pytestdebug.log",
2769 "*wrote pytest debug information to*pytestdebug.log",
2770 ]
2771 )
2772 assert "pytestdebug.log" in [f.name for f in pytester.path.glob("**/*.log")]
2773
2774 def test_multiple_custom_debug_logs(self, pytester: Pytester) -> None:
2775 result = pytester.runpytest("--debug", "bar.log")
2776 result.stderr.fnmatch_lines(
2777 [
2778 "*writing pytest debug information to*bar.log",
2779 "*wrote pytest debug information to*bar.log",
2780 ]
2781 )
2782 result = pytester.runpytest("--debug", "foo.log")
2783 result.stderr.fnmatch_lines(
2784 [
2785 "*writing pytest debug information to*foo.log",
2786 "*wrote pytest debug information to*foo.log",
2787 ]
2788 )
2789
2790 assert {"bar.log", "foo.log"} == {
2791 f.name for f in pytester.path.glob("**/*.log")
2792 }
2793
2794 def test_debug_help(self, pytester: Pytester) -> None:
2795 result = pytester.runpytest("-h")
2796 result.stdout.fnmatch_lines(
2797 [
2798 "*Store internal tracing debug information in this log*",
2799 "*file. This file is opened with 'w' and truncated as a*",
2800 "*Default: pytestdebug.log.",
2801 ]
2802 )
2803
2804
2805 class TestVerbosity:
2806 SOME_OUTPUT_TYPE = Config.VERBOSITY_ASSERTIONS
2807 SOME_OUTPUT_VERBOSITY_LEVEL = 5
2808
2809 class VerbosityIni:
2810 def pytest_addoption(self, parser: Parser) -> None:
2811 Config._add_verbosity_ini(
2812 parser, TestVerbosity.SOME_OUTPUT_TYPE, help="some help text"
2813 )
2814
2815 def test_level_matches_verbose_when_not_specified(
2816 self, pytester: Pytester, tmp_path: Path
2817 ) -> None:
2818 tmp_path.joinpath("pytest.ini").write_text(
2819 textwrap.dedent(
2820 """\
2821 [pytest]
2822 addopts = --verbose
2823 """
2824 ),
2825 encoding="utf-8",
2826 )
2827 pytester.plugins = [TestVerbosity.VerbosityIni()]
2828
2829 config = pytester.parseconfig(tmp_path)
2830
2831 assert (
2832 config.get_verbosity(TestVerbosity.SOME_OUTPUT_TYPE)
2833 == config.option.verbose
2834 )
2835
2836 def test_level_matches_verbose_when_not_known_type(
2837 self, pytester: Pytester, tmp_path: Path
2838 ) -> None:
2839 tmp_path.joinpath("pytest.ini").write_text(
2840 textwrap.dedent(
2841 """\
2842 [pytest]
2843 addopts = --verbose
2844 """
2845 ),
2846 encoding="utf-8",
2847 )
2848 pytester.plugins = [TestVerbosity.VerbosityIni()]
2849
2850 config = pytester.parseconfig(tmp_path)
2851
2852 assert config.get_verbosity("some fake verbosity type") == config.option.verbose
2853
2854 def test_level_matches_specified_override(
2855 self, pytester: Pytester, tmp_path: Path
2856 ) -> None:
2857 setting_name = f"verbosity_{TestVerbosity.SOME_OUTPUT_TYPE}"
2858 tmp_path.joinpath("pytest.ini").write_text(
2859 textwrap.dedent(
2860 f"""\
2861 [pytest]
2862 addopts = --verbose
2863 {setting_name} = {TestVerbosity.SOME_OUTPUT_VERBOSITY_LEVEL}
2864 """
2865 ),
2866 encoding="utf-8",
2867 )
2868 pytester.plugins = [TestVerbosity.VerbosityIni()]
2869
2870 config = pytester.parseconfig(tmp_path)
2871
2872 assert (
2873 config.get_verbosity(TestVerbosity.SOME_OUTPUT_TYPE)
2874 == TestVerbosity.SOME_OUTPUT_VERBOSITY_LEVEL
2875 )
2876
2877
2878 class TestNativeTomlConfig:
2879 """Test native TOML configuration parsing."""
2880
2881 def test_values(self, pytester: Pytester) -> None:
2882 """Test that values are parsed as expected in TOML mode."""
2883 pytester.makepyprojecttoml(
2884 """
2885 [tool.pytest]
2886 test_bool = true
2887 test_int = 5
2888 test_float = 30.5
2889 test_args = ["tests", "integration"]
2890 test_paths = ["src", "lib"]
2891 """
2892 )
2893 pytester.makeconftest(
2894 """
2895 def pytest_addoption(parser):
2896 parser.addini("test_bool", "Test boolean config", type="bool", default=False)
2897 parser.addini("test_int", "Test integer config", type="int", default=0)
2898 parser.addini("test_float", "Test float config", type="float", default=0.0)
2899 parser.addini("test_args", "Test args config", type="args")
2900 parser.addini("test_paths", "Test paths config", type="paths")
2901 """
2902 )
2903 config = pytester.parseconfig()
2904 assert config.getini("test_bool") is True
2905 assert config.getini("test_int") == 5
2906 assert config.getini("test_float") == 30.5
2907 assert config.getini("test_args") == ["tests", "integration"]
2908 paths = config.getini("test_paths")
2909 assert len(paths) == 2
2910 # Paths should be resolved relative to pyproject.toml location.
2911 assert all(isinstance(p, Path) for p in paths)
2912
2913 def test_override_with_list(self, pytester: Pytester) -> None:
2914 """Test that -o overrides work with INI-style list syntax even when
2915 config uses TOML mode."""
2916 pytester.makepyprojecttoml(
2917 """
2918 [tool.pytest]
2919 test_override_list = ["tests"]
2920 """
2921 )
2922 pytester.makeconftest(
2923 """
2924 def pytest_addoption(parser):
2925 parser.addini("test_override_list", "Test override list", type="args")
2926 """
2927 )
2928 # -o uses INI mode, so uses space-separated syntax.
2929 config = pytester.parseconfig("-o", "test_override_list=tests integration")
2930 assert config.getini("test_override_list") == ["tests", "integration"]
2931
2932 def test_conflict_between_native_and_ini_options(self, pytester: Pytester) -> None:
2933 """Test that using both [tool.pytest] and [tool.pytest.ini_options] fails."""
2934 pytester.makepyprojecttoml(
2935 """
2936 [tool.pytest]
2937 test_conflict_1 = true
2938
2939 [tool.pytest.ini_options]
2940 test_conflict_2 = true
2941 """,
2942 )
2943 pytester.makeconftest(
2944 """
2945 def pytest_addoption(parser):
2946 parser.addini("test_conflict_1", "Test conflict config 1", type="bool")
2947 parser.addini("test_conflict_2", "Test conflict config 2", type="bool")
2948 """
2949 )
2950 with pytest.raises(UsageError, match="Cannot use both"):
2951 pytester.parseconfig()
2952
2953 def test_type_errors(self, pytester: Pytester) -> None:
2954 """Test all possible TypeError cases in getini."""
2955 pytester.maketoml(
2956 """
2957 [pytest]
2958 paths_not_list = "should_be_list"
2959 paths_list_with_int = [1, 2]
2960
2961 args_not_list = 123
2962 args_list_with_int = ["valid", 456]
2963
2964 linelist_not_list = true
2965 linelist_list_with_bool = ["valid", false]
2966
2967 bool_not_bool = "true"
2968
2969 int_not_int = "123"
2970 int_is_bool = true
2971
2972 float_not_float = "3.14"
2973 float_is_bool = false
2974
2975 string_not_string = 123
2976 """
2977 )
2978 pytester.makeconftest(
2979 """
2980 def pytest_addoption(parser):
2981 parser.addini("paths_not_list", "test", type="paths")
2982 parser.addini("paths_list_with_int", "test", type="paths")
2983 parser.addini("args_not_list", "test", type="args")
2984 parser.addini("args_list_with_int", "test", type="args")
2985 parser.addini("linelist_not_list", "test", type="linelist")
2986 parser.addini("linelist_list_with_bool", "test", type="linelist")
2987 parser.addini("bool_not_bool", "test", type="bool")
2988 parser.addini("int_not_int", "test", type="int")
2989 parser.addini("int_is_bool", "test", type="int")
2990 parser.addini("float_not_float", "test", type="float")
2991 parser.addini("float_is_bool", "test", type="float")
2992 parser.addini("string_not_string", "test", type="string")
2993 """
2994 )
2995 config = pytester.parseconfig()
2996
2997 with pytest.raises(
2998 TypeError, match=r"expects a list for type 'paths'.*got str"
2999 ):
3000 config.getini("paths_not_list")
3001
3002 with pytest.raises(
3003 TypeError, match=r"expects a list of strings.*item at index 0 is int"
3004 ):
3005 config.getini("paths_list_with_int")
3006
3007 with pytest.raises(TypeError, match=r"expects a list for type 'args'.*got int"):
3008 config.getini("args_not_list")
3009
3010 with pytest.raises(
3011 TypeError, match=r"expects a list of strings.*item at index 1 is int"
3012 ):
3013 config.getini("args_list_with_int")
3014
3015 with pytest.raises(
3016 TypeError, match=r"expects a list for type 'linelist'.*got bool"
3017 ):
3018 config.getini("linelist_not_list")
3019
3020 with pytest.raises(
3021 TypeError, match=r"expects a list of strings.*item at index 1 is bool"
3022 ):
3023 config.getini("linelist_list_with_bool")
3024
3025 with pytest.raises(TypeError, match=r"expects a bool.*got str"):
3026 config.getini("bool_not_bool")
3027
3028 with pytest.raises(TypeError, match=r"expects an int.*got str"):
3029 config.getini("int_not_int")
3030
3031 with pytest.raises(TypeError, match=r"expects an int.*got bool"):
3032 config.getini("int_is_bool")
3033
3034 with pytest.raises(TypeError, match=r"expects a float.*got str"):
3035 config.getini("float_not_float")
3036
3037 with pytest.raises(TypeError, match=r"expects a float.*got bool"):
3038 config.getini("float_is_bool")
3039
3040 with pytest.raises(TypeError, match=r"expects a string.*got int"):
3041 config.getini("string_not_string")
3042
3043
3044 class TestInicfgDeprecation:
3045 """Tests for the deprecation of config.inicfg."""
3046
3047 def test_inicfg_deprecated(self, pytester: Pytester) -> None:
3048 """Test that accessing config.inicfg issues a deprecation warning."""
3049 pytester.makeini(
3050 """
3051 [pytest]
3052 minversion = 3.0
3053 """
3054 )
3055 config = pytester.parseconfig()
3056
3057 with pytest.warns(
3058 PytestDeprecationWarning, match=r"config\.inicfg is deprecated"
3059 ):
3060 inicfg = config.inicfg # type: ignore[deprecated]
3061
3062 assert config.getini("minversion") == "3.0"
3063 assert inicfg["minversion"] == "3.0"
3064 assert inicfg.get("minversion") == "3.0"
3065 del inicfg["minversion"]
3066 inicfg["minversion"] = "4.0"
3067 assert list(inicfg.keys()) == ["minversion"]
3068 assert list(inicfg.items()) == [("minversion", "4.0")]
3069 assert len(inicfg) == 1
3070
3071 def test_issue_13946_setting_bool_no_longer_crashes(
3072 self, pytester: Pytester
3073 ) -> None:
3074 """Regression test for #13946 - setting inicfg doesn't cause a crash."""
3075 pytester.makepyfile(
3076 """
3077 def pytest_configure(config):
3078 config.inicfg["xfail_strict"] = True
3079
3080 def test():
3081 pass
3082 """
3083 )
3084
3085 result = pytester.runpytest()
3086 assert result.ret == 0
3087
3088
3089 class TestProgName:
3090 """Test program name display in help and error messages (issue #1764)."""
3091
3092 def test_get_prog_name_direct_pytest(self) -> None:
3093 """When argv[0] is a pytest entry point, prog should be 'pytest'."""
3094 assert _get_prog_name(["/usr/bin/pytest", "--help"]) == "pytest"
3095 assert _get_prog_name(["pytest", "-v"]) == "pytest"
3096
3097 def test_get_prog_name_python_m_pytest(self) -> None:
3098 """When argv[0] is __main__.py, prog should be 'python -m pytest'."""
3099 assert (
3100 _get_prog_name(["/path/to/site-packages/pytest/__main__.py", "--help"])
3101 == "python -m pytest"
3102 )
3103 assert _get_prog_name(["__main__.py", "-v"]) == "python -m pytest"
3104
3105 def test_get_prog_name_empty_argv(self) -> None:
3106 """When argv is empty, should default to 'pytest'."""
3107 assert _get_prog_name([]) == "pytest"
3108
3109 def test_prog_in_error_message_programmatic(self, pytester: Pytester) -> None:
3110 """Error messages should show 'pytest.main()' when called programmatically.
3111
3112 runpytest_inprocess calls pytest.main() directly, so it should show
3113 pytest.main() as the program name.
3114 """
3115 result = pytester.runpytest_inprocess("--invalid-option-xyz")
3116 result.stderr.fnmatch_lines(["*pytest.main(): error:*invalid-option-xyz*"])
3117
3118 def test_prog_in_error_message_cli(self, pytester: Pytester) -> None:
3119 """Error messages should show 'python -m pytest' when called from CLI subprocess.
3120
3121 runpytest_subprocess runs pytest via 'python -m pytest', so it should
3122 show 'python -m pytest' as the program name.
3123 """
3124 result = pytester.runpytest_subprocess("--invalid-option-xyz")
3125 result.stderr.fnmatch_lines(["*python -m pytest: error:*invalid-option-xyz*"])
3126
3127 def test_prog_in_usage_programmatic(self, pytester: Pytester) -> None:
3128 """Usage line should show 'pytest.main()' when called programmatically."""
3129 result = pytester.runpytest_inprocess("--help")
3130 result.stdout.fnmatch_lines(["usage: pytest.main() *"])
3131
3132 def test_prog_in_usage_cli(self, pytester: Pytester) -> None:
3133 """Usage line should show 'python -m pytest' when called from CLI subprocess."""
3134 result = pytester.runpytest_subprocess("--help")
3135 result.stdout.fnmatch_lines(["usage: python -m pytest *"])
3136
3137 def test_console_main_deprecated(self, monkeypatch: pytest.MonkeyPatch) -> None:
3138 """Calling pytest.console_main() should emit a deprecation warning."""
3139 monkeypatch.setattr("_pytest.config._console_main", lambda: 0)
3140 with pytest.warns(
3141 pytest.PytestRemovedIn10Warning,
3142 match="pytest.console_main.*is deprecated",
3143 ):
3144 console_main()