-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathmetafunc.py
1901 lines (1617 loc) · 61.8 KB
/
metafunc.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 itertools
import re
import sys
import textwrap
from typing import Any
from typing import cast
from typing import Dict
from typing import Iterator
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
import attr
import hypothesis
from hypothesis import strategies
import pytest
from _pytest import fixtures
from _pytest import python
from _pytest.compat import _format_args
from _pytest.compat import getfuncargnames
from _pytest.compat import NOTSET
from _pytest.outcomes import fail
from _pytest.pytester import Pytester
from _pytest.python import _idval
from _pytest.python import idmaker
class TestMetafunc:
def Metafunc(self, func, config=None) -> python.Metafunc:
# The unit tests of this class check if things work correctly
# on the funcarg level, so we don't need a full blown
# initialization.
class FuncFixtureInfoMock:
name2fixturedefs = None
def __init__(self, names):
self.names_closure = names
@attr.s
class DefinitionMock(python.FunctionDefinition):
obj = attr.ib()
_nodeid = attr.ib()
names = getfuncargnames(func)
fixtureinfo: Any = FuncFixtureInfoMock(names)
definition: Any = DefinitionMock._create(func, "mock::nodeid")
return python.Metafunc(definition, fixtureinfo, config, _ispytest=True)
def test_no_funcargs(self) -> None:
def function():
pass
metafunc = self.Metafunc(function)
assert not metafunc.fixturenames
repr(metafunc._calls)
def test_function_basic(self) -> None:
def func(arg1, arg2="qwe"):
pass
metafunc = self.Metafunc(func)
assert len(metafunc.fixturenames) == 1
assert "arg1" in metafunc.fixturenames
assert metafunc.function is func
assert metafunc.cls is None
def test_parametrize_error(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2])
pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5, 6]))
pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5, 6]))
metafunc.parametrize("y", [1, 2])
pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5, 6]))
pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5, 6]))
with pytest.raises(TypeError, match="^ids must be a callable or an iterable$"):
metafunc.parametrize("y", [5, 6], ids=42) # type: ignore[arg-type]
def test_parametrize_error_iterator(self) -> None:
def func(x):
raise NotImplementedError()
class Exc(Exception):
def __repr__(self):
return "Exc(from_gen)"
def gen() -> Iterator[Union[int, None, Exc]]:
yield 0
yield None
yield Exc()
metafunc = self.Metafunc(func)
# When the input is an iterator, only len(args) are taken,
# so the bad Exc isn't reached.
metafunc.parametrize("x", [1, 2], ids=gen()) # type: ignore[arg-type]
assert [(x.funcargs, x.id) for x in metafunc._calls] == [
({"x": 1}, "0"),
({"x": 2}, "2"),
]
with pytest.raises(
fail.Exception,
match=(
r"In func: ids must be list of string/float/int/bool, found:"
r" Exc\(from_gen\) \(type: <class .*Exc'>\) at index 2"
),
):
metafunc.parametrize("x", [1, 2, 3], ids=gen()) # type: ignore[arg-type]
def test_parametrize_bad_scope(self) -> None:
def func(x):
pass
metafunc = self.Metafunc(func)
with pytest.raises(
fail.Exception,
match=r"parametrize\(\) call in func got an unexpected scope value 'doggy'",
):
metafunc.parametrize("x", [1], scope="doggy") # type: ignore[arg-type]
def test_parametrize_request_name(self, pytester: Pytester) -> None:
"""Show proper error when 'request' is used as a parameter name in parametrize (#6183)"""
def func(request):
raise NotImplementedError()
metafunc = self.Metafunc(func)
with pytest.raises(
fail.Exception,
match=r"'request' is a reserved name and cannot be used in @pytest.mark.parametrize",
):
metafunc.parametrize("request", [1])
def test_find_parametrized_scope(self) -> None:
"""Unit test for _find_parametrized_scope (#3941)."""
from _pytest.python import _find_parametrized_scope
@attr.s
class DummyFixtureDef:
scope = attr.ib()
fixtures_defs = cast(
Dict[str, Sequence[fixtures.FixtureDef[object]]],
dict(
session_fix=[DummyFixtureDef("session")],
package_fix=[DummyFixtureDef("package")],
module_fix=[DummyFixtureDef("module")],
class_fix=[DummyFixtureDef("class")],
func_fix=[DummyFixtureDef("function")],
),
)
# use arguments to determine narrow scope; the cause of the bug is that it would look on all
# fixture defs given to the method
def find_scope(argnames, indirect):
return _find_parametrized_scope(argnames, fixtures_defs, indirect=indirect)
assert find_scope(["func_fix"], indirect=True) == "function"
assert find_scope(["class_fix"], indirect=True) == "class"
assert find_scope(["module_fix"], indirect=True) == "module"
assert find_scope(["package_fix"], indirect=True) == "package"
assert find_scope(["session_fix"], indirect=True) == "session"
assert find_scope(["class_fix", "func_fix"], indirect=True) == "function"
assert find_scope(["func_fix", "session_fix"], indirect=True) == "function"
assert find_scope(["session_fix", "class_fix"], indirect=True) == "class"
assert find_scope(["package_fix", "session_fix"], indirect=True) == "package"
assert find_scope(["module_fix", "session_fix"], indirect=True) == "module"
# when indirect is False or is not for all scopes, always use function
assert find_scope(["session_fix", "module_fix"], indirect=False) == "function"
assert (
find_scope(["session_fix", "module_fix"], indirect=["module_fix"])
== "function"
)
assert (
find_scope(
["session_fix", "module_fix"], indirect=["session_fix", "module_fix"]
)
== "module"
)
def test_parametrize_and_id(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2], ids=["basic", "advanced"])
metafunc.parametrize("y", ["abc", "def"])
ids = [x.id for x in metafunc._calls]
assert ids == ["basic-abc", "basic-def", "advanced-abc", "advanced-def"]
def test_parametrize_and_id_unicode(self) -> None:
"""Allow unicode strings for "ids" parameter in Python 2 (##1905)"""
def func(x):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2], ids=["basic", "advanced"])
ids = [x.id for x in metafunc._calls]
assert ids == ["basic", "advanced"]
def test_parametrize_with_wrong_number_of_ids(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
with pytest.raises(fail.Exception):
metafunc.parametrize("x", [1, 2], ids=["basic"])
with pytest.raises(fail.Exception):
metafunc.parametrize(
("x", "y"), [("abc", "def"), ("ghi", "jkl")], ids=["one"]
)
def test_parametrize_ids_iterator_without_mark(self) -> None:
def func(x, y):
pass
it = itertools.count()
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2], ids=it)
metafunc.parametrize("y", [3, 4], ids=it)
ids = [x.id for x in metafunc._calls]
assert ids == ["0-2", "0-3", "1-2", "1-3"]
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2], ids=it)
metafunc.parametrize("y", [3, 4], ids=it)
ids = [x.id for x in metafunc._calls]
assert ids == ["4-6", "4-7", "5-6", "5-7"]
def test_parametrize_empty_list(self) -> None:
"""#510"""
def func(y):
pass
class MockConfig:
def getini(self, name):
return ""
@property
def hook(self):
return self
def pytest_make_parametrize_id(self, **kw):
pass
metafunc = self.Metafunc(func, MockConfig())
metafunc.parametrize("y", [])
assert "skip" == metafunc._calls[0].marks[0].name
def test_parametrize_with_userobjects(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
class A:
pass
metafunc.parametrize("x", [A(), A()])
metafunc.parametrize("y", list("ab"))
assert metafunc._calls[0].id == "x0-a"
assert metafunc._calls[1].id == "x0-b"
assert metafunc._calls[2].id == "x1-a"
assert metafunc._calls[3].id == "x1-b"
@hypothesis.given(strategies.text() | strategies.binary())
@hypothesis.settings(
deadline=400.0
) # very close to std deadline and CI boxes are not reliable in CPU power
def test_idval_hypothesis(self, value) -> None:
escaped = _idval(value, "a", 6, None, nodeid=None, config=None)
assert isinstance(escaped, str)
escaped.encode("ascii")
def test_unicode_idval(self) -> None:
"""Test that Unicode strings outside the ASCII character set get
escaped, using byte escapes if they're in that range or unicode
escapes if they're not.
"""
values = [
("", r""),
("ascii", r"ascii"),
("ação", r"a\xe7\xe3o"),
("josé@blah.com", r"jos\[email protected]"),
(
r"δοκ.ιμή@παράδειγμα.δοκιμή",
r"\u03b4\u03bf\u03ba.\u03b9\u03bc\u03ae@\u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3"
r"\u03bc\u03b1.\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae",
),
]
for val, expected in values:
assert _idval(val, "a", 6, None, nodeid=None, config=None) == expected
def test_unicode_idval_with_config(self) -> None:
"""Unit test for expected behavior to obtain ids with
disable_test_id_escaping_and_forfeit_all_rights_to_community_support
option (#5294)."""
class MockConfig:
def __init__(self, config):
self.config = config
@property
def hook(self):
return self
def pytest_make_parametrize_id(self, **kw):
pass
def getini(self, name):
return self.config[name]
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values: List[Tuple[str, Any, str]] = [
("ação", MockConfig({option: True}), "ação"),
("ação", MockConfig({option: False}), "a\\xe7\\xe3o"),
]
for val, config, expected in values:
actual = _idval(val, "a", 6, None, nodeid=None, config=config)
assert actual == expected
def test_bytes_idval(self) -> None:
"""Unit test for the expected behavior to obtain ids for parametrized
bytes values: bytes objects are always escaped using "binary escape"."""
values = [
(b"", r""),
(b"\xc3\xb4\xff\xe4", r"\xc3\xb4\xff\xe4"),
(b"ascii", r"ascii"),
("αρά".encode(), r"\xce\xb1\xcf\x81\xce\xac"),
]
for val, expected in values:
assert _idval(val, "a", 6, idfn=None, nodeid=None, config=None) == expected
def test_class_or_function_idval(self) -> None:
"""Unit test for the expected behavior to obtain ids for parametrized
values that are classes or functions: their __name__."""
class TestClass:
pass
def test_function():
pass
values = [(TestClass, "TestClass"), (test_function, "test_function")]
for val, expected in values:
assert _idval(val, "a", 6, None, nodeid=None, config=None) == expected
def test_notset_idval(self) -> None:
"""Test that a NOTSET value (used by an empty parameterset) generates
a proper ID.
Regression test for #7686.
"""
assert _idval(NOTSET, "a", 0, None, nodeid=None, config=None) == "a0"
def test_idmaker_autoname(self) -> None:
"""#250"""
result = idmaker(
("a", "b"), [pytest.param("string", 1.0), pytest.param("st-ring", 2.0)]
)
assert result == ["string-1.0", "st-ring-2.0"]
result = idmaker(
("a", "b"), [pytest.param(object(), 1.0), pytest.param(object(), object())]
)
assert result == ["a0-1.0", "a1-b1"]
# unicode mixing, issue250
result = idmaker(("a", "b"), [pytest.param({}, b"\xc3\xb4")])
assert result == ["a0-\\xc3\\xb4"]
def test_idmaker_with_bytes_regex(self) -> None:
result = idmaker(("a"), [pytest.param(re.compile(b"foo"), 1.0)])
assert result == ["foo"]
def test_idmaker_native_strings(self) -> None:
result = idmaker(
("a", "b"),
[
pytest.param(1.0, -1.1),
pytest.param(2, -202),
pytest.param("three", "three hundred"),
pytest.param(True, False),
pytest.param(None, None),
pytest.param(re.compile("foo"), re.compile("bar")),
pytest.param(str, int),
pytest.param(list("six"), [66, 66]),
pytest.param({7}, set("seven")),
pytest.param(tuple("eight"), (8, -8, 8)),
pytest.param(b"\xc3\xb4", b"name"),
pytest.param(b"\xc3\xb4", "other"),
],
)
assert result == [
"1.0--1.1",
"2--202",
"three-three hundred",
"True-False",
"None-None",
"foo-bar",
"str-int",
"a7-b7",
"a8-b8",
"a9-b9",
"\\xc3\\xb4-name",
"\\xc3\\xb4-other",
]
def test_idmaker_non_printable_characters(self) -> None:
result = idmaker(
("s", "n"),
[
pytest.param("\x00", 1),
pytest.param("\x05", 2),
pytest.param(b"\x00", 3),
pytest.param(b"\x05", 4),
pytest.param("\t", 5),
pytest.param(b"\t", 6),
],
)
assert result == ["\\x00-1", "\\x05-2", "\\x00-3", "\\x05-4", "\\t-5", "\\t-6"]
def test_idmaker_manual_ids_must_be_printable(self) -> None:
result = idmaker(
("s",),
[
pytest.param("x00", id="hello \x00"),
pytest.param("x05", id="hello \x05"),
],
)
assert result == ["hello \\x00", "hello \\x05"]
def test_idmaker_enum(self) -> None:
enum = pytest.importorskip("enum")
e = enum.Enum("Foo", "one, two")
result = idmaker(("a", "b"), [pytest.param(e.one, e.two)])
assert result == ["Foo.one-Foo.two"]
def test_idmaker_idfn(self) -> None:
"""#351"""
def ids(val: object) -> Optional[str]:
if isinstance(val, Exception):
return repr(val)
return None
result = idmaker(
("a", "b"),
[
pytest.param(10.0, IndexError()),
pytest.param(20, KeyError()),
pytest.param("three", [1, 2, 3]),
],
idfn=ids,
)
assert result == ["10.0-IndexError()", "20-KeyError()", "three-b2"]
def test_idmaker_idfn_unique_names(self) -> None:
"""#351"""
def ids(val: object) -> str:
return "a"
result = idmaker(
("a", "b"),
[
pytest.param(10.0, IndexError()),
pytest.param(20, KeyError()),
pytest.param("three", [1, 2, 3]),
],
idfn=ids,
)
assert result == ["a-a0", "a-a1", "a-a2"]
def test_idmaker_with_idfn_and_config(self) -> None:
"""Unit test for expected behavior to create ids with idfn and
disable_test_id_escaping_and_forfeit_all_rights_to_community_support
option (#5294).
"""
class MockConfig:
def __init__(self, config):
self.config = config
@property
def hook(self):
return self
def pytest_make_parametrize_id(self, **kw):
pass
def getini(self, name):
return self.config[name]
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values: List[Tuple[Any, str]] = [
(MockConfig({option: True}), "ação"),
(MockConfig({option: False}), "a\\xe7\\xe3o"),
]
for config, expected in values:
result = idmaker(
("a",),
[pytest.param("string")],
idfn=lambda _: "ação",
config=config,
)
assert result == [expected]
def test_idmaker_with_ids_and_config(self) -> None:
"""Unit test for expected behavior to create ids with ids and
disable_test_id_escaping_and_forfeit_all_rights_to_community_support
option (#5294).
"""
class MockConfig:
def __init__(self, config):
self.config = config
@property
def hook(self):
return self
def pytest_make_parametrize_id(self, **kw):
pass
def getini(self, name):
return self.config[name]
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values: List[Tuple[Any, str]] = [
(MockConfig({option: True}), "ação"),
(MockConfig({option: False}), "a\\xe7\\xe3o"),
]
for config, expected in values:
result = idmaker(
("a",),
[pytest.param("string")],
ids=["ação"],
config=config,
)
assert result == [expected]
def test_parametrize_ids_exception(self, pytester: Pytester) -> None:
"""
:param pytester: the instance of Pytester class, a temporary
test directory.
"""
pytester.makepyfile(
"""
import pytest
def ids(arg):
raise Exception("bad ids")
@pytest.mark.parametrize("arg", ["a", "b"], ids=ids)
def test_foo(arg):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*Exception: bad ids",
"*test_foo: error raised while trying to determine id of parameter 'arg' at position 0",
]
)
def test_parametrize_ids_returns_non_string(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""\
import pytest
def ids(d):
return d
@pytest.mark.parametrize("arg", ({1: 2}, {3, 4}), ids=ids)
def test(arg):
assert arg
@pytest.mark.parametrize("arg", (1, 2.0, True), ids=ids)
def test_int(arg):
assert arg
"""
)
result = pytester.runpytest("-vv", "-s")
result.stdout.fnmatch_lines(
[
"test_parametrize_ids_returns_non_string.py::test[arg0] PASSED",
"test_parametrize_ids_returns_non_string.py::test[arg1] PASSED",
"test_parametrize_ids_returns_non_string.py::test_int[1] PASSED",
"test_parametrize_ids_returns_non_string.py::test_int[2.0] PASSED",
"test_parametrize_ids_returns_non_string.py::test_int[True] PASSED",
]
)
def test_idmaker_with_ids(self) -> None:
result = idmaker(
("a", "b"), [pytest.param(1, 2), pytest.param(3, 4)], ids=["a", None]
)
assert result == ["a", "3-4"]
def test_idmaker_with_paramset_id(self) -> None:
result = idmaker(
("a", "b"),
[pytest.param(1, 2, id="me"), pytest.param(3, 4, id="you")],
ids=["a", None],
)
assert result == ["me", "you"]
def test_idmaker_with_ids_unique_names(self) -> None:
result = idmaker(
("a"), map(pytest.param, [1, 2, 3, 4, 5]), ids=["a", "a", "b", "c", "b"]
)
assert result == ["a0", "a1", "b0", "c", "b1"]
def test_parametrize_indirect(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1], indirect=True)
metafunc.parametrize("y", [2, 3], indirect=True)
assert len(metafunc._calls) == 2
assert metafunc._calls[0].funcargs == {}
assert metafunc._calls[1].funcargs == {}
assert metafunc._calls[0].params == dict(x=1, y=2)
assert metafunc._calls[1].params == dict(x=1, y=3)
def test_parametrize_indirect_list(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x, y", [("a", "b")], indirect=["x"])
assert metafunc._calls[0].funcargs == dict(y="b")
assert metafunc._calls[0].params == dict(x="a")
def test_parametrize_indirect_list_all(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x, y", [("a", "b")], indirect=["x", "y"])
assert metafunc._calls[0].funcargs == {}
assert metafunc._calls[0].params == dict(x="a", y="b")
def test_parametrize_indirect_list_empty(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x, y", [("a", "b")], indirect=[])
assert metafunc._calls[0].funcargs == dict(x="a", y="b")
assert metafunc._calls[0].params == {}
def test_parametrize_indirect_wrong_type(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
with pytest.raises(
fail.Exception,
match="In func: expected Sequence or boolean for indirect, got dict",
):
metafunc.parametrize("x, y", [("a", "b")], indirect={}) # type: ignore[arg-type]
def test_parametrize_indirect_list_functional(self, pytester: Pytester) -> None:
"""
#714
Test parametrization with 'indirect' parameter applied on
particular arguments. As y is is direct, its value should
be used directly rather than being passed to the fixture
y.
:param pytester: the instance of Pytester class, a temporary
test directory.
"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.fixture(scope='function')
def y(request):
return request.param * 2
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])
def test_simple(x,y):
assert len(x) == 3
assert len(y) == 1
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(["*test_simple*a-b*", "*1 passed*"])
def test_parametrize_indirect_list_error(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
with pytest.raises(fail.Exception):
metafunc.parametrize("x, y", [("a", "b")], indirect=["x", "z"])
def test_parametrize_uses_no_fixture_error_indirect_false(
self, pytester: Pytester
) -> None:
"""The 'uses no fixture' error tells the user at collection time
that the parametrize data they've set up doesn't correspond to the
fixtures in their test function, rather than silently ignoring this
and letting the test potentially pass.
#714
"""
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=False)
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no argument 'y'*"])
def test_parametrize_uses_no_fixture_error_indirect_true(
self, pytester: Pytester
) -> None:
"""#714"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.fixture(scope='function')
def y(request):
return request.param * 2
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=True)
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
def test_parametrize_indirect_uses_no_fixture_error_indirect_string(
self, pytester: Pytester
) -> None:
"""#714"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect='y')
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
def test_parametrize_indirect_uses_no_fixture_error_indirect_list(
self, pytester: Pytester
) -> None:
"""#714"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['y'])
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
def test_parametrize_argument_not_in_indirect_list(
self, pytester: Pytester
) -> None:
"""#714"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no argument 'y'*"])
def test_parametrize_gives_indicative_error_on_function_with_default_argument(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize('x, y', [('a', 'b')])
def test_simple(x, y=1):
assert len(x) == 1
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(
["*already takes an argument 'y' with a default value"]
)
def test_parametrize_functional(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def pytest_generate_tests(metafunc):
metafunc.parametrize('x', [1,2], indirect=True)
metafunc.parametrize('y', [2])
@pytest.fixture
def x(request):
return request.param * 10
def test_simple(x,y):
assert x in (10,20)
assert y == 2
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
["*test_simple*1-2*", "*test_simple*2-2*", "*2 passed*"]
)
def test_parametrize_onearg(self) -> None:
metafunc = self.Metafunc(lambda x: None)
metafunc.parametrize("x", [1, 2])
assert len(metafunc._calls) == 2
assert metafunc._calls[0].funcargs == dict(x=1)
assert metafunc._calls[0].id == "1"
assert metafunc._calls[1].funcargs == dict(x=2)
assert metafunc._calls[1].id == "2"
def test_parametrize_onearg_indirect(self) -> None:
metafunc = self.Metafunc(lambda x: None)
metafunc.parametrize("x", [1, 2], indirect=True)
assert metafunc._calls[0].params == dict(x=1)
assert metafunc._calls[0].id == "1"
assert metafunc._calls[1].params == dict(x=2)
assert metafunc._calls[1].id == "2"
def test_parametrize_twoargs(self) -> None:
metafunc = self.Metafunc(lambda x, y: None)
metafunc.parametrize(("x", "y"), [(1, 2), (3, 4)])
assert len(metafunc._calls) == 2
assert metafunc._calls[0].funcargs == dict(x=1, y=2)
assert metafunc._calls[0].id == "1-2"
assert metafunc._calls[1].funcargs == dict(x=3, y=4)
assert metafunc._calls[1].id == "3-4"
def test_parametrize_multiple_times(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
pytestmark = pytest.mark.parametrize("x", [1,2])
def test_func(x):
assert 0, x
class TestClass(object):
pytestmark = pytest.mark.parametrize("y", [3,4])
def test_meth(self, x, y):
assert 0, x
"""
)
result = pytester.runpytest()
assert result.ret == 1
result.assert_outcomes(failed=6)
def test_parametrize_CSV(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("x, y,", [(1,2), (2,3)])
def test_func(x, y):
assert x+1 == y
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_parametrize_class_scenarios(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
# same as doc/en/example/parametrize scenario example
def pytest_generate_tests(metafunc):
idlist = []
argvalues = []
for scenario in metafunc.cls.scenarios:
idlist.append(scenario[0])
items = scenario[1].items()
argnames = [x[0] for x in items]
argvalues.append(([x[1] for x in items]))
metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")
class Test(object):
scenarios = [['1', {'arg': {1: 2}, "arg2": "value2"}],
['2', {'arg':'value2', "arg2": "value2"}]]
def test_1(self, arg, arg2):
pass
def test_2(self, arg2, arg):
pass
def test_3(self, arg, arg2):
pass
"""
)
result = pytester.runpytest("-v")
assert result.ret == 0
result.stdout.fnmatch_lines(
"""
*test_1*1*
*test_2*1*
*test_3*1*
*test_1*2*
*test_2*2*
*test_3*2*
*6 passed*
"""
)
def test_format_args(self) -> None:
def function1():
pass
assert _format_args(function1) == "()"
def function2(arg1):
pass
assert _format_args(function2) == "(arg1)"
def function3(arg1, arg2="qwe"):
pass
assert _format_args(function3) == "(arg1, arg2='qwe')"
def function4(arg1, *args, **kwargs):
pass
assert _format_args(function4) == "(arg1, *args, **kwargs)"
class TestMetafuncFunctional:
def test_attributes(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
# assumes that generate/provide runs in the same process
import sys, pytest
def pytest_generate_tests(metafunc):
metafunc.parametrize('metafunc', [metafunc])
@pytest.fixture
def metafunc(request):
return request.param