Debian Codegraph @

testing/python/metafunc.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Iterator
5 from collections.abc import Sequence
6 import dataclasses
7 import itertools
8 import re
9 import sys
10 import textwrap
11 from typing import Any
12 from typing import cast
13 from typing import ClassVar
14
15 import hypothesis
16 from hypothesis import strategies
17
18 from _pytest import fixtures
19 from _pytest import python
20 from _pytest.compat import getfuncargnames
21 from _pytest.compat import NOTSET
22 from _pytest.outcomes import fail
23 from _pytest.outcomes import Failed
24 from _pytest.pytester import Pytester
25 from _pytest.python import Function
26 from _pytest.python import IdMaker
27 from _pytest.scope import Scope
28 import pytest
29
30
31 class TestMetafunc:
32 def Metafunc(self, func, config=None) -> python.Metafunc:
33 # The unit tests of this class check if things work correctly
34 # on the funcarg level, so we don't need a full blown
35 # initialization.
36 class FuncFixtureInfoMock:
37 name2fixturedefs: dict[str, list[fixtures.FixtureDef[object]]] = {}
38
39 def __init__(self, names):
40 self.names_closure = names
41
42 @dataclasses.dataclass
43 class FixtureManagerMock:
44 config: Any
45
46 @dataclasses.dataclass
47 class SessionMock:
48 config: Any
49 _fixturemanager: FixtureManagerMock
50 nodeid: ClassVar = ""
51
52 @dataclasses.dataclass
53 class DefinitionMock(python.FunctionDefinition):
54 _nodeid: str
55 obj: object
56
57 names = getfuncargnames(func)
58 fixtureinfo: Any = FuncFixtureInfoMock(names)
59 definition: Any = DefinitionMock._create(obj=func, _nodeid="mock::nodeid")
60 definition._fixtureinfo = fixtureinfo
61 definition.session = SessionMock(config, FixtureManagerMock({}))
62 return python.Metafunc(definition, fixtureinfo, config, _ispytest=True)
63
64 def test_no_funcargs(self) -> None:
65 def function():
66 pass
67
68 metafunc = self.Metafunc(function)
69 assert not metafunc.fixturenames
70 repr(metafunc._calls)
71
72 def test_function_basic(self) -> None:
73 def func(arg1, arg2="qwe"):
74 pass
75
76 metafunc = self.Metafunc(func)
77 assert len(metafunc.fixturenames) == 1
78 assert "arg1" in metafunc.fixturenames
79 assert metafunc.function is func
80 assert metafunc.cls is None
81
82 def test_parametrize_single_arg_trailing_comma(self) -> None:
83 """Test that trailing comma in string argnames behaves like tuple argnames.
84
85 Regression test for https://github.com/pytest-dev/pytest/issues/719
86
87 When using a single argument with:
88 - "arg" (string, no comma): argvalues is a list of values
89 - "arg," (string, trailing comma): argvalues is a list of tuples (like tuple form)
90 - ("arg",) (tuple): argvalues is a list of tuples
91 """
92
93 def func(arg):
94 pass # pragma: no cover
95
96 scenarios = [("a",), ("b",)]
97
98 # Tuple form: argvalues are tuples, unpacked to get the value
99 metafunc = self.Metafunc(func)
100 metafunc.parametrize(("arg",), scenarios)
101 assert metafunc._calls[0].params == {"arg": "a"}
102 assert metafunc._calls[1].params == {"arg": "b"}
103
104 # String with trailing comma: should behave like tuple form
105 metafunc = self.Metafunc(func)
106 metafunc.parametrize("arg,", scenarios)
107 assert metafunc._calls[0].params == {"arg": "a"}
108 assert metafunc._calls[1].params == {"arg": "b"}
109
110 # String without comma: argvalues are values directly (tuples are passed as-is)
111 metafunc = self.Metafunc(func)
112 metafunc.parametrize("arg", scenarios)
113 assert metafunc._calls[0].params == {"arg": ("a",)}
114 assert metafunc._calls[1].params == {"arg": ("b",)}
115
116 # String without comma with plain values: values are used directly
117 metafunc = self.Metafunc(func)
118 metafunc.parametrize("arg", ["a", "b"])
119 assert metafunc._calls[0].params == {"arg": "a"}
120 assert metafunc._calls[1].params == {"arg": "b"}
121
122 def test_parametrize_error(self) -> None:
123 def func(x, y):
124 pass
125
126 metafunc = self.Metafunc(func)
127 metafunc.parametrize("x", [1, 2])
128 with pytest.raises(pytest.Collector.CollectError):
129 metafunc.parametrize("x", [5, 6])
130 with pytest.raises(pytest.Collector.CollectError):
131 metafunc.parametrize("x", [5, 6])
132 metafunc.parametrize("y", [1, 2])
133 with pytest.raises(pytest.Collector.CollectError):
134 metafunc.parametrize("y", [5, 6])
135 with pytest.raises(pytest.Collector.CollectError):
136 metafunc.parametrize("y", [5, 6])
137
138 with pytest.raises(TypeError, match=r"^ids must be a callable or an iterable$"):
139 metafunc.parametrize("y", [5, 6], ids=42) # type: ignore[arg-type]
140
141 def test_parametrize_error_iterator(self) -> None:
142 def func(x):
143 raise NotImplementedError()
144
145 class Exc(Exception):
146 def __repr__(self):
147 return "Exc(from_gen)"
148
149 def gen() -> Iterator[int | None | Exc]:
150 yield 0
151 yield None
152 yield Exc()
153
154 metafunc = self.Metafunc(func)
155 # When the input is an iterator, only len(args) are taken,
156 # so the bad Exc isn't reached.
157 metafunc.parametrize("x", [1, 2], ids=gen())
158 assert [(x.params, x.id) for x in metafunc._calls] == [
159 ({"x": 1}, "0"),
160 ({"x": 2}, "2"),
161 ]
162 with pytest.raises(
163 fail.Exception,
164 match=(
165 r"In mock::nodeid: ids contains unsupported value Exc\(from_gen\) \(type: <class .*Exc'>\) at index 2. "
166 r"Supported types are: .*"
167 ),
168 ):
169 metafunc.parametrize("x", [1, 2, 3], ids=gen())
170
171 def test_parametrize_bad_scope(self) -> None:
172 def func(x):
173 pass
174
175 metafunc = self.Metafunc(func)
176 with pytest.raises(
177 fail.Exception,
178 match=r"parametrize\(\) call in func got an unexpected scope value 'doggy'",
179 ):
180 metafunc.parametrize("x", [1], scope="doggy") # type: ignore[arg-type]
181
182 def test_parametrize_request_name(self, pytester: Pytester) -> None:
183 """Show proper error when 'request' is used as a parameter name in parametrize (#6183)"""
184
185 def func(request):
186 raise NotImplementedError()
187
188 metafunc = self.Metafunc(func)
189 with pytest.raises(
190 fail.Exception,
191 match=r"'request' is a reserved name and cannot be used in @pytest.mark.parametrize",
192 ):
193 metafunc.parametrize("request", [1])
194
195 def test_find_parametrized_scope(self) -> None:
196 """Unit test for _find_parametrized_scope (#3941)."""
197 from _pytest.python import _find_parametrized_scope
198
199 @dataclasses.dataclass
200 class DummyFixtureDef:
201 _scope: Scope
202
203 fixtures_defs = cast(
204 dict[str, Sequence[fixtures.FixtureDef[object]]],
205 dict(
206 session_fix=[DummyFixtureDef(Scope.Session)],
207 package_fix=[DummyFixtureDef(Scope.Package)],
208 module_fix=[DummyFixtureDef(Scope.Module)],
209 class_fix=[DummyFixtureDef(Scope.Class)],
210 func_fix=[DummyFixtureDef(Scope.Function)],
211 mixed_fix=[DummyFixtureDef(Scope.Module), DummyFixtureDef(Scope.Class)],
212 ),
213 )
214
215 # use arguments to determine narrow scope; the cause of the bug is that it would look on all
216 # fixture defs given to the method
217 def find_scope(argnames, indirect):
218 return _find_parametrized_scope(argnames, fixtures_defs, indirect=indirect)
219
220 assert find_scope(["func_fix"], indirect=True) == Scope.Function
221 assert find_scope(["class_fix"], indirect=True) == Scope.Class
222 assert find_scope(["module_fix"], indirect=True) == Scope.Module
223 assert find_scope(["package_fix"], indirect=True) == Scope.Package
224 assert find_scope(["session_fix"], indirect=True) == Scope.Session
225
226 assert find_scope(["class_fix", "func_fix"], indirect=True) == Scope.Function
227 assert find_scope(["func_fix", "session_fix"], indirect=True) == Scope.Function
228 assert find_scope(["session_fix", "class_fix"], indirect=True) == Scope.Class
229 assert (
230 find_scope(["package_fix", "session_fix"], indirect=True) == Scope.Package
231 )
232 assert find_scope(["module_fix", "session_fix"], indirect=True) == Scope.Module
233
234 # when indirect is False or is not for all scopes, always use function
235 assert (
236 find_scope(["session_fix", "module_fix"], indirect=False) == Scope.Function
237 )
238 assert (
239 find_scope(["session_fix", "module_fix"], indirect=["module_fix"])
240 == Scope.Function
241 )
242 assert (
243 find_scope(
244 ["session_fix", "module_fix"], indirect=["session_fix", "module_fix"]
245 )
246 == Scope.Module
247 )
248 assert find_scope(["mixed_fix"], indirect=True) == Scope.Class
249
250 def test_parametrize_and_id(self) -> None:
251 def func(x, y):
252 pass
253
254 metafunc = self.Metafunc(func)
255
256 metafunc.parametrize("x", [1, 2], ids=["basic", "advanced"])
257 metafunc.parametrize("y", ["abc", "def"])
258 ids = [x.id for x in metafunc._calls]
259 assert ids == ["basic-abc", "basic-def", "advanced-abc", "advanced-def"]
260
261 def test_parametrize_and_id_unicode(self) -> None:
262 """Allow unicode strings for "ids" parameter in Python 2 (##1905)"""
263
264 def func(x):
265 pass
266
267 metafunc = self.Metafunc(func)
268 metafunc.parametrize("x", [1, 2], ids=["basic", "advanced"])
269 ids = [x.id for x in metafunc._calls]
270 assert ids == ["basic", "advanced"]
271
272 def test_parametrize_with_wrong_number_of_ids(self) -> None:
273 def func(x, y):
274 pass
275
276 metafunc = self.Metafunc(func)
277
278 with pytest.raises(fail.Exception):
279 metafunc.parametrize("x", [1, 2], ids=["basic"])
280
281 with pytest.raises(fail.Exception):
282 metafunc.parametrize(
283 ("x", "y"), [("abc", "def"), ("ghi", "jkl")], ids=["one"]
284 )
285
286 def test_parametrize_ids_iterator_without_mark(self) -> None:
287 def func(x, y):
288 pass
289
290 it = itertools.count()
291
292 metafunc = self.Metafunc(func)
293 metafunc.parametrize("x", [1, 2], ids=it)
294 metafunc.parametrize("y", [3, 4], ids=it)
295 ids = [x.id for x in metafunc._calls]
296 assert ids == ["0-2", "0-3", "1-2", "1-3"]
297
298 metafunc = self.Metafunc(func)
299 metafunc.parametrize("x", [1, 2], ids=it)
300 metafunc.parametrize("y", [3, 4], ids=it)
301 ids = [x.id for x in metafunc._calls]
302 assert ids == ["4-6", "4-7", "5-6", "5-7"]
303
304 def test_parametrize_empty_list(self) -> None:
305 """#510"""
306
307 def func(y):
308 pass
309
310 class MockConfig:
311 def getini(self, name):
312 return ""
313
314 @property
315 def hook(self):
316 return self
317
318 def pytest_make_parametrize_id(self, **kw):
319 pass
320
321 metafunc = self.Metafunc(func, MockConfig())
322 metafunc.parametrize("y", [])
323 assert "skip" == metafunc._calls[0].marks[0].name
324
325 def test_parametrize_with_userobjects(self) -> None:
326 def func(x, y):
327 pass
328
329 metafunc = self.Metafunc(func)
330
331 class A:
332 pass
333
334 metafunc.parametrize("x", [A(), A()])
335 metafunc.parametrize("y", list("ab"))
336 assert metafunc._calls[0].id == "x0-a"
337 assert metafunc._calls[1].id == "x0-b"
338 assert metafunc._calls[2].id == "x1-a"
339 assert metafunc._calls[3].id == "x1-b"
340
341 @hypothesis.given(strategies.text() | strategies.binary())
342 @hypothesis.settings(
343 deadline=400.0
344 ) # very close to std deadline and CI boxes are not reliable in CPU power
345 def test_idval_hypothesis(self, value) -> None:
346 escaped = IdMaker([], [], None, None, None, None)._idval(value, "a", 6)
347 assert isinstance(escaped, str)
348 escaped.encode("ascii")
349
350 def test_unicode_idval(self) -> None:
351 """Test that Unicode strings outside the ASCII character set get
352 escaped, using byte escapes if they're in that range or unicode
353 escapes if they're not.
354
355 """
356 values = [
357 ("", r""),
358 ("ascii", r"ascii"),
359 ("ação", r"a\xe7\xe3o"),
360 ("josé@blah.com", r"jos\[email protected]"),
361 (
362 r"δοκ.ιμή@παράδειγμα.δοκιμή",
363 r"\u03b4\u03bf\u03ba.\u03b9\u03bc\u03ae@\u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3"
364 r"\u03bc\u03b1.\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae",
365 ),
366 ]
367 for val, expected in values:
368 assert (
369 IdMaker([], [], None, None, None, None)._idval(val, "a", 6) == expected
370 )
371
372 def test_unicode_idval_with_config(self) -> None:
373 """Unit test for expected behavior to obtain ids with
374 disable_test_id_escaping_and_forfeit_all_rights_to_community_support
375 option (#5294)."""
376
377 class MockConfig:
378 def __init__(self, config):
379 self.config = config
380
381 @property
382 def hook(self):
383 return self
384
385 def pytest_make_parametrize_id(self, **kw):
386 pass
387
388 def getini(self, name):
389 return self.config[name]
390
391 option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
392
393 values: list[tuple[str, Any, str]] = [
394 ("ação", MockConfig({option: True}), "ação"),
395 ("ação", MockConfig({option: False}), "a\\xe7\\xe3o"),
396 ]
397 for val, config, expected in values:
398 actual = IdMaker([], [], None, None, config, None)._idval(val, "a", 6)
399 assert actual == expected
400
401 def test_bytes_idval(self) -> None:
402 """Unit test for the expected behavior to obtain ids for parametrized
403 bytes values: bytes objects are always escaped using "binary escape"."""
404 values = [
405 (b"", r""),
406 (b"\xc3\xb4\xff\xe4", r"\xc3\xb4\xff\xe4"),
407 (b"ascii", r"ascii"),
408 ("αρά".encode(), r"\xce\xb1\xcf\x81\xce\xac"),
409 ]
410 for val, expected in values:
411 assert (
412 IdMaker([], [], None, None, None, None)._idval(val, "a", 6) == expected
413 )
414
415 def test_class_or_function_idval(self) -> None:
416 """Unit test for the expected behavior to obtain ids for parametrized
417 values that are classes or functions: their __name__."""
418
419 class TestClass:
420 pass
421
422 def test_function():
423 pass
424
425 values = [(TestClass, "TestClass"), (test_function, "test_function")]
426 for val, expected in values:
427 assert (
428 IdMaker([], [], None, None, None, None)._idval(val, "a", 6) == expected
429 )
430
431 def test_notset_idval(self) -> None:
432 """Test that a NOTSET value (used by an empty parameterset) generates
433 a proper ID.
434
435 Regression test for #7686.
436 """
437 assert IdMaker([], [], None, None, None, None)._idval(NOTSET, "a", 0) == "a0"
438
439 def test_idmaker_autoname(self) -> None:
440 """#250"""
441 result = IdMaker(
442 ("a", "b"),
443 [pytest.param("string", 1.0), pytest.param("st-ring", 2.0)],
444 None,
445 None,
446 None,
447 None,
448 ).make_unique_parameterset_ids()
449 assert result == ["string-1.0", "st-ring-2.0"]
450
451 result = IdMaker(
452 ("a", "b"),
453 [pytest.param(object(), 1.0), pytest.param(object(), object())],
454 None,
455 None,
456 None,
457 None,
458 ).make_unique_parameterset_ids()
459 assert result == ["a0-1.0", "a1-b1"]
460 # unicode mixing, issue250
461 result = IdMaker(
462 ("a", "b"), [pytest.param({}, b"\xc3\xb4")], None, None, None, None
463 ).make_unique_parameterset_ids()
464 assert result == ["a0-\\xc3\\xb4"]
465
466 def test_idmaker_with_bytes_regex(self) -> None:
467 result = IdMaker(
468 ("a"), [pytest.param(re.compile(b"foo"))], None, None, None, None
469 ).make_unique_parameterset_ids()
470 assert result == ["foo"]
471
472 def test_idmaker_native_strings(self) -> None:
473 result = IdMaker(
474 ("a", "b"),
475 [
476 pytest.param(1.0, -1.1),
477 pytest.param(2, -202),
478 pytest.param("three", "three hundred"),
479 pytest.param(True, False),
480 pytest.param(None, None),
481 pytest.param(re.compile("foo"), re.compile("bar")),
482 pytest.param(str, int),
483 pytest.param(list("six"), [66, 66]),
484 pytest.param({7}, set("seven")),
485 pytest.param(tuple("eight"), (8, -8, 8)),
486 pytest.param(b"\xc3\xb4", b"name"),
487 pytest.param(b"\xc3\xb4", "other"),
488 pytest.param(1.0j, -2.0j),
489 ],
490 None,
491 None,
492 None,
493 None,
494 ).make_unique_parameterset_ids()
495 assert result == [
496 "1.0--1.1",
497 "2--202",
498 "three-three hundred",
499 "True-False",
500 "None-None",
501 "foo-bar",
502 "str-int",
503 "a7-b7",
504 "a8-b8",
505 "a9-b9",
506 "\\xc3\\xb4-name",
507 "\\xc3\\xb4-other",
508 "1j-(-0-2j)",
509 ]
510
511 def test_idmaker_non_printable_characters(self) -> None:
512 result = IdMaker(
513 ("s", "n"),
514 [
515 pytest.param("\x00", 1),
516 pytest.param("\x05", 2),
517 pytest.param(b"\x00", 3),
518 pytest.param(b"\x05", 4),
519 pytest.param("\t", 5),
520 pytest.param(b"\t", 6),
521 ],
522 None,
523 None,
524 None,
525 None,
526 ).make_unique_parameterset_ids()
527 assert result == ["\\x00-1", "\\x05-2", "\\x00-3", "\\x05-4", "\\t-5", "\\t-6"]
528
529 def test_idmaker_manual_ids_must_be_printable(self) -> None:
530 result = IdMaker(
531 ("s",),
532 [
533 pytest.param("x00", id="hello \x00"),
534 pytest.param("x05", id="hello \x05"),
535 ],
536 None,
537 None,
538 None,
539 None,
540 ).make_unique_parameterset_ids()
541 assert result == ["hello \\x00", "hello \\x05"]
542
543 def test_idmaker_enum(self) -> None:
544 enum = pytest.importorskip("enum")
545 e = enum.Enum("Foo", "one, two")
546 result = IdMaker(
547 ("a", "b"), [pytest.param(e.one, e.two)], None, None, None, None
548 ).make_unique_parameterset_ids()
549 assert result == ["Foo.one-Foo.two"]
550
551 def test_idmaker_idfn(self) -> None:
552 """#351"""
553
554 def ids(val: object) -> str | None:
555 if isinstance(val, Exception):
556 return repr(val)
557 return None
558
559 result = IdMaker(
560 ("a", "b"),
561 [
562 pytest.param(10.0, IndexError()),
563 pytest.param(20, KeyError()),
564 pytest.param("three", [1, 2, 3]),
565 ],
566 ids,
567 None,
568 None,
569 None,
570 ).make_unique_parameterset_ids()
571 assert result == ["10.0-IndexError()", "20-KeyError()", "three-b2"]
572
573 def test_idmaker_idfn_unique_names(self) -> None:
574 """#351"""
575
576 def ids(val: object) -> str:
577 return "a"
578
579 result = IdMaker(
580 ("a", "b"),
581 [
582 pytest.param(10.0, IndexError()),
583 pytest.param(20, KeyError()),
584 pytest.param("three", [1, 2, 3]),
585 ],
586 ids,
587 None,
588 None,
589 None,
590 ).make_unique_parameterset_ids()
591 assert result == ["a-a0", "a-a1", "a-a2"]
592
593 def test_idmaker_with_idfn_and_config(self) -> None:
594 """Unit test for expected behavior to create ids with idfn and
595 disable_test_id_escaping_and_forfeit_all_rights_to_community_support
596 option (#5294).
597 """
598
599 class MockConfig:
600 def __init__(self, config):
601 self.config = config
602
603 @property
604 def hook(self):
605 return self
606
607 def pytest_make_parametrize_id(self, **kw):
608 pass
609
610 def getini(self, name):
611 return self.config[name]
612
613 option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
614
615 values: list[tuple[Any, str]] = [
616 (MockConfig({option: True}), "ação"),
617 (MockConfig({option: False}), "a\\xe7\\xe3o"),
618 ]
619 for config, expected in values:
620 result = IdMaker(
621 ("a",),
622 [pytest.param("string")],
623 lambda _: "ação",
624 None,
625 config,
626 None,
627 ).make_unique_parameterset_ids()
628 assert result == [expected]
629
630 def test_idmaker_with_ids_and_config(self) -> None:
631 """Unit test for expected behavior to create ids with ids and
632 disable_test_id_escaping_and_forfeit_all_rights_to_community_support
633 option (#5294).
634 """
635
636 class MockConfig:
637 def __init__(self, config):
638 self.config = config
639
640 @property
641 def hook(self):
642 return self
643
644 def pytest_make_parametrize_id(self, **kw):
645 pass
646
647 def getini(self, name):
648 return self.config[name]
649
650 option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
651
652 values: list[tuple[Any, str]] = [
653 (MockConfig({option: True}), "ação"),
654 (MockConfig({option: False}), "a\\xe7\\xe3o"),
655 ]
656 for config, expected in values:
657 result = IdMaker(
658 ("a",), [pytest.param("string")], None, ["ação"], config, None
659 ).make_unique_parameterset_ids()
660 assert result == [expected]
661
662 def test_idmaker_with_param_id_and_config(self) -> None:
663 """Unit test for expected behavior to create ids with pytest.param(id=...) and
664 disable_test_id_escaping_and_forfeit_all_rights_to_community_support
665 option (#9037).
666 """
667
668 class MockConfig:
669 def __init__(self, config):
670 self.config = config
671
672 def getini(self, name):
673 return self.config[name]
674
675 option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
676
677 values: list[tuple[Any, str]] = [
678 (MockConfig({option: True}), "ação"),
679 (MockConfig({option: False}), "a\\xe7\\xe3o"),
680 ]
681 for config, expected in values:
682 result = IdMaker(
683 ("a",),
684 [pytest.param("string", id="ação")],
685 None,
686 None,
687 config,
688 None,
689 ).make_unique_parameterset_ids()
690 assert result == [expected]
691
692 def test_idmaker_duplicated_empty_str(self) -> None:
693 """Regression test for empty strings parametrized more than once (#11563)."""
694 result = IdMaker(
695 ("a",), [pytest.param(""), pytest.param("")], None, None, None, None
696 ).make_unique_parameterset_ids()
697 assert result == ["0", "1"]
698
699 def test_parametrize_ids_exception(self, pytester: Pytester) -> None:
700 """
701 :param pytester: the instance of Pytester class, a temporary
702 test directory.
703 """
704 pytester.makepyfile(
705 """
706 import pytest
707
708 def ids(arg):
709 raise Exception("bad ids")
710
711 @pytest.mark.parametrize("arg", ["a", "b"], ids=ids)
712 def test_foo(arg):
713 pass
714 """
715 )
716 result = pytester.runpytest()
717 result.stdout.fnmatch_lines(
718 [
719 "*Exception: bad ids",
720 "*test_foo: error raised while trying to determine id of parameter 'arg' at position 0",
721 ]
722 )
723
724 def test_parametrize_ids_returns_non_string(self, pytester: Pytester) -> None:
725 pytester.makepyfile(
726 """\
727 import pytest
728
729 def ids(d):
730 return d
731
732 @pytest.mark.parametrize("arg", ({1: 2}, {3, 4}), ids=ids)
733 def test(arg):
734 assert arg
735
736 @pytest.mark.parametrize("arg", (1, 2.0, True), ids=ids)
737 def test_int(arg):
738 assert arg
739 """
740 )
741 result = pytester.runpytest("-vv", "-s")
742 result.stdout.fnmatch_lines(
743 [
744 "test_parametrize_ids_returns_non_string.py::test[arg0] PASSED",
745 "test_parametrize_ids_returns_non_string.py::test[arg1] PASSED",
746 "test_parametrize_ids_returns_non_string.py::test_int[1] PASSED",
747 "test_parametrize_ids_returns_non_string.py::test_int[2.0] PASSED",
748 "test_parametrize_ids_returns_non_string.py::test_int[True] PASSED",
749 ]
750 )
751
752 def test_idmaker_with_ids(self) -> None:
753 result = IdMaker(
754 ("a", "b"),
755 [pytest.param(1, 2), pytest.param(3, 4)],
756 None,
757 ["a", None],
758 None,
759 None,
760 ).make_unique_parameterset_ids()
761 assert result == ["a", "3-4"]
762
763 def test_idmaker_with_paramset_id(self) -> None:
764 result = IdMaker(
765 ("a", "b"),
766 [pytest.param(1, 2, id="me"), pytest.param(3, 4, id="you")],
767 None,
768 ["a", None],
769 None,
770 None,
771 ).make_unique_parameterset_ids()
772 assert result == ["me", "you"]
773
774 def test_idmaker_with_ids_unique_names(self) -> None:
775 result = IdMaker(
776 ("a"),
777 list(map(pytest.param, [1, 2, 3, 4, 5])),
778 None,
779 ["a", "a", "b", "c", "b"],
780 None,
781 None,
782 ).make_unique_parameterset_ids()
783 assert result == ["a0", "a1", "b0", "c", "b1"]
784
785 def test_parametrize_indirect(self) -> None:
786 """#714"""
787
788 def func(x, y):
789 pass
790
791 metafunc = self.Metafunc(func)
792 metafunc.parametrize("x", [1], indirect=True)
793 metafunc.parametrize("y", [2, 3], indirect=True)
794 assert len(metafunc._calls) == 2
795 assert metafunc._calls[0].params == dict(x=1, y=2)
796 assert metafunc._calls[1].params == dict(x=1, y=3)
797
798 def test_parametrize_indirect_list(self) -> None:
799 """#714"""
800
801 def func(x, y):
802 pass
803
804 metafunc = self.Metafunc(func)
805 metafunc.parametrize("x, y", [("a", "b")], indirect=["x"])
806 assert metafunc._calls[0].params == dict(x="a", y="b")
807 # Since `y` is a direct parameter, its DirectParamFixtureDef would
808 # be registered.
809 assert list(metafunc._arg2fixturedefs.keys()) == ["y"]
810
811 def test_parametrize_indirect_list_all(self) -> None:
812 """#714"""
813
814 def func(x, y):
815 pass
816
817 metafunc = self.Metafunc(func)
818 metafunc.parametrize("x, y", [("a", "b")], indirect=["x", "y"])
819 assert metafunc._calls[0].params == dict(x="a", y="b")
820 assert list(metafunc._arg2fixturedefs.keys()) == []
821
822 def test_parametrize_indirect_list_empty(self) -> None:
823 """#714"""
824
825 def func(x, y):
826 pass
827
828 metafunc = self.Metafunc(func)
829 metafunc.parametrize("x, y", [("a", "b")], indirect=[])
830 assert metafunc._calls[0].params == dict(x="a", y="b")
831 assert list(metafunc._arg2fixturedefs.keys()) == ["x", "y"]
832
833 def test_parametrize_indirect_wrong_type(self) -> None:
834 def func(x, y):
835 pass
836
837 metafunc = self.Metafunc(func)
838 with pytest.raises(
839 fail.Exception,
840 match="In mock::nodeid: expected Sequence or boolean for indirect, got dict",
841 ):
842 metafunc.parametrize("x, y", [("a", "b")], indirect={}) # type: ignore[arg-type]
843
844 def test_parametrize_indirect_list_functional(self, pytester: Pytester) -> None:
845 """
846 #714
847 Test parametrization with 'indirect' parameter applied on
848 particular arguments. As y is direct, its value should
849 be used directly rather than being passed to the fixture y.
850
851 :param pytester: the instance of Pytester class, a temporary
852 test directory.
853 """
854 pytester.makepyfile(
855 """
856 import pytest
857 @pytest.fixture(scope='function')
858 def x(request):
859 return request.param * 3
860 @pytest.fixture(scope='function')
861 def y(request):
862 return request.param * 2
863 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])
864 def test_simple(x,y):
865 assert len(x) == 3
866 assert len(y) == 1
867 """
868 )
869 result = pytester.runpytest("-v")
870 result.stdout.fnmatch_lines(["*test_simple*a-b*", "*1 passed*"])
871
872 def test_parametrize_indirect_list_error(self) -> None:
873 """#714"""
874
875 def func(x, y):
876 pass
877
878 metafunc = self.Metafunc(func)
879 with pytest.raises(fail.Exception):
880 metafunc.parametrize("x, y", [("a", "b")], indirect=["x", "z"])
881
882 def test_parametrize_uses_no_fixture_error_indirect_false(
883 self, pytester: Pytester
884 ) -> None:
885 """The 'uses no fixture' error tells the user at collection time
886 that the parametrize data they've set up doesn't correspond to the
887 fixtures in their test function, rather than silently ignoring this
888 and letting the test potentially pass.
889
890 #714
891 """
892 pytester.makepyfile(
893 """
894 import pytest
895
896 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=False)
897 def test_simple(x):
898 assert len(x) == 3
899 """
900 )
901 result = pytester.runpytest("--collect-only")
902 result.stdout.fnmatch_lines(["*uses no argument 'y'*"])
903
904 def test_parametrize_uses_no_fixture_error_indirect_true(
905 self, pytester: Pytester
906 ) -> None:
907 """#714"""
908 pytester.makepyfile(
909 """
910 import pytest
911 @pytest.fixture(scope='function')
912 def x(request):
913 return request.param * 3
914 @pytest.fixture(scope='function')
915 def y(request):
916 return request.param * 2
917
918 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=True)
919 def test_simple(x):
920 assert len(x) == 3
921 """
922 )
923 result = pytester.runpytest("--collect-only")
924 result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
925
926 def test_parametrize_indirect_uses_no_fixture_error_indirect_string(
927 self, pytester: Pytester
928 ) -> None:
929 """#714"""
930 pytester.makepyfile(
931 """
932 import pytest
933 @pytest.fixture(scope='function')
934 def x(request):
935 return request.param * 3
936
937 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect='y')
938 def test_simple(x):
939 assert len(x) == 3
940 """
941 )
942 result = pytester.runpytest("--collect-only")
943 result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
944
945 def test_parametrize_indirect_uses_no_fixture_error_indirect_list(
946 self, pytester: Pytester
947 ) -> None:
948 """#714"""
949 pytester.makepyfile(
950 """
951 import pytest
952 @pytest.fixture(scope='function')
953 def x(request):
954 return request.param * 3
955
956 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['y'])
957 def test_simple(x):
958 assert len(x) == 3
959 """
960 )
961 result = pytester.runpytest("--collect-only")
962 result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
963
964 def test_parametrize_argument_not_in_indirect_list(
965 self, pytester: Pytester
966 ) -> None:
967 """#714"""
968 pytester.makepyfile(
969 """
970 import pytest
971 @pytest.fixture(scope='function')
972 def x(request):
973 return request.param * 3
974
975 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])
976 def test_simple(x):
977 assert len(x) == 3
978 """
979 )
980 result = pytester.runpytest("--collect-only")
981 result.stdout.fnmatch_lines(["*uses no argument 'y'*"])
982
983 def test_parametrize_gives_indicative_error_on_function_with_default_argument(
984 self, pytester: Pytester
985 ) -> None:
986 pytester.makepyfile(
987 """
988 import pytest
989
990 @pytest.mark.parametrize('x, y', [('a', 'b')])
991 def test_simple(x, y=1):
992 assert len(x) == 1
993 """
994 )
995 result = pytester.runpytest("--collect-only")
996 result.stdout.fnmatch_lines(
997 ["*already takes an argument 'y' with a default value"]
998 )
999
1000 def test_parametrize_functional(self, pytester: Pytester) -> None:
1001 pytester.makepyfile(
1002 """
1003 import pytest
1004 def pytest_generate_tests(metafunc):
1005 metafunc.parametrize('x', [1,2], indirect=True)
1006 metafunc.parametrize('y', [2])
1007 @pytest.fixture
1008 def x(request):
1009 return request.param * 10
1010
1011 def test_simple(x,y):
1012 assert x in (10,20)
1013 assert y == 2
1014 """
1015 )
1016 result = pytester.runpytest("-v")
1017 result.stdout.fnmatch_lines(
1018 ["*test_simple*1-2*", "*test_simple*2-2*", "*2 passed*"]
1019 )
1020
1021 def test_parametrize_onearg(self) -> None:
1022 metafunc = self.Metafunc(lambda x: None)
1023 metafunc.parametrize("x", [1, 2])
1024 assert len(metafunc._calls) == 2
1025 assert metafunc._calls[0].params == dict(x=1)
1026 assert metafunc._calls[0].id == "1"
1027 assert metafunc._calls[1].params == dict(x=2)
1028 assert metafunc._calls[1].id == "2"
1029
1030 def test_parametrize_onearg_indirect(self) -> None:
1031 metafunc = self.Metafunc(lambda x: None)
1032 metafunc.parametrize("x", [1, 2], indirect=True)
1033 assert metafunc._calls[0].params == dict(x=1)
1034 assert metafunc._calls[0].id == "1"
1035 assert metafunc._calls[1].params == dict(x=2)
1036 assert metafunc._calls[1].id == "2"
1037
1038 def test_parametrize_twoargs(self) -> None:
1039 metafunc = self.Metafunc(lambda x, y: None)
1040 metafunc.parametrize(("x", "y"), [(1, 2), (3, 4)])
1041 assert len(metafunc._calls) == 2
1042 assert metafunc._calls[0].params == dict(x=1, y=2)
1043 assert metafunc._calls[0].id == "1-2"
1044 assert metafunc._calls[1].params == dict(x=3, y=4)
1045 assert metafunc._calls[1].id == "3-4"
1046
1047 def test_high_scoped_parametrize_reordering(self, pytester: Pytester) -> None:
1048 pytester.makepyfile(
1049 """
1050 import pytest
1051
1052 @pytest.mark.parametrize("arg2", [3, 4])
1053 @pytest.mark.parametrize("arg1", [0, 1, 2], scope='module')
1054 def test1(arg1, arg2):
1055 pass
1056
1057 def test2():
1058 pass
1059
1060 @pytest.mark.parametrize("arg1", [0, 1, 2], scope='module')
1061 def test3(arg1):
1062 pass
1063 """
1064 )
1065 result = pytester.runpytest("--collect-only")
1066 result.stdout.re_match_lines(
1067 [
1068 r" <Function test1\[0-3\]>",
1069 r" <Function test3\[0\]>",
1070 r" <Function test1\[0-4\]>",
1071 r" <Function test3\[1\]>",
1072 r" <Function test1\[1-3\]>",
1073 r" <Function test3\[2\]>",
1074 r" <Function test1\[1-4\]>",
1075 r" <Function test1\[2-3\]>",
1076 r" <Function test1\[2-4\]>",
1077 r" <Function test2>",
1078 ]
1079 )
1080
1081 def test_parametrize_multiple_times(self, pytester: Pytester) -> None:
1082 pytester.makepyfile(
1083 """
1084 import pytest
1085 pytestmark = pytest.mark.parametrize("x", [1,2])
1086 def test_func(x):
1087 assert 0, x
1088 class TestClass(object):
1089 pytestmark = pytest.mark.parametrize("y", [3,4])
1090 def test_meth(self, x, y):
1091 assert 0, x
1092 """
1093 )
1094 result = pytester.runpytest()
1095 assert result.ret == 1
1096 result.assert_outcomes(failed=6)
1097
1098 def test_parametrize_CSV(self, pytester: Pytester) -> None:
1099 pytester.makepyfile(
1100 """
1101 import pytest
1102 @pytest.mark.parametrize("x, y,", [(1,2), (2,3)])
1103 def test_func(x, y):
1104 assert x+1 == y
1105 """
1106 )
1107 reprec = pytester.inline_run()
1108 reprec.assertoutcome(passed=2)
1109
1110 def test_parametrize_class_scenarios(self, pytester: Pytester) -> None:
1111 pytester.makepyfile(
1112 """
1113 # same as doc/en/example/parametrize scenario example
1114 def pytest_generate_tests(metafunc):
1115 idlist = []
1116 argvalues = []
1117 for scenario in metafunc.cls.scenarios:
1118 idlist.append(scenario[0])
1119 items = scenario[1].items()
1120 argnames = [x[0] for x in items]
1121 argvalues.append(([x[1] for x in items]))
1122 metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")
1123
1124 class Test(object):
1125 scenarios = [['1', {'arg': {1: 2}, "arg2": "value2"}],
1126 ['2', {'arg':'value2', "arg2": "value2"}]]
1127
1128 def test_1(self, arg, arg2):
1129 pass
1130
1131 def test_2(self, arg2, arg):
1132 pass
1133
1134 def test_3(self, arg, arg2):
1135 pass
1136 """
1137 )
1138 result = pytester.runpytest("-v")
1139 assert result.ret == 0
1140 result.stdout.fnmatch_lines(
1141 """
1142 *test_1*1*
1143 *test_2*1*
1144 *test_3*1*
1145 *test_1*2*
1146 *test_2*2*
1147 *test_3*2*
1148 *6 passed*
1149 """
1150 )
1151
1152 def test_parametrize_iterator_deprecation(self) -> None:
1153 """Test that using iterators for argvalues raises a deprecation warning."""
1154
1155 def func(x: int) -> None:
1156 raise NotImplementedError()
1157
1158 def data_generator() -> Iterator[int]:
1159 yield 1
1160 yield 2
1161
1162 metafunc = self.Metafunc(func)
1163
1164 with pytest.warns(
1165 pytest.PytestRemovedIn10Warning,
1166 match=r"Passing a non-Collection iterable to parametrize is deprecated",
1167 ):
1168 metafunc.parametrize("x", data_generator())
1169
1170
1171 class TestMetafuncFunctional:
1172 def test_attributes(self, pytester: Pytester) -> None:
1173 p = pytester.makepyfile(
1174 """
1175 # assumes that generate/provide runs in the same process
1176 import sys, pytest
1177 def pytest_generate_tests(metafunc):
1178 metafunc.parametrize('metafunc', [metafunc])
1179
1180 @pytest.fixture
1181 def metafunc(request):
1182 return request.param
1183
1184 def test_function(metafunc, pytestconfig):
1185 assert metafunc.config == pytestconfig
1186 assert metafunc.module.__name__ == __name__
1187 assert metafunc.function == test_function
1188 assert metafunc.cls is None
1189
1190 class TestClass(object):
1191 def test_method(self, metafunc, pytestconfig):
1192 assert metafunc.config == pytestconfig
1193 assert metafunc.module.__name__ == __name__
1194 unbound = TestClass.test_method
1195 assert metafunc.function == unbound
1196 assert metafunc.cls == TestClass
1197 """
1198 )
1199 result = pytester.runpytest(p, "-v")
1200 result.assert_outcomes(passed=2)
1201
1202 def test_two_functions(self, pytester: Pytester) -> None:
1203 p = pytester.makepyfile(
1204 """
1205 def pytest_generate_tests(metafunc):
1206 metafunc.parametrize('arg1', [10, 20], ids=['0', '1'])
1207
1208 def test_func1(arg1):
1209 assert arg1 == 10
1210
1211 def test_func2(arg1):
1212 assert arg1 in (10, 20)
1213 """
1214 )
1215 result = pytester.runpytest("-v", p)
1216 result.stdout.fnmatch_lines(
1217 [
1218 "*test_func1*0*PASS*",
1219 "*test_func1*1*FAIL*",
1220 "*test_func2*PASS*",
1221 "*test_func2*PASS*",
1222 "*1 failed, 3 passed*",
1223 ]
1224 )
1225
1226 def test_noself_in_method(self, pytester: Pytester) -> None:
1227 p = pytester.makepyfile(
1228 """
1229 def pytest_generate_tests(metafunc):
1230 assert 'xyz' not in metafunc.fixturenames
1231
1232 class TestHello(object):
1233 def test_hello(xyz):
1234 pass
1235 """
1236 )
1237 result = pytester.runpytest(p)
1238 result.assert_outcomes(passed=1)
1239
1240 def test_generate_tests_in_class(self, pytester: Pytester) -> None:
1241 p = pytester.makepyfile(
1242 """
1243 class TestClass(object):
1244 def pytest_generate_tests(self, metafunc):
1245 metafunc.parametrize('hello', ['world'], ids=['hellow'])
1246
1247 def test_myfunc(self, hello):
1248 assert hello == "world"
1249 """
1250 )
1251 result = pytester.runpytest("-v", p)
1252 result.stdout.fnmatch_lines(["*test_myfunc*hello*PASS*", "*1 passed*"])
1253
1254 def test_two_functions_not_same_instance(self, pytester: Pytester) -> None:
1255 p = pytester.makepyfile(
1256 """
1257 def pytest_generate_tests(metafunc):
1258 metafunc.parametrize('arg1', [10, 20], ids=["0", "1"])
1259
1260 class TestClass(object):
1261 def test_func(self, arg1):
1262 assert not hasattr(self, 'x')
1263 self.x = 1
1264 """
1265 )
1266 result = pytester.runpytest("-v", p)
1267 result.stdout.fnmatch_lines(
1268 ["*test_func*0*PASS*", "*test_func*1*PASS*", "*2 pass*"]
1269 )
1270
1271 def test_issue28_setup_method_in_generate_tests(self, pytester: Pytester) -> None:
1272 p = pytester.makepyfile(
1273 """
1274 def pytest_generate_tests(metafunc):
1275 metafunc.parametrize('arg1', [1])
1276
1277 class TestClass(object):
1278 def test_method(self, arg1):
1279 assert arg1 == self.val
1280 def setup_method(self, func):
1281 self.val = 1
1282 """
1283 )
1284 result = pytester.runpytest(p)
1285 result.assert_outcomes(passed=1)
1286
1287 def test_parametrize_functional2(self, pytester: Pytester) -> None:
1288 pytester.makepyfile(
1289 """
1290 def pytest_generate_tests(metafunc):
1291 metafunc.parametrize("arg1", [1,2])
1292 metafunc.parametrize("arg2", [4,5])
1293 def test_hello(arg1, arg2):
1294 assert 0, (arg1, arg2)
1295 """
1296 )
1297 result = pytester.runpytest()
1298 result.stdout.fnmatch_lines(
1299 ["*(1, 4)*", "*(1, 5)*", "*(2, 4)*", "*(2, 5)*", "*4 failed*"]
1300 )
1301
1302 def test_parametrize_single_arg_trailing_comma_functional(
1303 self, pytester: Pytester
1304 ) -> None:
1305 """Test that trailing comma in string argnames behaves like tuple argnames.
1306
1307 Regression test for https://github.com/pytest-dev/pytest/issues/719
1308 """
1309 pytester.makepyfile(
1310 """
1311 import pytest
1312
1313 scenarios = [('a',), ('b',)]
1314
1315 @pytest.mark.parametrize(("arg",), scenarios)
1316 def test_tuple_form(arg):
1317 # Tuple argnames: values are unpacked from tuples
1318 assert arg in ('a', 'b')
1319 assert isinstance(arg, str)
1320
1321 @pytest.mark.parametrize("arg,", scenarios)
1322 def test_string_trailing_comma(arg):
1323 # String with trailing comma: should behave like tuple form
1324 assert arg in ('a', 'b')
1325 assert isinstance(arg, str)
1326
1327 @pytest.mark.parametrize("arg", scenarios)
1328 def test_string_no_comma(arg):
1329 # String without comma: tuples are passed as-is
1330 assert arg in (('a',), ('b',))
1331 assert isinstance(arg, tuple)
1332 """
1333 )
1334 result = pytester.runpytest("-v")
1335 result.assert_outcomes(passed=6)
1336
1337 def test_parametrize_and_inner_getfixturevalue(self, pytester: Pytester) -> None:
1338 p = pytester.makepyfile(
1339 """
1340 def pytest_generate_tests(metafunc):
1341 metafunc.parametrize("arg1", [1], indirect=True)
1342 metafunc.parametrize("arg2", [10], indirect=True)
1343
1344 import pytest
1345 @pytest.fixture
1346 def arg1(request):
1347 x = request.getfixturevalue("arg2")
1348 return x + request.param
1349
1350 @pytest.fixture
1351 def arg2(request):
1352 return request.param
1353
1354 def test_func1(arg1, arg2):
1355 assert arg1 == 11
1356 """
1357 )
1358 result = pytester.runpytest("-v", p)
1359 result.stdout.fnmatch_lines(["*test_func1*1*PASS*", "*1 passed*"])
1360
1361 def test_parametrize_on_setup_arg(self, pytester: Pytester) -> None:
1362 p = pytester.makepyfile(
1363 """
1364 def pytest_generate_tests(metafunc):
1365 assert "arg1" in metafunc.fixturenames
1366 metafunc.parametrize("arg1", [1], indirect=True)
1367
1368 import pytest
1369 @pytest.fixture
1370 def arg1(request):
1371 return request.param
1372
1373 @pytest.fixture
1374 def arg2(request, arg1):
1375 return 10 * arg1
1376
1377 def test_func(arg2):
1378 assert arg2 == 10
1379 """
1380 )
1381 result = pytester.runpytest("-v", p)
1382 result.stdout.fnmatch_lines(["*test_func*1*PASS*", "*1 passed*"])
1383
1384 def test_parametrize_with_ids(self, pytester: Pytester) -> None:
1385 pytester.makeini(
1386 """
1387 [pytest]
1388 console_output_style=classic
1389 """
1390 )
1391 pytester.makepyfile(
1392 """
1393 import pytest
1394 def pytest_generate_tests(metafunc):
1395 metafunc.parametrize(("a", "b"), [(1,1), (1,2)],
1396 ids=["basic", "advanced"])
1397
1398 def test_function(a, b):
1399 assert a == b
1400 """
1401 )
1402 result = pytester.runpytest("-v")
1403 assert result.ret == 1
1404 result.stdout.fnmatch_lines_random(
1405 ["*test_function*basic*PASSED", "*test_function*advanced*FAILED"]
1406 )
1407
1408 def test_parametrize_without_ids(self, pytester: Pytester) -> None:
1409 pytester.makepyfile(
1410 """
1411 import pytest
1412 def pytest_generate_tests(metafunc):
1413 metafunc.parametrize(("a", "b"),
1414 [(1,object()), (1.3,object())])
1415
1416 def test_function(a, b):
1417 assert 1
1418 """
1419 )
1420 result = pytester.runpytest("-v")
1421 result.stdout.fnmatch_lines(
1422 """
1423 *test_function*1-b0*
1424 *test_function*1.3-b1*
1425 """
1426 )
1427
1428 def test_parametrize_with_None_in_ids(self, pytester: Pytester) -> None:
1429 pytester.makepyfile(
1430 """
1431 import pytest
1432 def pytest_generate_tests(metafunc):
1433 metafunc.parametrize(("a", "b"), [(1,1), (1,1), (1,2)],
1434 ids=["basic", None, "advanced"])
1435
1436 def test_function(a, b):
1437 assert a == b
1438 """
1439 )
1440 result = pytester.runpytest("-v")
1441 assert result.ret == 1
1442 result.stdout.fnmatch_lines_random(
1443 [
1444 "*test_function*basic*PASSED*",
1445 "*test_function*1-1*PASSED*",
1446 "*test_function*advanced*FAILED*",
1447 ]
1448 )
1449
1450 def test_fixture_parametrized_empty_ids(self, pytester: Pytester) -> None:
1451 """Fixtures parametrized with empty ids cause an internal error (#1849)."""
1452 pytester.makepyfile(
1453 """
1454 import pytest
1455
1456 @pytest.fixture(scope="module", ids=[], params=[])
1457 def temp(request):
1458 return request.param
1459
1460 def test_temp(temp):
1461 pass
1462 """
1463 )
1464 result = pytester.runpytest()
1465 result.stdout.fnmatch_lines(["* 1 skipped *"])
1466
1467 def test_parametrized_empty_ids(self, pytester: Pytester) -> None:
1468 """Tests parametrized with empty ids cause an internal error (#1849)."""
1469 pytester.makepyfile(
1470 """
1471 import pytest
1472
1473 @pytest.mark.parametrize('temp', [], ids=list())
1474 def test_temp(temp):
1475 pass
1476 """
1477 )
1478 result = pytester.runpytest()
1479 result.stdout.fnmatch_lines(["* 1 skipped *"])
1480
1481 def test_parametrized_ids_invalid_type(self, pytester: Pytester) -> None:
1482 """Test error with non-strings/non-ints, without generator (#1857)."""
1483 pytester.makepyfile(
1484 """
1485 import pytest
1486
1487 @pytest.mark.parametrize("x, expected", [(1, 2), (3, 4), (5, 6)], ids=(None, 2, OSError()))
1488 def test_ids_numbers(x,expected):
1489 assert x * 2 == expected
1490 """
1491 )
1492 result = pytester.runpytest()
1493 result.stdout.fnmatch_lines(
1494 [
1495 "In test_parametrized_ids_invalid_type.py::test_ids_numbers: ids contains unsupported value "
1496 "OSError() (type: <class 'OSError'>) at index 2. "
1497 "Supported types are: str, bytes, int, float, complex, bool, enum, regex or anything with a __name__."
1498 ]
1499 )
1500
1501 def test_parametrize_with_identical_ids_get_unique_names(
1502 self, pytester: Pytester
1503 ) -> None:
1504 pytester.makepyfile(
1505 """
1506 import pytest
1507 def pytest_generate_tests(metafunc):
1508 metafunc.parametrize(("a", "b"), [(1,1), (1,2)],
1509 ids=["a", "a"])
1510
1511 def test_function(a, b):
1512 assert a == b
1513 """
1514 )
1515 result = pytester.runpytest("-v")
1516 assert result.ret == 1
1517 result.stdout.fnmatch_lines_random(
1518 ["*test_function*a0*PASSED*", "*test_function*a1*FAILED*"]
1519 )
1520
1521 @pytest.mark.parametrize(("scope", "length"), [("module", 2), ("function", 4)])
1522 def test_parametrize_scope_overrides(
1523 self, pytester: Pytester, scope: str, length: int
1524 ) -> None:
1525 pytester.makepyfile(
1526 f"""
1527 import pytest
1528 values = []
1529 def pytest_generate_tests(metafunc):
1530 if "arg" in metafunc.fixturenames:
1531 metafunc.parametrize("arg", [1,2], indirect=True,
1532 scope={scope!r})
1533 @pytest.fixture
1534 def arg(request):
1535 values.append(request.param)
1536 return request.param
1537 def test_hello(arg):
1538 assert arg in (1,2)
1539 def test_world(arg):
1540 assert arg in (1,2)
1541 def test_checklength():
1542 assert len(values) == {length}
1543 """
1544 )
1545 reprec = pytester.inline_run()
1546 reprec.assertoutcome(passed=5)
1547
1548 def test_parametrize_issue323(self, pytester: Pytester) -> None:
1549 pytester.makepyfile(
1550 """
1551 import pytest
1552
1553 @pytest.fixture(scope='module', params=range(966))
1554 def foo(request):
1555 return request.param
1556
1557 def test_it(foo):
1558 pass
1559 def test_it2(foo):
1560 pass
1561 """
1562 )
1563 reprec = pytester.inline_run("--collect-only")
1564 assert not reprec.getcalls("pytest_internalerror")
1565
1566 def test_usefixtures_seen_in_generate_tests(self, pytester: Pytester) -> None:
1567 pytester.makepyfile(
1568 """
1569 import pytest
1570 def pytest_generate_tests(metafunc):
1571 assert "abc" in metafunc.fixturenames
1572 metafunc.parametrize("abc", [1])
1573
1574 @pytest.mark.usefixtures("abc")
1575 def test_function():
1576 pass
1577 """
1578 )
1579 reprec = pytester.runpytest()
1580 reprec.assert_outcomes(passed=1)
1581
1582 def test_generate_tests_only_done_in_subdir(self, pytester: Pytester) -> None:
1583 sub1 = pytester.mkpydir("sub1")
1584 sub2 = pytester.mkpydir("sub2")
1585 sub1.joinpath("conftest.py").write_text(
1586 textwrap.dedent(
1587 """\
1588 def pytest_generate_tests(metafunc):
1589 assert metafunc.function.__name__ == "test_1"
1590 """
1591 ),
1592 encoding="utf-8",
1593 )
1594 sub2.joinpath("conftest.py").write_text(
1595 textwrap.dedent(
1596 """\
1597 def pytest_generate_tests(metafunc):
1598 assert metafunc.function.__name__ == "test_2"
1599 """
1600 ),
1601 encoding="utf-8",
1602 )
1603 sub1.joinpath("test_in_sub1.py").write_text(
1604 "def test_1(): pass", encoding="utf-8"
1605 )
1606 sub2.joinpath("test_in_sub2.py").write_text(
1607 "def test_2(): pass", encoding="utf-8"
1608 )
1609 result = pytester.runpytest("--keep-duplicates", "-v", "-s", sub1, sub2, sub1)
1610 result.assert_outcomes(passed=3)
1611
1612 def test_generate_same_function_names_issue403(self, pytester: Pytester) -> None:
1613 pytester.makepyfile(
1614 """
1615 import pytest
1616
1617 def make_tests():
1618 @pytest.mark.parametrize("x", range(2))
1619 def test_foo(x):
1620 pass
1621 return test_foo
1622
1623 test_x = make_tests()
1624 test_y = make_tests()
1625 """
1626 )
1627 reprec = pytester.runpytest()
1628 reprec.assert_outcomes(passed=4)
1629
1630 def test_parametrize_misspelling(self, pytester: Pytester) -> None:
1631 """#463"""
1632 pytester.makepyfile(
1633 """
1634 import pytest
1635
1636 @pytest.mark.parametrise("x", range(2))
1637 def test_foo(x):
1638 pass
1639 """
1640 )
1641 result = pytester.runpytest("--collect-only")
1642 result.stdout.fnmatch_lines(
1643 [
1644 "collected 0 items / 1 error",
1645 "",
1646 "*= ERRORS =*",
1647 "*_ ERROR collecting test_parametrize_misspelling.py _*",
1648 "test_parametrize_misspelling.py:3: in <module>",
1649 ' @pytest.mark.parametrise("x", range(2))',
1650 "E Failed: Unknown 'parametrise' mark, did you mean 'parametrize'?",
1651 "*! Interrupted: 1 error during collection !*",
1652 "*= no tests collected, 1 error in *",
1653 ]
1654 )
1655
1656 @pytest.mark.parametrize("scope", ["class", "package"])
1657 def test_parametrize_missing_scope_doesnt_crash(
1658 self, pytester: Pytester, scope: str
1659 ) -> None:
1660 """Doesn't crash when parametrize(scope=<scope>) is used without a
1661 corresponding <scope> node."""
1662 pytester.makepyfile(
1663 f"""
1664 import pytest
1665
1666 @pytest.mark.parametrize("x", [0], scope="{scope}")
1667 def test_it(x): pass
1668 """
1669 )
1670 result = pytester.runpytest()
1671 assert result.ret == 0
1672
1673 def test_parametrize_module_level_test_with_class_scope(
1674 self, pytester: Pytester
1675 ) -> None:
1676 """
1677 Test that a class-scoped parametrization without a corresponding `Class`
1678 gets module scope, i.e. we only create a single FixtureDef for it per module.
1679 """
1680 module = pytester.makepyfile(
1681 """
1682 import pytest
1683
1684 @pytest.mark.parametrize("x", [0, 1], scope="class")
1685 def test_1(x):
1686 pass
1687
1688 @pytest.mark.parametrize("x", [1, 2], scope="module")
1689 def test_2(x):
1690 pass
1691 """
1692 )
1693 test_1_0, _, test_2_0, _ = pytester.genitems((pytester.getmodulecol(module),))
1694
1695 assert isinstance(test_1_0, Function)
1696 assert test_1_0.name == "test_1[0]"
1697 test_1_fixture_x = test_1_0._fixtureinfo.name2fixturedefs["x"][-1]
1698
1699 assert isinstance(test_2_0, Function)
1700 assert test_2_0.name == "test_2[1]"
1701 test_2_fixture_x = test_2_0._fixtureinfo.name2fixturedefs["x"][-1]
1702
1703 assert test_1_fixture_x is test_2_fixture_x
1704
1705 def test_reordering_with_scopeless_and_just_indirect_parametrization(
1706 self, pytester: Pytester
1707 ) -> None:
1708 pytester.makeconftest(
1709 """
1710 import pytest
1711
1712 @pytest.fixture(scope="package")
1713 def fixture1():
1714 pass
1715 """
1716 )
1717 pytester.makepyfile(
1718 """
1719 import pytest
1720
1721 @pytest.fixture(scope="module")
1722 def fixture0():
1723 pass
1724
1725 @pytest.fixture(scope="module")
1726 def fixture1(fixture0):
1727 pass
1728
1729 @pytest.mark.parametrize("fixture1", [0], indirect=True)
1730 def test_0(fixture1):
1731 pass
1732
1733 @pytest.fixture(scope="module")
1734 def fixture():
1735 pass
1736
1737 @pytest.mark.parametrize("fixture", [0], indirect=True)
1738 def test_1(fixture):
1739 pass
1740
1741 def test_2():
1742 pass
1743
1744 class Test:
1745 @pytest.fixture(scope="class")
1746 @classmethod
1747 def fixture(cls, fixture):
1748 pass
1749
1750 @pytest.mark.parametrize("fixture", [0], indirect=True)
1751 def test_3(self, fixture):
1752 pass
1753 """
1754 )
1755 result = pytester.runpytest("-v")
1756 assert result.ret == 0
1757 result.stdout.fnmatch_lines(
1758 [
1759 "*test_0*",
1760 "*test_1*",
1761 "*test_2*",
1762 "*test_3*",
1763 ]
1764 )
1765
1766 def test_parametrize_generator_multiple_runs(self, pytester: Pytester) -> None:
1767 """Test that generators in parametrize work with multiple pytest.main() (deprecated)."""
1768 testfile = pytester.makepyfile(
1769 """
1770 import pytest
1771
1772 def data_generator():
1773 yield 1
1774 yield 2
1775
1776 @pytest.mark.parametrize("bar", data_generator())
1777 def test_foo(bar):
1778 pass
1779
1780 if __name__ == '__main__':
1781 args = ["-q", "--collect-only"]
1782 pytest.main(args) # First run - should work with warning
1783 pytest.main(args) # Second run - should also work with warning
1784 """
1785 )
1786 result = pytester.run(sys.executable, "-Wdefault", testfile)
1787 # Should see the deprecation warnings.
1788 result.stdout.fnmatch_lines(
1789 [
1790 "*PytestRemovedIn10Warning: Passing a non-Collection iterable*",
1791 "*PytestRemovedIn10Warning: Passing a non-Collection iterable*",
1792 ]
1793 )
1794
1795 def test_parametrize_iterator_class_multiple_tests(
1796 self, pytester: Pytester
1797 ) -> None:
1798 """Test that iterators in parametrize on a class get exhausted (deprecated)."""
1799 pytester.makepyfile(
1800 """
1801 import pytest
1802
1803 @pytest.mark.parametrize("n", iter(range(2)))
1804 class Test:
1805 def test_1(self, n):
1806 pass
1807
1808 def test_2(self, n):
1809 pass
1810 """
1811 )
1812 result = pytester.runpytest("-v", "-Wdefault")
1813 # Iterator gets exhausted after first test, second test gets no parameters.
1814 # This is deprecated.
1815 result.assert_outcomes(passed=2, skipped=1)
1816 result.stdout.fnmatch_lines(
1817 [
1818 "*test_parametrize_iterator_class_multiple_tests.py::Test::test_1[[]0] PASSED*",
1819 "*test_parametrize_iterator_class_multiple_tests.py::Test::test_1[[]1] PASSED*",
1820 "*test_parametrize_iterator_class_multiple_tests.py::Test::test_2[[]NOTSET] SKIPPED*",
1821 "*PytestRemovedIn10Warning: Passing a non-Collection iterable*",
1822 ]
1823 )
1824
1825
1826 class TestMetafuncFunctionalAuto:
1827 """Tests related to automatically find out the correct scope for
1828 parametrized tests (#1832)."""
1829
1830 def test_parametrize_auto_scope(self, pytester: Pytester) -> None:
1831 pytester.makepyfile(
1832 """
1833 import pytest
1834
1835 @pytest.fixture(scope='session', autouse=True)
1836 def fixture():
1837 return 1
1838
1839 @pytest.mark.parametrize('animal', ["dog", "cat"])
1840 def test_1(animal):
1841 assert animal in ('dog', 'cat')
1842
1843 @pytest.mark.parametrize('animal', ['fish'])
1844 def test_2(animal):
1845 assert animal == 'fish'
1846
1847 """
1848 )
1849 result = pytester.runpytest()
1850 result.stdout.fnmatch_lines(["* 3 passed *"])
1851
1852 def test_parametrize_auto_scope_indirect(self, pytester: Pytester) -> None:
1853 pytester.makepyfile(
1854 """
1855 import pytest
1856
1857 @pytest.fixture(scope='session')
1858 def echo(request):
1859 return request.param
1860
1861 @pytest.mark.parametrize('animal, echo', [("dog", 1), ("cat", 2)], indirect=['echo'])
1862 def test_1(animal, echo):
1863 assert animal in ('dog', 'cat')
1864 assert echo in (1, 2, 3)
1865
1866 @pytest.mark.parametrize('animal, echo', [('fish', 3)], indirect=['echo'])
1867 def test_2(animal, echo):
1868 assert animal == 'fish'
1869 assert echo in (1, 2, 3)
1870 """
1871 )
1872 result = pytester.runpytest()
1873 result.stdout.fnmatch_lines(["* 3 passed *"])
1874
1875 def test_parametrize_auto_scope_override_fixture(self, pytester: Pytester) -> None:
1876 pytester.makepyfile(
1877 """
1878 import pytest
1879
1880 @pytest.fixture(scope='session', autouse=True)
1881 def animal():
1882 return 'fox'
1883
1884 @pytest.mark.parametrize('animal', ["dog", "cat"])
1885 def test_1(animal):
1886 assert animal in ('dog', 'cat')
1887 """
1888 )
1889 result = pytester.runpytest()
1890 result.stdout.fnmatch_lines(["* 2 passed *"])
1891
1892 def test_parametrize_all_indirects(self, pytester: Pytester) -> None:
1893 pytester.makepyfile(
1894 """
1895 import pytest
1896
1897 @pytest.fixture()
1898 def animal(request):
1899 return request.param
1900
1901 @pytest.fixture(scope='session')
1902 def echo(request):
1903 return request.param
1904
1905 @pytest.mark.parametrize('animal, echo', [("dog", 1), ("cat", 2)], indirect=True)
1906 def test_1(animal, echo):
1907 assert animal in ('dog', 'cat')
1908 assert echo in (1, 2, 3)
1909
1910 @pytest.mark.parametrize('animal, echo', [("fish", 3)], indirect=True)
1911 def test_2(animal, echo):
1912 assert animal == 'fish'
1913 assert echo in (1, 2, 3)
1914 """
1915 )
1916 result = pytester.runpytest()
1917 result.stdout.fnmatch_lines(["* 3 passed *"])
1918
1919 def test_parametrize_some_arguments_auto_scope(
1920 self, pytester: Pytester, monkeypatch
1921 ) -> None:
1922 """Integration test for (#3941)"""
1923 class_fix_setup: list[object] = []
1924 monkeypatch.setattr(sys, "class_fix_setup", class_fix_setup, raising=False)
1925 func_fix_setup: list[object] = []
1926 monkeypatch.setattr(sys, "func_fix_setup", func_fix_setup, raising=False)
1927
1928 pytester.makepyfile(
1929 """
1930 import pytest
1931 import sys
1932
1933 @pytest.fixture(scope='class', autouse=True)
1934 def class_fix(request):
1935 sys.class_fix_setup.append(request.param)
1936
1937 @pytest.fixture(autouse=True)
1938 def func_fix():
1939 sys.func_fix_setup.append(True)
1940
1941 @pytest.mark.parametrize('class_fix', [10, 20], indirect=True)
1942 class Test:
1943 def test_foo(self):
1944 pass
1945 def test_bar(self):
1946 pass
1947 """
1948 )
1949 result = pytester.runpytest_inprocess()
1950 result.stdout.fnmatch_lines(["* 4 passed in *"])
1951 assert func_fix_setup == [True] * 4
1952 assert class_fix_setup == [10, 20]
1953
1954 def test_parametrize_issue634(self, pytester: Pytester) -> None:
1955 pytester.makepyfile(
1956 """
1957 import pytest
1958
1959 @pytest.fixture(scope='module')
1960 def foo(request):
1961 print('preparing foo-%d' % request.param)
1962 return 'foo-%d' % request.param
1963
1964 def test_one(foo):
1965 pass
1966
1967 def test_two(foo):
1968 pass
1969
1970 test_two.test_with = (2, 3)
1971
1972 def pytest_generate_tests(metafunc):
1973 params = (1, 2, 3, 4)
1974 if not 'foo' in metafunc.fixturenames:
1975 return
1976
1977 test_with = getattr(metafunc.function, 'test_with', None)
1978 if test_with:
1979 params = test_with
1980 metafunc.parametrize('foo', params, indirect=True)
1981 """
1982 )
1983 result = pytester.runpytest("-s")
1984 output = result.stdout.str()
1985 assert output.count("preparing foo-2") == 1
1986 assert output.count("preparing foo-3") == 1
1987
1988
1989 class TestMarkersWithParametrization:
1990 """#308"""
1991
1992 def test_simple_mark(self, pytester: Pytester) -> None:
1993 s = """
1994 import pytest
1995
1996 @pytest.mark.foo
1997 @pytest.mark.parametrize(("n", "expected"), [
1998 (1, 2),
1999 pytest.param(1, 3, marks=pytest.mark.bar),
2000 (2, 3),
2001 ])
2002 def test_increment(n, expected):
2003 assert n + 1 == expected
2004 """
2005 items = pytester.getitems(s)
2006 assert len(items) == 3
2007 for item in items:
2008 assert "foo" in item.keywords
2009 assert "bar" not in items[0].keywords
2010 assert "bar" in items[1].keywords
2011 assert "bar" not in items[2].keywords
2012
2013 def test_select_based_on_mark(self, pytester: Pytester) -> None:
2014 s = """
2015 import pytest
2016
2017 @pytest.mark.parametrize(("n", "expected"), [
2018 (1, 2),
2019 pytest.param(2, 3, marks=pytest.mark.foo),
2020 (3, 4),
2021 ])
2022 def test_increment(n, expected):
2023 assert n + 1 == expected
2024 """
2025 pytester.makepyfile(s)
2026 rec = pytester.inline_run("-m", "foo")
2027 passed, skipped, fail = rec.listoutcomes()
2028 assert len(passed) == 1
2029 assert len(skipped) == 0
2030 assert len(fail) == 0
2031
2032 def test_simple_xfail(self, pytester: Pytester) -> None:
2033 s = """
2034 import pytest
2035
2036 @pytest.mark.parametrize(("n", "expected"), [
2037 (1, 2),
2038 pytest.param(1, 3, marks=pytest.mark.xfail),
2039 (2, 3),
2040 ])
2041 def test_increment(n, expected):
2042 assert n + 1 == expected
2043 """
2044 pytester.makepyfile(s)
2045 reprec = pytester.inline_run()
2046 # xfail is skip??
2047 reprec.assertoutcome(passed=2, skipped=1)
2048
2049 def test_simple_xfail_single_argname(self, pytester: Pytester) -> None:
2050 s = """
2051 import pytest
2052
2053 @pytest.mark.parametrize("n", [
2054 2,
2055 pytest.param(3, marks=pytest.mark.xfail),
2056 4,
2057 ])
2058 def test_isEven(n):
2059 assert n % 2 == 0
2060 """
2061 pytester.makepyfile(s)
2062 reprec = pytester.inline_run()
2063 reprec.assertoutcome(passed=2, skipped=1)
2064
2065 def test_xfail_with_arg(self, pytester: Pytester) -> None:
2066 s = """
2067 import pytest
2068
2069 @pytest.mark.parametrize(("n", "expected"), [
2070 (1, 2),
2071 pytest.param(1, 3, marks=pytest.mark.xfail("True")),
2072 (2, 3),
2073 ])
2074 def test_increment(n, expected):
2075 assert n + 1 == expected
2076 """
2077 pytester.makepyfile(s)
2078 reprec = pytester.inline_run()
2079 reprec.assertoutcome(passed=2, skipped=1)
2080
2081 def test_xfail_with_kwarg(self, pytester: Pytester) -> None:
2082 s = """
2083 import pytest
2084
2085 @pytest.mark.parametrize(("n", "expected"), [
2086 (1, 2),
2087 pytest.param(1, 3, marks=pytest.mark.xfail(reason="some bug")),
2088 (2, 3),
2089 ])
2090 def test_increment(n, expected):
2091 assert n + 1 == expected
2092 """
2093 pytester.makepyfile(s)
2094 reprec = pytester.inline_run()
2095 reprec.assertoutcome(passed=2, skipped=1)
2096
2097 def test_xfail_with_arg_and_kwarg(self, pytester: Pytester) -> None:
2098 s = """
2099 import pytest
2100
2101 @pytest.mark.parametrize(("n", "expected"), [
2102 (1, 2),
2103 pytest.param(1, 3, marks=pytest.mark.xfail("True", reason="some bug")),
2104 (2, 3),
2105 ])
2106 def test_increment(n, expected):
2107 assert n + 1 == expected
2108 """
2109 pytester.makepyfile(s)
2110 reprec = pytester.inline_run()
2111 reprec.assertoutcome(passed=2, skipped=1)
2112
2113 @pytest.mark.parametrize("strict", [True, False])
2114 def test_xfail_passing_is_xpass(self, pytester: Pytester, strict: bool) -> None:
2115 s = f"""
2116 import pytest
2117
2118 m = pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict})
2119
2120 @pytest.mark.parametrize(("n", "expected"), [
2121 (1, 2),
2122 pytest.param(2, 3, marks=m),
2123 (3, 4),
2124 ])
2125 def test_increment(n, expected):
2126 assert n + 1 == expected
2127 """
2128 pytester.makepyfile(s)
2129 reprec = pytester.inline_run()
2130 passed, failed = (2, 1) if strict else (3, 0)
2131 reprec.assertoutcome(passed=passed, failed=failed)
2132
2133 def test_parametrize_called_in_generate_tests(self, pytester: Pytester) -> None:
2134 s = """
2135 import pytest
2136
2137
2138 def pytest_generate_tests(metafunc):
2139 passingTestData = [(1, 2),
2140 (2, 3)]
2141 failingTestData = [(1, 3),
2142 (2, 2)]
2143
2144 testData = passingTestData + [pytest.param(*d, marks=pytest.mark.xfail)
2145 for d in failingTestData]
2146 metafunc.parametrize(("n", "expected"), testData)
2147
2148
2149 def test_increment(n, expected):
2150 assert n + 1 == expected
2151 """
2152 pytester.makepyfile(s)
2153 reprec = pytester.inline_run()
2154 reprec.assertoutcome(passed=2, skipped=2)
2155
2156 def test_parametrize_ID_generation_string_int_works(
2157 self, pytester: Pytester
2158 ) -> None:
2159 """#290"""
2160 pytester.makepyfile(
2161 """
2162 import pytest
2163
2164 @pytest.fixture
2165 def myfixture():
2166 return 'example'
2167 @pytest.mark.parametrize(
2168 'limit', (0, '0'))
2169 def test_limit(limit, myfixture):
2170 return
2171 """
2172 )
2173 reprec = pytester.inline_run()
2174 reprec.assertoutcome(passed=2)
2175
2176 @pytest.mark.parametrize("strict", [True, False])
2177 def test_parametrize_marked_value(self, pytester: Pytester, strict: bool) -> None:
2178 s = f"""
2179 import pytest
2180
2181 @pytest.mark.parametrize(("n", "expected"), [
2182 pytest.param(
2183 2,3,
2184 marks=pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict}),
2185 ),
2186 pytest.param(
2187 2,3,
2188 marks=[pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict})],
2189 ),
2190 ])
2191 def test_increment(n, expected):
2192 assert n + 1 == expected
2193 """
2194 pytester.makepyfile(s)
2195 reprec = pytester.inline_run()
2196 passed, failed = (0, 2) if strict else (2, 0)
2197 reprec.assertoutcome(passed=passed, failed=failed)
2198
2199 def test_pytest_make_parametrize_id(self, pytester: Pytester) -> None:
2200 pytester.makeconftest(
2201 """
2202 def pytest_make_parametrize_id(config, val):
2203 return str(val * 2)
2204 """
2205 )
2206 pytester.makepyfile(
2207 """
2208 import pytest
2209
2210 @pytest.mark.parametrize("x", range(2))
2211 def test_func(x):
2212 pass
2213 """
2214 )
2215 result = pytester.runpytest("-v")
2216 result.stdout.fnmatch_lines(["*test_func*0*PASS*", "*test_func*2*PASS*"])
2217
2218 def test_pytest_make_parametrize_id_with_argname(self, pytester: Pytester) -> None:
2219 pytester.makeconftest(
2220 """
2221 def pytest_make_parametrize_id(config, val, argname):
2222 return str(val * 2 if argname == 'x' else val * 10)
2223 """
2224 )
2225 pytester.makepyfile(
2226 """
2227 import pytest
2228
2229 @pytest.mark.parametrize("x", range(2))
2230 def test_func_a(x):
2231 pass
2232
2233 @pytest.mark.parametrize("y", [1])
2234 def test_func_b(y):
2235 pass
2236 """
2237 )
2238 result = pytester.runpytest("-v")
2239 result.stdout.fnmatch_lines(
2240 ["*test_func_a*0*PASS*", "*test_func_a*2*PASS*", "*test_func_b*10*PASS*"]
2241 )
2242
2243 def test_parametrize_positional_args(self, pytester: Pytester) -> None:
2244 pytester.makepyfile(
2245 """
2246 import pytest
2247
2248 @pytest.mark.parametrize("a", [1], False)
2249 def test_foo(a):
2250 pass
2251 """
2252 )
2253 result = pytester.runpytest()
2254 result.assert_outcomes(passed=1)
2255
2256 def test_parametrize_iterator(self, pytester: Pytester) -> None:
2257 pytester.makepyfile(
2258 """
2259 import itertools
2260 import pytest
2261
2262 id_parametrize = pytest.mark.parametrize(
2263 ids=("param%d" % i for i in itertools.count())
2264 )
2265
2266 @id_parametrize('y', ['a', 'b'])
2267 def test1(y):
2268 pass
2269
2270 @id_parametrize('y', ['a', 'b'])
2271 def test2(y):
2272 pass
2273
2274 @pytest.mark.parametrize("a, b", [(1, 2), (3, 4)], ids=itertools.count())
2275 def test_converted_to_str(a, b):
2276 pass
2277 """
2278 )
2279 result = pytester.runpytest("-vv", "-s")
2280 result.stdout.fnmatch_lines(
2281 [
2282 "test_parametrize_iterator.py::test1[param0] PASSED",
2283 "test_parametrize_iterator.py::test1[param1] PASSED",
2284 "test_parametrize_iterator.py::test2[param0] PASSED",
2285 "test_parametrize_iterator.py::test2[param1] PASSED",
2286 "test_parametrize_iterator.py::test_converted_to_str[0] PASSED",
2287 "test_parametrize_iterator.py::test_converted_to_str[1] PASSED",
2288 "*= 6 passed in *",
2289 ]
2290 )
2291
2292
2293 class TestHiddenParam:
2294 """Test that pytest.HIDDEN_PARAM works"""
2295
2296 def test_parametrize_ids(self, pytester: Pytester) -> None:
2297 items = pytester.getitems(
2298 """
2299 import pytest
2300
2301 @pytest.mark.parametrize(
2302 ("foo", "bar"),
2303 [
2304 ("a", "x"),
2305 ("b", "y"),
2306 ("c", "z"),
2307 ],
2308 ids=["paramset1", pytest.HIDDEN_PARAM, "paramset3"],
2309 )
2310 def test_func(foo, bar):
2311 pass
2312 """
2313 )
2314 names = [item.name for item in items]
2315 assert names == [
2316 "test_func[paramset1]",
2317 "test_func",
2318 "test_func[paramset3]",
2319 ]
2320
2321 def test_param_id(self, pytester: Pytester) -> None:
2322 items = pytester.getitems(
2323 """
2324 import pytest
2325
2326 @pytest.mark.parametrize(
2327 ("foo", "bar"),
2328 [
2329 pytest.param("a", "x", id="paramset1"),
2330 pytest.param("b", "y", id=pytest.HIDDEN_PARAM),
2331 ("c", "z"),
2332 ],
2333 )
2334 def test_func(foo, bar):
2335 pass
2336 """
2337 )
2338 names = [item.name for item in items]
2339 assert names == [
2340 "test_func[paramset1]",
2341 "test_func",
2342 "test_func[c-z]",
2343 ]
2344
2345 def test_multiple_hidden_param_is_forbidden(self, pytester: Pytester) -> None:
2346 pytester.makepyfile(
2347 """
2348 import pytest
2349
2350 @pytest.mark.parametrize(
2351 ("foo", "bar"),
2352 [
2353 ("a", "x"),
2354 ("b", "y"),
2355 ],
2356 ids=[pytest.HIDDEN_PARAM, pytest.HIDDEN_PARAM],
2357 )
2358 def test_func(foo, bar):
2359 pass
2360 """
2361 )
2362 result = pytester.runpytest("--collect-only")
2363 result.stdout.fnmatch_lines(
2364 [
2365 "collected 0 items / 1 error",
2366 "",
2367 "*= ERRORS =*",
2368 "*_ ERROR collecting test_multiple_hidden_param_is_forbidden.py _*",
2369 "E Failed: In test_multiple_hidden_param_is_forbidden.py::test_func: multiple instances of "
2370 "HIDDEN_PARAM cannot be used in the same parametrize call, because the tests names need to be unique.",
2371 "*! Interrupted: 1 error during collection !*",
2372 "*= no tests collected, 1 error in *",
2373 ]
2374 )
2375
2376 def test_multiple_hidden_param_is_forbidden_idmaker(self) -> None:
2377 id_maker = IdMaker(
2378 ("foo", "bar"),
2379 [pytest.param("a", "x"), pytest.param("b", "y")],
2380 None,
2381 [pytest.HIDDEN_PARAM, pytest.HIDDEN_PARAM],
2382 None,
2383 "some_node_id",
2384 )
2385 expected = "In some_node_id: multiple instances of HIDDEN_PARAM"
2386 with pytest.raises(Failed, match=expected):
2387 id_maker.make_unique_parameterset_ids()
2388
2389 def test_idmaker_error_without_nodeid(self) -> None:
2390 id_maker = IdMaker(["a"], [pytest.param("a")], None, [object()], None, None)
2391 with pytest.raises(Failed, match="ids contains unsupported value"):
2392 id_maker.make_unique_parameterset_ids()
2393
2394 def test_multiple_parametrize(self, pytester: Pytester) -> None:
2395 items = pytester.getitems(
2396 """
2397 import pytest
2398
2399 @pytest.mark.parametrize(
2400 "bar",
2401 ["x", "y"],
2402 )
2403 @pytest.mark.parametrize(
2404 "foo",
2405 ["a", "b"],
2406 ids=["a", pytest.HIDDEN_PARAM],
2407 )
2408 def test_func(foo, bar):
2409 pass
2410 """
2411 )
2412 names = [item.name for item in items]
2413 assert names == [
2414 "test_func[a-x]",
2415 "test_func[a-y]",
2416 "test_func[x]",
2417 "test_func[y]",
2418 ]