forked from pytest-dev/pytest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_config.py
2183 lines (1935 loc) · 70.4 KB
/
test_config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dataclasses
import importlib.metadata
import os
import re
import sys
import textwrap
from pathlib import Path
from typing import Dict
from typing import List
from typing import Sequence
from typing import Tuple
from typing import Type
from typing import Union
import _pytest._code
import pytest
from _pytest.config import _get_plugin_specs_as_list
from _pytest.config import _iter_rewritable_modules
from _pytest.config import _strtobool
from _pytest.config import Config
from _pytest.config import ConftestImportFailure
from _pytest.config import ExitCode
from _pytest.config import parse_warning_filter
from _pytest.config.exceptions import UsageError
from _pytest.config.findpaths import determine_setup
from _pytest.config.findpaths import get_common_ancestor
from _pytest.config.findpaths import locate_config
from _pytest.monkeypatch import MonkeyPatch
from _pytest.pathlib import absolutepath
from _pytest.pytester import Pytester
class TestParseIni:
@pytest.mark.parametrize(
"section, filename", [("pytest", "pytest.ini"), ("tool:pytest", "setup.cfg")]
)
def test_getcfg_and_config(
self,
pytester: Pytester,
tmp_path: Path,
section: str,
filename: str,
monkeypatch: MonkeyPatch,
) -> None:
sub = tmp_path / "sub"
sub.mkdir()
monkeypatch.chdir(sub)
(tmp_path / filename).write_text(
textwrap.dedent(
"""\
[{section}]
name = value
""".format(
section=section
)
),
encoding="utf-8",
)
_, _, cfg = locate_config([sub])
assert cfg["name"] == "value"
config = pytester.parseconfigure(str(sub))
assert config.inicfg["name"] == "value"
def test_setupcfg_uses_toolpytest_with_pytest(self, pytester: Pytester) -> None:
p1 = pytester.makepyfile("def test(): pass")
pytester.makefile(
".cfg",
setup="""
[tool:pytest]
testpaths=%s
[pytest]
testpaths=ignored
"""
% p1.name,
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["configfile: setup.cfg", "* 1 passed in *"])
assert result.ret == 0
def test_append_parse_args(
self, pytester: Pytester, tmp_path: Path, monkeypatch: MonkeyPatch
) -> None:
monkeypatch.setenv("PYTEST_ADDOPTS", '--color no -rs --tb="short"')
tmp_path.joinpath("pytest.ini").write_text(
textwrap.dedent(
"""\
[pytest]
addopts = --verbose
"""
),
encoding="utf-8",
)
config = pytester.parseconfig(tmp_path)
assert config.option.color == "no"
assert config.option.reportchars == "s"
assert config.option.tbstyle == "short"
assert config.option.verbose
def test_tox_ini_wrong_version(self, pytester: Pytester) -> None:
pytester.makefile(
".ini",
tox="""
[pytest]
minversion=999.0
""",
)
result = pytester.runpytest()
assert result.ret != 0
result.stderr.fnmatch_lines(
["*tox.ini: 'minversion' requires pytest-999.0, actual pytest-*"]
)
@pytest.mark.parametrize(
"section, name",
[
("tool:pytest", "setup.cfg"),
("pytest", "tox.ini"),
("pytest", "pytest.ini"),
("pytest", ".pytest.ini"),
],
)
def test_ini_names(self, pytester: Pytester, name, section) -> None:
pytester.path.joinpath(name).write_text(
textwrap.dedent(
"""
[{section}]
minversion = 3.36
""".format(
section=section
)
),
encoding="utf-8",
)
config = pytester.parseconfig()
assert config.getini("minversion") == "3.36"
def test_pyproject_toml(self, pytester: Pytester) -> None:
pytester.makepyprojecttoml(
"""
[tool.pytest.ini_options]
minversion = "1.0"
"""
)
config = pytester.parseconfig()
assert config.getini("minversion") == "1.0"
def test_toxini_before_lower_pytestini(self, pytester: Pytester) -> None:
sub = pytester.mkdir("sub")
sub.joinpath("tox.ini").write_text(
textwrap.dedent(
"""
[pytest]
minversion = 2.0
"""
),
encoding="utf-8",
)
pytester.path.joinpath("pytest.ini").write_text(
textwrap.dedent(
"""
[pytest]
minversion = 1.5
"""
),
encoding="utf-8",
)
config = pytester.parseconfigure(sub)
assert config.getini("minversion") == "2.0"
def test_ini_parse_error(self, pytester: Pytester) -> None:
pytester.path.joinpath("pytest.ini").write_text(
"addopts = -x", encoding="utf-8"
)
result = pytester.runpytest()
assert result.ret != 0
result.stderr.fnmatch_lines("ERROR: *pytest.ini:1: no section header defined")
def test_toml_parse_error(self, pytester: Pytester) -> None:
pytester.makepyprojecttoml(
"""
\\"
"""
)
result = pytester.runpytest()
assert result.ret != 0
result.stderr.fnmatch_lines("ERROR: *pyproject.toml: Invalid statement*")
def test_confcutdir_default_without_configfile(self, pytester: Pytester) -> None:
# If --confcutdir is not specified, and there is no configfile, default
# to the roothpath.
sub = pytester.mkdir("sub")
os.chdir(sub)
config = pytester.parseconfigure()
assert config.pluginmanager._confcutdir == sub
def test_confcutdir_default_with_configfile(self, pytester: Pytester) -> None:
# If --confcutdir is not specified, and there is a configfile, default
# to the configfile's directory.
pytester.makeini("[pytest]")
sub = pytester.mkdir("sub")
os.chdir(sub)
config = pytester.parseconfigure()
assert config.pluginmanager._confcutdir == pytester.path
@pytest.mark.xfail(reason="probably not needed")
def test_confcutdir(self, pytester: Pytester) -> None:
sub = pytester.mkdir("sub")
os.chdir(sub)
pytester.makeini(
"""
[pytest]
addopts = --qwe
"""
)
result = pytester.inline_run("--confcutdir=.")
assert result.ret == 0
@pytest.mark.parametrize(
"ini_file_text, invalid_keys, warning_output, exception_text",
[
pytest.param(
"""
[pytest]
unknown_ini = value1
another_unknown_ini = value2
""",
["unknown_ini", "another_unknown_ini"],
[
"=*= warnings summary =*=",
"*PytestConfigWarning:*Unknown config option: another_unknown_ini",
"*PytestConfigWarning:*Unknown config option: unknown_ini",
],
"Unknown config option: another_unknown_ini",
id="2-unknowns",
),
pytest.param(
"""
[pytest]
unknown_ini = value1
minversion = 5.0.0
""",
["unknown_ini"],
[
"=*= warnings summary =*=",
"*PytestConfigWarning:*Unknown config option: unknown_ini",
],
"Unknown config option: unknown_ini",
id="1-unknown",
),
pytest.param(
"""
[some_other_header]
unknown_ini = value1
[pytest]
minversion = 5.0.0
""",
[],
[],
"",
id="unknown-in-other-header",
),
pytest.param(
"""
[pytest]
minversion = 5.0.0
""",
[],
[],
"",
id="no-unknowns",
),
pytest.param(
"""
[pytest]
conftest_ini_key = 1
""",
[],
[],
"",
id="1-known",
),
],
)
@pytest.mark.filterwarnings("default")
def test_invalid_config_options(
self,
pytester: Pytester,
ini_file_text,
invalid_keys,
warning_output,
exception_text,
) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("conftest_ini_key", "")
"""
)
pytester.makepyfile("def test(): pass")
pytester.makeini(ini_file_text)
config = pytester.parseconfig()
assert sorted(config._get_unknown_ini_keys()) == sorted(invalid_keys)
result = pytester.runpytest()
result.stdout.fnmatch_lines(warning_output)
result = pytester.runpytest("--strict-config")
if exception_text:
result.stderr.fnmatch_lines("ERROR: " + exception_text)
assert result.ret == pytest.ExitCode.USAGE_ERROR
else:
result.stderr.no_fnmatch_line(exception_text)
assert result.ret == pytest.ExitCode.OK
@pytest.mark.filterwarnings("default")
def test_silence_unknown_key_warning(self, pytester: Pytester) -> None:
"""Unknown config key warnings can be silenced using filterwarnings (#7620)"""
pytester.makeini(
"""
[pytest]
filterwarnings =
ignore:Unknown config option:pytest.PytestConfigWarning
foobar=1
"""
)
result = pytester.runpytest()
result.stdout.no_fnmatch_line("*PytestConfigWarning*")
@pytest.mark.filterwarnings("default::pytest.PytestConfigWarning")
def test_disable_warnings_plugin_disables_config_warnings(
self, pytester: Pytester
) -> None:
"""Disabling 'warnings' plugin also disables config time warnings"""
pytester.makeconftest(
"""
import pytest
def pytest_configure(config):
config.issue_config_time_warning(
pytest.PytestConfigWarning("custom config warning"),
stacklevel=2,
)
"""
)
result = pytester.runpytest("-pno:warnings")
result.stdout.no_fnmatch_line("*PytestConfigWarning*")
@pytest.mark.parametrize(
"ini_file_text, plugin_version, exception_text",
[
pytest.param(
"""
[pytest]
required_plugins = a z
""",
"1.5",
"Missing required plugins: a, z",
id="2-missing",
),
pytest.param(
"""
[pytest]
required_plugins = a z myplugin
""",
"1.5",
"Missing required plugins: a, z",
id="2-missing-1-ok",
),
pytest.param(
"""
[pytest]
required_plugins = myplugin
""",
"1.5",
None,
id="1-ok",
),
pytest.param(
"""
[pytest]
required_plugins = myplugin==1.5
""",
"1.5",
None,
id="1-ok-pin-exact",
),
pytest.param(
"""
[pytest]
required_plugins = myplugin>1.0,<2.0
""",
"1.5",
None,
id="1-ok-pin-loose",
),
pytest.param(
"""
[pytest]
required_plugins = myplugin
""",
"1.5a1",
None,
id="1-ok-prerelease",
),
pytest.param(
"""
[pytest]
required_plugins = myplugin==1.6
""",
"1.5",
"Missing required plugins: myplugin==1.6",
id="missing-version",
),
pytest.param(
"""
[pytest]
required_plugins = myplugin==1.6 other==1.0
""",
"1.5",
"Missing required plugins: myplugin==1.6, other==1.0",
id="missing-versions",
),
pytest.param(
"""
[some_other_header]
required_plugins = won't be triggered
[pytest]
""",
"1.5",
None,
id="invalid-header",
),
],
)
def test_missing_required_plugins(
self,
pytester: Pytester,
monkeypatch: MonkeyPatch,
ini_file_text: str,
plugin_version: str,
exception_text: str,
) -> None:
"""Check 'required_plugins' option with various settings.
This test installs a mock "myplugin-1.5" which is used in the parametrized test cases.
"""
@dataclasses.dataclass
class DummyEntryPoint:
name: str
module: str
group: str = "pytest11"
def load(self):
__import__(self.module)
return sys.modules[self.module]
entry_points = [
DummyEntryPoint("myplugin1", "myplugin1_module"),
]
@dataclasses.dataclass
class DummyDist:
entry_points: object
files: object = ()
version: str = plugin_version
@property
def metadata(self):
return {"name": "myplugin"}
def my_dists():
return [DummyDist(entry_points)]
pytester.makepyfile(myplugin1_module="# my plugin module")
pytester.syspathinsert()
monkeypatch.setattr(importlib.metadata, "distributions", my_dists)
monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
pytester.makeini(ini_file_text)
if exception_text:
with pytest.raises(pytest.UsageError, match=exception_text):
pytester.parseconfig()
else:
pytester.parseconfig()
def test_early_config_cmdline(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
"""early_config contains options registered by third-party plugins.
This is a regression involving pytest-cov (and possibly others) introduced in #7700.
"""
pytester.makepyfile(
myplugin="""
def pytest_addoption(parser):
parser.addoption('--foo', default=None, dest='foo')
def pytest_load_initial_conftests(early_config, parser, args):
assert early_config.known_args_namespace.foo == "1"
"""
)
monkeypatch.setenv("PYTEST_PLUGINS", "myplugin")
pytester.syspathinsert()
result = pytester.runpytest("--foo=1")
result.stdout.fnmatch_lines("* no tests ran in *")
def test_args_source_args(self, pytester: Pytester):
config = pytester.parseconfig("--", "test_filename.py")
assert config.args_source == Config.ArgsSource.ARGS
def test_args_source_invocation_dir(self, pytester: Pytester):
config = pytester.parseconfig()
assert config.args_source == Config.ArgsSource.INVOCATION_DIR
def test_args_source_testpaths(self, pytester: Pytester):
pytester.makeini(
"""
[pytest]
testpaths=*
"""
)
config = pytester.parseconfig()
assert config.args_source == Config.ArgsSource.TESTPATHS
class TestConfigCmdlineParsing:
def test_parsing_again_fails(self, pytester: Pytester) -> None:
config = pytester.parseconfig()
pytest.raises(AssertionError, lambda: config.parse([]))
def test_explicitly_specified_config_file_is_loaded(
self, pytester: Pytester
) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("custom", "")
"""
)
pytester.makeini(
"""
[pytest]
custom = 0
"""
)
pytester.makefile(
".ini",
custom="""
[pytest]
custom = 1
""",
)
config = pytester.parseconfig("-c", "custom.ini")
assert config.getini("custom") == "1"
config = pytester.parseconfig("--config-file", "custom.ini")
assert config.getini("custom") == "1"
pytester.makefile(
".cfg",
custom_tool_pytest_section="""
[tool:pytest]
custom = 1
""",
)
config = pytester.parseconfig("-c", "custom_tool_pytest_section.cfg")
assert config.getini("custom") == "1"
config = pytester.parseconfig("--config-file", "custom_tool_pytest_section.cfg")
assert config.getini("custom") == "1"
pytester.makefile(
".toml",
custom="""
[tool.pytest.ini_options]
custom = 1
value = [
] # this is here on purpose, as it makes this an invalid '.ini' file
""",
)
config = pytester.parseconfig("-c", "custom.toml")
assert config.getini("custom") == "1"
config = pytester.parseconfig("--config-file", "custom.toml")
assert config.getini("custom") == "1"
def test_absolute_win32_path(self, pytester: Pytester) -> None:
temp_ini_file = pytester.makefile(
".ini",
custom="""
[pytest]
addopts = --version
""",
)
from os.path import normpath
temp_ini_file_norm = normpath(str(temp_ini_file))
ret = pytest.main(["-c", temp_ini_file_norm])
assert ret == ExitCode.OK
ret = pytest.main(["--config-file", temp_ini_file_norm])
assert ret == ExitCode.OK
class TestConfigAPI:
def test_config_trace(self, pytester: Pytester) -> None:
config = pytester.parseconfig()
values: List[str] = []
config.trace.root.setwriter(values.append)
config.trace("hello")
assert len(values) == 1
assert values[0] == "hello [config]\n"
def test_config_getoption(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addoption("--hello", "-X", dest="hello")
"""
)
config = pytester.parseconfig("--hello=this")
for x in ("hello", "--hello", "-X"):
assert config.getoption(x) == "this"
pytest.raises(ValueError, config.getoption, "qweqwe")
def test_config_getoption_unicode(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addoption('--hello', type=str)
"""
)
config = pytester.parseconfig("--hello=this")
assert config.getoption("hello") == "this"
def test_config_getvalueorskip(self, pytester: Pytester) -> None:
config = pytester.parseconfig()
pytest.raises(pytest.skip.Exception, config.getvalueorskip, "hello")
verbose = config.getvalueorskip("verbose")
assert verbose == config.option.verbose
def test_config_getvalueorskip_None(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addoption("--hello")
"""
)
config = pytester.parseconfig()
with pytest.raises(pytest.skip.Exception):
config.getvalueorskip("hello")
def test_getoption(self, pytester: Pytester) -> None:
config = pytester.parseconfig()
with pytest.raises(ValueError):
config.getvalue("x")
assert config.getoption("x", 1) == 1
def test_getconftest_pathlist(self, pytester: Pytester, tmp_path: Path) -> None:
somepath = tmp_path.joinpath("x", "y", "z")
p = tmp_path.joinpath("conftest.py")
p.write_text(f"mylist = {['.', str(somepath)]}", encoding="utf-8")
config = pytester.parseconfigure(p)
assert config._getconftest_pathlist("notexist", path=tmp_path) is None
assert config._getconftest_pathlist("mylist", path=tmp_path) == [
tmp_path,
somepath,
]
@pytest.mark.parametrize("maybe_type", ["not passed", "None", '"string"'])
def test_addini(self, pytester: Pytester, maybe_type: str) -> None:
if maybe_type == "not passed":
type_string = ""
else:
type_string = f", {maybe_type}"
pytester.makeconftest(
f"""
def pytest_addoption(parser):
parser.addini("myname", "my new ini value"{type_string})
"""
)
pytester.makeini(
"""
[pytest]
myname=hello
"""
)
config = pytester.parseconfig()
val = config.getini("myname")
assert val == "hello"
pytest.raises(ValueError, config.getini, "other")
@pytest.mark.parametrize("config_type", ["ini", "pyproject"])
def test_addini_paths(self, pytester: Pytester, config_type: str) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("paths", "my new ini value", type="paths")
parser.addini("abc", "abc value")
"""
)
if config_type == "ini":
inipath = pytester.makeini(
"""
[pytest]
paths=hello world/sub.py
"""
)
elif config_type == "pyproject":
inipath = pytester.makepyprojecttoml(
"""
[tool.pytest.ini_options]
paths=["hello", "world/sub.py"]
"""
)
config = pytester.parseconfig()
values = config.getini("paths")
assert len(values) == 2
assert values[0] == inipath.parent.joinpath("hello")
assert values[1] == inipath.parent.joinpath("world/sub.py")
pytest.raises(ValueError, config.getini, "other")
def make_conftest_for_args(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("args", "new args", type="args")
parser.addini("a2", "", "args", default="1 2 3".split())
"""
)
def test_addini_args_ini_files(self, pytester: Pytester) -> None:
self.make_conftest_for_args(pytester)
pytester.makeini(
"""
[pytest]
args=123 "123 hello" "this"
"""
)
self.check_config_args(pytester)
def test_addini_args_pyproject_toml(self, pytester: Pytester) -> None:
self.make_conftest_for_args(pytester)
pytester.makepyprojecttoml(
"""
[tool.pytest.ini_options]
args = ["123", "123 hello", "this"]
"""
)
self.check_config_args(pytester)
def check_config_args(self, pytester: Pytester) -> None:
config = pytester.parseconfig()
values = config.getini("args")
assert values == ["123", "123 hello", "this"]
values = config.getini("a2")
assert values == list("123")
def make_conftest_for_linelist(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("xy", "", type="linelist")
parser.addini("a2", "", "linelist")
"""
)
def test_addini_linelist_ini_files(self, pytester: Pytester) -> None:
self.make_conftest_for_linelist(pytester)
pytester.makeini(
"""
[pytest]
xy= 123 345
second line
"""
)
self.check_config_linelist(pytester)
def test_addini_linelist_pprojecttoml(self, pytester: Pytester) -> None:
self.make_conftest_for_linelist(pytester)
pytester.makepyprojecttoml(
"""
[tool.pytest.ini_options]
xy = ["123 345", "second line"]
"""
)
self.check_config_linelist(pytester)
def check_config_linelist(self, pytester: Pytester) -> None:
config = pytester.parseconfig()
values = config.getini("xy")
assert len(values) == 2
assert values == ["123 345", "second line"]
values = config.getini("a2")
assert values == []
@pytest.mark.parametrize(
"str_val, bool_val", [("True", True), ("no", False), ("no-ini", True)]
)
def test_addini_bool(
self, pytester: Pytester, str_val: str, bool_val: bool
) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("strip", "", type="bool", default=True)
"""
)
if str_val != "no-ini":
pytester.makeini(
"""
[pytest]
strip=%s
"""
% str_val
)
config = pytester.parseconfig()
assert config.getini("strip") is bool_val
def test_addinivalue_line_existing(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("xy", "", type="linelist")
"""
)
pytester.makeini(
"""
[pytest]
xy= 123
"""
)
config = pytester.parseconfig()
values = config.getini("xy")
assert len(values) == 1
assert values == ["123"]
config.addinivalue_line("xy", "456")
values = config.getini("xy")
assert len(values) == 2
assert values == ["123", "456"]
def test_addinivalue_line_new(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("xy", "", type="linelist")
"""
)
config = pytester.parseconfig()
assert not config.getini("xy")
config.addinivalue_line("xy", "456")
values = config.getini("xy")
assert len(values) == 1
assert values == ["456"]
config.addinivalue_line("xy", "123")
values = config.getini("xy")
assert len(values) == 2
assert values == ["456", "123"]
def test_confcutdir_check_isdir(self, pytester: Pytester) -> None:
"""Give an error if --confcutdir is not a valid directory (#2078)"""
exp_match = r"^--confcutdir must be a directory, given: "
with pytest.raises(pytest.UsageError, match=exp_match):
pytester.parseconfig("--confcutdir", pytester.path.joinpath("file"))
with pytest.raises(pytest.UsageError, match=exp_match):
pytester.parseconfig("--confcutdir", pytester.path.joinpath("nonexistent"))
p = pytester.mkdir("dir")
config = pytester.parseconfig("--confcutdir", p)
assert config.getoption("confcutdir") == str(p)
@pytest.mark.parametrize(
"names, expected",
[
# dist-info based distributions root are files as will be put in PYTHONPATH
(["bar.py"], ["bar"]),
(["foo/bar.py"], ["bar"]),
(["foo/bar.pyc"], []),
(["foo/__init__.py"], ["foo"]),
(["bar/__init__.py", "xz.py"], ["bar", "xz"]),
(["setup.py"], []),
# egg based distributions root contain the files from the dist root
(["src/bar/__init__.py"], ["bar"]),
(["src/bar/__init__.py", "setup.py"], ["bar"]),
(["source/python/bar/__init__.py", "setup.py"], ["bar"]),
# editable installation finder modules
(["__editable___xyz_finder.py"], []),
(["bar/__init__.py", "__editable___xyz_finder.py"], ["bar"]),
],
)
def test_iter_rewritable_modules(self, names, expected) -> None:
assert list(_iter_rewritable_modules(names)) == expected
class TestConfigFromdictargs:
def test_basic_behavior(self, _sys_snapshot) -> None:
option_dict = {"verbose": 444, "foo": "bar", "capture": "no"}
args = ["a", "b"]
config = Config.fromdictargs(option_dict, args)
with pytest.raises(AssertionError):
config.parse(["should refuse to parse again"])
assert config.option.verbose == 444
assert config.option.foo == "bar"
assert config.option.capture == "no"
assert config.args == args
def test_invocation_params_args(self, _sys_snapshot) -> None:
"""Show that fromdictargs can handle args in their "orig" format"""
option_dict: Dict[str, object] = {}
args = ["-vvvv", "-s", "a", "b"]
config = Config.fromdictargs(option_dict, args)
assert config.args == ["a", "b"]
assert config.invocation_params.args == tuple(args)
assert config.option.verbose == 4
assert config.option.capture == "no"
def test_inifilename(self, tmp_path: Path) -> None:
d1 = tmp_path.joinpath("foo")
d1.mkdir()
p1 = d1.joinpath("bar.ini")
p1.touch()
p1.write_text(
textwrap.dedent(
"""\
[pytest]
name = value
"""
),
encoding="utf-8",
)
inifilename = "../../foo/bar.ini"
option_dict = {"inifilename": inifilename, "capture": "no"}
cwd = tmp_path.joinpath("a/b")
cwd.mkdir(parents=True)
p2 = cwd.joinpath("pytest.ini")
p2.touch()
p2.write_text(
textwrap.dedent(
"""\
[pytest]
name = wrong-value
should_not_be_set = true
"""
),
encoding="utf-8",
)
with MonkeyPatch.context() as mp:
mp.chdir(cwd)
config = Config.fromdictargs(option_dict, ())
inipath = absolutepath(inifilename)
assert config.args == [str(cwd)]
assert config.option.inifilename == inifilename
assert config.option.capture == "no"
# this indicates this is the file used for getting configuration values
assert config.inipath == inipath
assert config.inicfg.get("name") == "value"
assert config.inicfg.get("should_not_be_set") is None
def test_options_on_small_file_do_not_blow_up(pytester: Pytester) -> None:
def runfiletest(opts: Sequence[str]) -> None:
reprec = pytester.inline_run(*opts)
passed, skipped, failed = reprec.countoutcomes()
assert failed == 2
assert skipped == passed == 0
path = str(
pytester.makepyfile(
"""
def test_f1(): assert 0
def test_f2(): assert 0
"""
)
)
runfiletest([path])
runfiletest(["-l", path])
runfiletest(["-s", path])
runfiletest(["--tb=no", path])
runfiletest(["--tb=short", path])
runfiletest(["--tb=long", path])
runfiletest(["--fulltrace", path])
runfiletest(["--traceconfig", path])
runfiletest(["-v", path])
runfiletest(["-v", "-v", path])
def test_preparse_ordering_with_setuptools(
pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
class EntryPoint:
name = "mytestplugin"