diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue88_initial_file_multinodes/test_hello.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue88_initial_file_multinodes/test_hello.py
new file mode 100644
index 0000000000000000000000000000000000000000..b10f874e78d8082289d59381bb3de8ec7f9bb258
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue88_initial_file_multinodes/test_hello.py
@@ -0,0 +1,6 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+
+def test_hello():
+ pass
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue_519.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue_519.py
new file mode 100644
index 0000000000000000000000000000000000000000..da5f5ad6aa97b78629cd57c7381965dbbb53c225
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue_519.py
@@ -0,0 +1,54 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import pprint
+
+import pytest
+
+
+def pytest_generate_tests(metafunc):
+ if "arg1" in metafunc.fixturenames:
+ metafunc.parametrize("arg1", ["arg1v1", "arg1v2"], scope="module")
+
+ if "arg2" in metafunc.fixturenames:
+ metafunc.parametrize("arg2", ["arg2v1", "arg2v2"], scope="function")
+
+
+@pytest.fixture(scope="session")
+def checked_order():
+ order: list[tuple[str, str, str]] = []
+
+ yield order
+ pprint.pprint(order)
+ assert order == [
+ ("issue_519.py", "fix1", "arg1v1"),
+ ("test_one[arg1v1-arg2v1]", "fix2", "arg2v1"),
+ ("test_two[arg1v1-arg2v1]", "fix2", "arg2v1"),
+ ("test_one[arg1v1-arg2v2]", "fix2", "arg2v2"),
+ ("test_two[arg1v1-arg2v2]", "fix2", "arg2v2"),
+ ("issue_519.py", "fix1", "arg1v2"),
+ ("test_one[arg1v2-arg2v1]", "fix2", "arg2v1"),
+ ("test_two[arg1v2-arg2v1]", "fix2", "arg2v1"),
+ ("test_one[arg1v2-arg2v2]", "fix2", "arg2v2"),
+ ("test_two[arg1v2-arg2v2]", "fix2", "arg2v2"),
+ ]
+
+
+@pytest.fixture(scope="module")
+def fix1(request, arg1, checked_order):
+ checked_order.append((request.node.name, "fix1", arg1))
+ yield "fix1-" + arg1
+
+
+@pytest.fixture(scope="function")
+def fix2(request, fix1, arg2, checked_order):
+ checked_order.append((request.node.name, "fix2", arg2))
+ yield "fix2-" + arg2 + fix1
+
+
+def test_one(fix2):
+ pass
+
+
+def test_two(fix2):
+ pass
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/junit-10.xsd b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/junit-10.xsd
new file mode 100644
index 0000000000000000000000000000000000000000..286fbf7c87b127386b1596835044550628801cb0
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/junit-10.xsd
@@ -0,0 +1,147 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/__init__.pyi b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/conftest.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/test_marks_as_keywords.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/test_marks_as_keywords.py
new file mode 100644
index 0000000000000000000000000000000000000000..c98e58316eb0ed725047358c2dec08c57b14cf4c
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/test_marks_as_keywords.py
@@ -0,0 +1,9 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import pytest
+
+
+@pytest.mark.foo
+def test_mark():
+ pass
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/.gitignore b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..1c45c2ea351a709822b79d16aa36146baba80c92
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/.gitignore
@@ -0,0 +1 @@
+foo_*
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/generate_folders.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/generate_folders.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b580aa341aae4743b15b80318a2e3c0c3b6ad32
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/generate_folders.py
@@ -0,0 +1,31 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import argparse
+import pathlib
+
+
+HERE = pathlib.Path(__file__).parent
+TEST_CONTENT = (HERE / "template_test.py").read_bytes()
+
+parser = argparse.ArgumentParser()
+parser.add_argument("numbers", nargs="*", type=int)
+
+
+def generate_folders(root, elements, *more_numbers):
+ fill_len = len(str(elements))
+ if more_numbers:
+ for i in range(elements):
+ new_folder = root.joinpath(f"foo_{i:0>{fill_len}}")
+ new_folder.mkdir()
+ new_folder.joinpath("__init__.py").write_bytes(TEST_CONTENT)
+ generate_folders(new_folder, *more_numbers)
+ else:
+ for i in range(elements):
+ new_test = root.joinpath(f"test_{i:0<{fill_len}}.py")
+ new_test.write_bytes(TEST_CONTENT)
+
+
+if __name__ == "__main__":
+ args = parser.parse_args()
+ generate_folders(HERE, *(args.numbers or (10, 100)))
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/template_test.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/template_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9449485db68a8b4434d61f9168722268b9dbf15
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/template_test.py
@@ -0,0 +1,6 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+
+def test_x():
+ pass
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/pytest.ini b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/pytest.ini
new file mode 100644
index 0000000000000000000000000000000000000000..ec5fe0e83a70510f965077497e989ead968322ce
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/pytest.ini
@@ -0,0 +1,2 @@
+[pytest]
+# dummy pytest.ini to ease direct running of example scripts
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/tmpdir/tmp_path_fixture.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/tmpdir/tmp_path_fixture.py
new file mode 100644
index 0000000000000000000000000000000000000000..503ead473e7aa34404cfdf237a20ae57c8ba5d58
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/tmpdir/tmp_path_fixture.py
@@ -0,0 +1,10 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import pytest
+
+
+@pytest.mark.parametrize("a", [r"qwe/\abc"])
+def test_fixture(tmp_path, a):
+ assert tmp_path.is_dir()
+ assert list(tmp_path.iterdir()) == []
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_parametrized_fixture_error_message.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_parametrized_fixture_error_message.py
new file mode 100644
index 0000000000000000000000000000000000000000..733202915e4d00ff0755f67127ed6ed122b67e8c
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_parametrized_fixture_error_message.py
@@ -0,0 +1,17 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import unittest
+
+import pytest
+
+
+@pytest.fixture(params=[1, 2])
+def two(request):
+ return request.param
+
+
+@pytest.mark.usefixtures("two")
+class TestSomethingElse(unittest.TestCase):
+ def test_two(self):
+ pass
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip.py
new file mode 100644
index 0000000000000000000000000000000000000000..52ff96ea8be9662264c463e4bb340d114880b203
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip.py
@@ -0,0 +1,17 @@
+# mypy: allow-untyped-defs
+"""Skipping an entire subclass with unittest.skip() should *not* call setUp from a base class."""
+
+from __future__ import annotations
+
+import unittest
+
+
+class Base(unittest.TestCase):
+ def setUp(self):
+ assert 0
+
+
+@unittest.skip("skip all tests")
+class Test(Base):
+ def test_foo(self):
+ assert 0
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_class.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_class.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe431d8e794328abbe61ac7207ef0bf1090d094f
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_class.py
@@ -0,0 +1,18 @@
+# mypy: allow-untyped-defs
+"""Skipping an entire subclass with unittest.skip() should *not* call setUpClass from a base class."""
+
+from __future__ import annotations
+
+import unittest
+
+
+class Base(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ assert 0
+
+
+@unittest.skip("skip all tests")
+class Test(Base):
+ def test_foo(self):
+ assert 0
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_module.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_module.py
new file mode 100644
index 0000000000000000000000000000000000000000..07fd96c9cef90f19640a5ad4d44cc68f21e72de2
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_module.py
@@ -0,0 +1,16 @@
+# mypy: allow-untyped-defs
+"""setUpModule is always called, even if all tests in the module are skipped"""
+
+from __future__ import annotations
+
+import unittest
+
+
+def setUpModule():
+ assert 0
+
+
+@unittest.skip("skip all tests")
+class Base(unittest.TestCase):
+ def test(self):
+ assert 0
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asyncio.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asyncio.py
new file mode 100644
index 0000000000000000000000000000000000000000..8792492b38d88a1b0c2983987ce4fca3ca14cb7b
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asyncio.py
@@ -0,0 +1,27 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from unittest import IsolatedAsyncioTestCase
+
+
+teardowns: list[None] = []
+
+
+class AsyncArguments(IsolatedAsyncioTestCase):
+ async def asyncTearDown(self):
+ teardowns.append(None)
+
+ async def test_something_async(self):
+ async def addition(x, y):
+ return x + y
+
+ self.assertEqual(await addition(2, 2), 4)
+
+ async def test_something_async_fails(self):
+ async def addition(x, y):
+ return x + y
+
+ self.assertEqual(await addition(2, 2), 3)
+
+ def test_teardowns(self):
+ assert len(teardowns) == 2
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asynctest.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asynctest.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a93366b9a34d092515b9bf6e324ec943d776860
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asynctest.py
@@ -0,0 +1,26 @@
+# mypy: allow-untyped-defs
+"""Issue #7110"""
+
+from __future__ import annotations
+
+import asyncio
+
+import asynctest
+
+
+teardowns: list[None] = []
+
+
+class Test(asynctest.TestCase):
+ async def tearDown(self):
+ teardowns.append(None)
+
+ async def test_error(self):
+ await asyncio.sleep(0)
+ self.fail("failing on purpose")
+
+ async def test_ok(self):
+ await asyncio.sleep(0)
+
+ def test_teardowns(self):
+ assert len(teardowns) == 2
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_plain_async.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_plain_async.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea1ae3715517ccd4df8f487241850ad8bc41fee6
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_plain_async.py
@@ -0,0 +1,9 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import unittest
+
+
+class Test(unittest.TestCase):
+ async def test_foo(self):
+ assert False
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee3bc2bbee43ecad23a4cfb210ea1adf69d3872f
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message.py
@@ -0,0 +1,24 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import warnings
+
+import pytest
+
+
+def func(msg):
+ warnings.warn(UserWarning(msg))
+
+
+@pytest.mark.parametrize("i", range(5))
+def test_foo(i):
+ func("foo")
+
+
+def test_foo_1():
+ func("foo")
+
+
+@pytest.mark.parametrize("i", range(5))
+def test_bar(i):
+ func("bar")
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_1.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_1.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc514bafbe98c546d4a759ecccd5dc502d2e5f30
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_1.py
@@ -0,0 +1,24 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import warnings
+
+import pytest
+
+
+def func(msg):
+ warnings.warn(UserWarning(msg))
+
+
+@pytest.mark.parametrize("i", range(20))
+def test_foo(i):
+ func("foo")
+
+
+def test_foo_1():
+ func("foo")
+
+
+@pytest.mark.parametrize("i", range(20))
+def test_bar(i):
+ func("bar")
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_2.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..33d5ce8ce34aead5309833ff0d487ec25cf2c1ec
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_2.py
@@ -0,0 +1,8 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from test_1 import func
+
+
+def test_2():
+ func("foo")
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/examples/test_issue519.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/examples/test_issue519.py
new file mode 100644
index 0000000000000000000000000000000000000000..80f78d843a2afd12b29631804cc6b4bc86e423c6
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/examples/test_issue519.py
@@ -0,0 +1,9 @@
+from __future__ import annotations
+
+from _pytest.pytester import Pytester
+
+
+def test_519(pytester: Pytester) -> None:
+ pytester.copy_example("issue_519.py")
+ res = pytester.runpytest("issue_519.py")
+ res.assert_outcomes(passed=8)
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/.gitignore b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..b533190872485742d0f0770921e77e8e7b8b5ed0
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/.gitignore
@@ -0,0 +1,3 @@
+build/
+dist/
+*.spec
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/create_executable.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/create_executable.py
new file mode 100644
index 0000000000000000000000000000000000000000..2015d22c7c0a7a2d758426b5adc892d1c9aa9eec
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/create_executable.py
@@ -0,0 +1,16 @@
+"""Generate an executable with pytest runner embedded using PyInstaller."""
+
+from __future__ import annotations
+
+
+if __name__ == "__main__":
+ import subprocess
+
+ import pytest
+
+ hidden = []
+ for x in pytest.freeze_includes():
+ hidden.extend(["--hidden-import", x])
+ hidden.extend(["--hidden-import", "distutils"])
+ args = ["pyinstaller", "--noconfirm", *hidden, "runtests_script.py"]
+ subprocess.check_call(" ".join(args), shell=True)
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/runtests_script.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/runtests_script.py
new file mode 100644
index 0000000000000000000000000000000000000000..286c98ac5397b9a62dcd96ae6278a7daece55afb
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/runtests_script.py
@@ -0,0 +1,14 @@
+"""
+This is the script that is actually frozen into an executable: simply executes
+pytest main().
+"""
+
+from __future__ import annotations
+
+
+if __name__ == "__main__":
+ import sys
+
+ import pytest
+
+ sys.exit(pytest.main())
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_doctest.txt b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_doctest.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e18a4b68cc967a55cc805a439fb543a79acb0adf
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_doctest.txt
@@ -0,0 +1,6 @@
+
+
+Testing doctest::
+
+ >>> 1 + 1
+ 2
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_trivial.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_trivial.py
new file mode 100644
index 0000000000000000000000000000000000000000..000ca97310c433bbe1b7c7b6c5a387a1e6b17e22
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_trivial.py
@@ -0,0 +1,10 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+
+def test_upper():
+ assert "foo".upper() == "FOO"
+
+
+def test_lower():
+ assert "FOO".lower() == "foo"
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tox_run.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tox_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..38c1e75cf10d0699fef3a9045a708a4e0a7402e6
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tox_run.py
@@ -0,0 +1,16 @@
+"""
+Called by tox.ini: uses the generated executable to run the tests in ./tests/
+directory.
+"""
+
+from __future__ import annotations
+
+
+if __name__ == "__main__":
+ import os
+ import sys
+
+ executable = os.path.join(os.getcwd(), "dist", "runtests_script", "runtests_script")
+ if sys.platform.startswith("win"):
+ executable += ".exe"
+ sys.exit(os.system(f"{executable} tests"))
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_pprint.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_pprint.py
new file mode 100644
index 0000000000000000000000000000000000000000..1326ef34b2ebc67f7af53e6756932ab65554986e
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_pprint.py
@@ -0,0 +1,408 @@
+from __future__ import annotations
+
+from collections import ChainMap
+from collections import Counter
+from collections import defaultdict
+from collections import deque
+from collections import OrderedDict
+from dataclasses import dataclass
+import textwrap
+from types import MappingProxyType
+from types import SimpleNamespace
+from typing import Any
+
+from _pytest._io.pprint import PrettyPrinter
+import pytest
+
+
+@dataclass
+class EmptyDataclass:
+ pass
+
+
+@dataclass
+class DataclassWithOneItem:
+ foo: str
+
+
+@dataclass
+class DataclassWithTwoItems:
+ foo: str
+ bar: str
+
+
+@pytest.mark.parametrize(
+ ("data", "expected"),
+ (
+ pytest.param(
+ EmptyDataclass(),
+ "EmptyDataclass()",
+ id="dataclass-empty",
+ ),
+ pytest.param(
+ DataclassWithOneItem(foo="bar"),
+ """
+ DataclassWithOneItem(
+ foo='bar',
+ )
+ """,
+ id="dataclass-one-item",
+ ),
+ pytest.param(
+ DataclassWithTwoItems(foo="foo", bar="bar"),
+ """
+ DataclassWithTwoItems(
+ foo='foo',
+ bar='bar',
+ )
+ """,
+ id="dataclass-two-items",
+ ),
+ pytest.param(
+ {},
+ "{}",
+ id="dict-empty",
+ ),
+ pytest.param(
+ {"one": 1},
+ """
+ {
+ 'one': 1,
+ }
+ """,
+ id="dict-one-item",
+ ),
+ pytest.param(
+ {"one": 1, "two": 2},
+ """
+ {
+ 'one': 1,
+ 'two': 2,
+ }
+ """,
+ id="dict-two-items",
+ ),
+ pytest.param(OrderedDict(), "OrderedDict()", id="ordereddict-empty"),
+ pytest.param(
+ OrderedDict({"one": 1}),
+ """
+ OrderedDict({
+ 'one': 1,
+ })
+ """,
+ id="ordereddict-one-item",
+ ),
+ pytest.param(
+ OrderedDict({"one": 1, "two": 2}),
+ """
+ OrderedDict({
+ 'one': 1,
+ 'two': 2,
+ })
+ """,
+ id="ordereddict-two-items",
+ ),
+ pytest.param(
+ [],
+ "[]",
+ id="list-empty",
+ ),
+ pytest.param(
+ [1],
+ """
+ [
+ 1,
+ ]
+ """,
+ id="list-one-item",
+ ),
+ pytest.param(
+ [1, 2],
+ """
+ [
+ 1,
+ 2,
+ ]
+ """,
+ id="list-two-items",
+ ),
+ pytest.param(
+ tuple(),
+ "()",
+ id="tuple-empty",
+ ),
+ pytest.param(
+ (1,),
+ """
+ (
+ 1,
+ )
+ """,
+ id="tuple-one-item",
+ ),
+ pytest.param(
+ (1, 2),
+ """
+ (
+ 1,
+ 2,
+ )
+ """,
+ id="tuple-two-items",
+ ),
+ pytest.param(
+ set(),
+ "set()",
+ id="set-empty",
+ ),
+ pytest.param(
+ {1},
+ """
+ {
+ 1,
+ }
+ """,
+ id="set-one-item",
+ ),
+ pytest.param(
+ {1, 2},
+ """
+ {
+ 1,
+ 2,
+ }
+ """,
+ id="set-two-items",
+ ),
+ pytest.param(
+ MappingProxyType({}),
+ "mappingproxy({})",
+ id="mappingproxy-empty",
+ ),
+ pytest.param(
+ MappingProxyType({"one": 1}),
+ """
+ mappingproxy({
+ 'one': 1,
+ })
+ """,
+ id="mappingproxy-one-item",
+ ),
+ pytest.param(
+ MappingProxyType({"one": 1, "two": 2}),
+ """
+ mappingproxy({
+ 'one': 1,
+ 'two': 2,
+ })
+ """,
+ id="mappingproxy-two-items",
+ ),
+ pytest.param(
+ SimpleNamespace(),
+ "namespace()",
+ id="simplenamespace-empty",
+ ),
+ pytest.param(
+ SimpleNamespace(one=1),
+ """
+ namespace(
+ one=1,
+ )
+ """,
+ id="simplenamespace-one-item",
+ ),
+ pytest.param(
+ SimpleNamespace(one=1, two=2),
+ """
+ namespace(
+ one=1,
+ two=2,
+ )
+ """,
+ id="simplenamespace-two-items",
+ ),
+ pytest.param(
+ defaultdict(str), "defaultdict(, {})", id="defaultdict-empty"
+ ),
+ pytest.param(
+ defaultdict(str, {"one": "1"}),
+ """
+ defaultdict(, {
+ 'one': '1',
+ })
+ """,
+ id="defaultdict-one-item",
+ ),
+ pytest.param(
+ defaultdict(str, {"one": "1", "two": "2"}),
+ """
+ defaultdict(, {
+ 'one': '1',
+ 'two': '2',
+ })
+ """,
+ id="defaultdict-two-items",
+ ),
+ pytest.param(
+ Counter(),
+ "Counter()",
+ id="counter-empty",
+ ),
+ pytest.param(
+ Counter("1"),
+ """
+ Counter({
+ '1': 1,
+ })
+ """,
+ id="counter-one-item",
+ ),
+ pytest.param(
+ Counter("121"),
+ """
+ Counter({
+ '1': 2,
+ '2': 1,
+ })
+ """,
+ id="counter-two-items",
+ ),
+ pytest.param(ChainMap(), "ChainMap({})", id="chainmap-empty"),
+ pytest.param(
+ ChainMap({"one": 1, "two": 2}),
+ """
+ ChainMap(
+ {
+ 'one': 1,
+ 'two': 2,
+ },
+ )
+ """,
+ id="chainmap-one-item",
+ ),
+ pytest.param(
+ ChainMap({"one": 1}, {"two": 2}),
+ """
+ ChainMap(
+ {
+ 'one': 1,
+ },
+ {
+ 'two': 2,
+ },
+ )
+ """,
+ id="chainmap-two-items",
+ ),
+ pytest.param(
+ deque(),
+ "deque([])",
+ id="deque-empty",
+ ),
+ pytest.param(
+ deque([1]),
+ """
+ deque([
+ 1,
+ ])
+ """,
+ id="deque-one-item",
+ ),
+ pytest.param(
+ deque([1, 2]),
+ """
+ deque([
+ 1,
+ 2,
+ ])
+ """,
+ id="deque-two-items",
+ ),
+ pytest.param(
+ deque([1, 2], maxlen=3),
+ """
+ deque(maxlen=3, [
+ 1,
+ 2,
+ ])
+ """,
+ id="deque-maxlen",
+ ),
+ pytest.param(
+ {
+ "chainmap": ChainMap({"one": 1}, {"two": 2}),
+ "counter": Counter("122"),
+ "dataclass": DataclassWithTwoItems(foo="foo", bar="bar"),
+ "defaultdict": defaultdict(str, {"one": "1", "two": "2"}),
+ "deque": deque([1, 2], maxlen=3),
+ "dict": {"one": 1, "two": 2},
+ "list": [1, 2],
+ "mappingproxy": MappingProxyType({"one": 1, "two": 2}),
+ "ordereddict": OrderedDict({"one": 1, "two": 2}),
+ "set": {1, 2},
+ "simplenamespace": SimpleNamespace(one=1, two=2),
+ "tuple": (1, 2),
+ },
+ """
+ {
+ 'chainmap': ChainMap(
+ {
+ 'one': 1,
+ },
+ {
+ 'two': 2,
+ },
+ ),
+ 'counter': Counter({
+ '2': 2,
+ '1': 1,
+ }),
+ 'dataclass': DataclassWithTwoItems(
+ foo='foo',
+ bar='bar',
+ ),
+ 'defaultdict': defaultdict(, {
+ 'one': '1',
+ 'two': '2',
+ }),
+ 'deque': deque(maxlen=3, [
+ 1,
+ 2,
+ ]),
+ 'dict': {
+ 'one': 1,
+ 'two': 2,
+ },
+ 'list': [
+ 1,
+ 2,
+ ],
+ 'mappingproxy': mappingproxy({
+ 'one': 1,
+ 'two': 2,
+ }),
+ 'ordereddict': OrderedDict({
+ 'one': 1,
+ 'two': 2,
+ }),
+ 'set': {
+ 1,
+ 2,
+ },
+ 'simplenamespace': namespace(
+ one=1,
+ two=2,
+ ),
+ 'tuple': (
+ 1,
+ 2,
+ ),
+ }
+ """,
+ id="deep-example",
+ ),
+ ),
+)
+def test_consistent_pretty_printer(data: Any, expected: str) -> None:
+ assert PrettyPrinter().pformat(data) == textwrap.dedent(expected).strip()
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_saferepr.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_saferepr.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e3dd55b81fe389e4c2f213dd13c61052950bf4c
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_saferepr.py
@@ -0,0 +1,231 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
+from _pytest._io.saferepr import SafeRepr
+from _pytest._io.saferepr import saferepr
+from _pytest._io.saferepr import saferepr_unlimited
+import pytest
+
+
+def test_simple_repr():
+ assert saferepr(1) == "1"
+ assert saferepr(None) == "None"
+
+
+def test_maxsize():
+ s = saferepr("x" * 50, maxsize=25)
+ assert len(s) == 25
+ expected = repr("x" * 10 + "..." + "x" * 10)
+ assert s == expected
+
+
+def test_no_maxsize():
+ text = "x" * DEFAULT_REPR_MAX_SIZE * 10
+ s = saferepr(text, maxsize=None)
+ expected = repr(text)
+ assert s == expected
+
+
+def test_maxsize_error_on_instance():
+ class A:
+ def __repr__(self):
+ raise ValueError("...")
+
+ s = saferepr(("*" * 50, A()), maxsize=25)
+ assert len(s) == 25
+ assert s[0] == "(" and s[-1] == ")"
+
+
+def test_exceptions() -> None:
+ class BrokenRepr:
+ def __init__(self, ex):
+ self.ex = ex
+
+ def __repr__(self):
+ raise self.ex
+
+ class BrokenReprException(Exception):
+ __str__ = None # type: ignore[assignment]
+ __repr__ = None # type: ignore[assignment]
+
+ assert "Exception" in saferepr(BrokenRepr(Exception("broken")))
+ s = saferepr(BrokenReprException("really broken"))
+ assert "TypeError" in s
+ assert "TypeError" in saferepr(BrokenRepr("string"))
+
+ none = None
+ try:
+ none() # type: ignore[misc]
+ except BaseException as exc:
+ exp_exc = repr(exc)
+ obj = BrokenRepr(BrokenReprException("omg even worse"))
+ s2 = saferepr(obj)
+ assert s2 == (
+ f"<[unpresentable exception ({exp_exc!s}) raised in repr()] BrokenRepr object at 0x{id(obj):x}>"
+ )
+
+
+def test_baseexception():
+ """Test saferepr() with BaseExceptions, which includes pytest outcomes."""
+
+ class RaisingOnStrRepr(BaseException):
+ def __init__(self, exc_types):
+ self.exc_types = exc_types
+
+ def raise_exc(self, *args):
+ try:
+ self.exc_type = self.exc_types.pop(0)
+ except IndexError:
+ pass
+ if hasattr(self.exc_type, "__call__"):
+ raise self.exc_type(*args)
+ raise self.exc_type
+
+ def __str__(self): # noqa: PLE0307
+ self.raise_exc("__str__")
+
+ def __repr__(self):
+ self.raise_exc("__repr__")
+
+ class BrokenObj:
+ def __init__(self, exc):
+ self.exc = exc
+
+ def __repr__(self):
+ raise self.exc
+
+ __str__ = __repr__
+
+ baseexc_str = BaseException("__str__")
+ obj = BrokenObj(RaisingOnStrRepr([BaseException]))
+ assert saferepr(obj) == (
+ f"<[unpresentable exception ({baseexc_str!r}) "
+ f"raised in repr()] BrokenObj object at 0x{id(obj):x}>"
+ )
+ obj = BrokenObj(RaisingOnStrRepr([RaisingOnStrRepr([BaseException])]))
+ assert saferepr(obj) == (
+ f"<[{baseexc_str!r} raised in repr()] BrokenObj object at 0x{id(obj):x}>"
+ )
+
+ with pytest.raises(KeyboardInterrupt):
+ saferepr(BrokenObj(KeyboardInterrupt()))
+
+ with pytest.raises(SystemExit):
+ saferepr(BrokenObj(SystemExit()))
+
+ with pytest.raises(KeyboardInterrupt):
+ saferepr(BrokenObj(RaisingOnStrRepr([KeyboardInterrupt])))
+
+ with pytest.raises(SystemExit):
+ saferepr(BrokenObj(RaisingOnStrRepr([SystemExit])))
+
+ with pytest.raises(KeyboardInterrupt):
+ print(saferepr(BrokenObj(RaisingOnStrRepr([BaseException, KeyboardInterrupt]))))
+
+ with pytest.raises(SystemExit):
+ saferepr(BrokenObj(RaisingOnStrRepr([BaseException, SystemExit])))
+
+
+def test_buggy_builtin_repr():
+ # Simulate a case where a repr for a builtin raises.
+ # reprlib dispatches by type name, so use "int".
+
+ class int:
+ def __repr__(self):
+ raise ValueError("Buggy repr!")
+
+ assert "Buggy" in saferepr(int())
+
+
+def test_big_repr():
+ from _pytest._io.saferepr import SafeRepr
+
+ assert len(saferepr(range(1000))) <= len("[" + SafeRepr(0).maxlist * "1000" + "]")
+
+
+def test_repr_on_newstyle() -> None:
+ class Function:
+ def __repr__(self):
+ return f"<{self.name}>" # type: ignore[attr-defined]
+
+ assert saferepr(Function())
+
+
+def test_unicode():
+ val = "£€"
+ reprval = "'£€'"
+ assert saferepr(val) == reprval
+
+
+def test_broken_getattribute():
+ """saferepr() can create proper representations of classes with
+ broken __getattribute__ (#7145)
+ """
+
+ class SomeClass:
+ def __getattribute__(self, attr):
+ raise RuntimeError
+
+ def __repr__(self):
+ raise RuntimeError
+
+ assert saferepr(SomeClass()).startswith(
+ "<[RuntimeError() raised in repr()] SomeClass object at 0x"
+ )
+
+
+def test_saferepr_unlimited():
+ dict5 = {f"v{i}": i for i in range(5)}
+ assert saferepr_unlimited(dict5) == "{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4}"
+
+ dict_long = {f"v{i}": i for i in range(1_000)}
+ r = saferepr_unlimited(dict_long)
+ assert "..." not in r
+ assert "\n" not in r
+
+
+def test_saferepr_unlimited_exc():
+ class A:
+ def __repr__(self):
+ raise ValueError(42)
+
+ assert saferepr_unlimited(A()).startswith(
+ "<[ValueError(42) raised in repr()] A object at 0x"
+ )
+
+
+def test_saferepr_dict_preserves_insertion_order() -> None:
+ d = {
+ "b": 2,
+ "a": 1,
+ "d": 4,
+ "e": 5,
+ "c": 3,
+ }
+ s = SafeRepr(maxsize=None)
+ s.maxdict = 10
+ assert s.repr(d) == "{'b': 2, 'a': 1, 'd': 4, 'e': 5, 'c': 3}"
+
+
+def test_saferepr_dict_truncation_preserves_insertion_order() -> None:
+ d = {
+ "b": 2,
+ "a": 1,
+ "d": 4,
+ "e": 5,
+ "c": 3,
+ }
+ s = SafeRepr(maxsize=None)
+ s.maxdict = 1
+ assert s.repr(d) == "{'b': 2, ...}"
+
+
+def test_saferepr_dict_fillvalue_when_level_is_zero() -> None:
+ s = SafeRepr(maxsize=None)
+ assert s.repr_dict({"a": 1}, level=0) == "{...}"
+
+
+def test_saferepr_dict_empty() -> None:
+ s = SafeRepr(maxsize=None)
+ assert s.repr_dict({}, level=1) == "{}"
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_terminalwriter.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_terminalwriter.py
new file mode 100644
index 0000000000000000000000000000000000000000..9aa89da0e41e375a2a5be917c104e91008231c7b
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_terminalwriter.py
@@ -0,0 +1,325 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from collections.abc import Generator
+import io
+from io import StringIO
+import os
+from pathlib import Path
+import re
+import shutil
+import sys
+from unittest import mock
+
+from _pytest._io import terminalwriter
+from _pytest.monkeypatch import MonkeyPatch
+import pytest
+
+
+# These tests were initially copied from py 1.8.1.
+
+
+def test_terminal_width_COLUMNS(monkeypatch: MonkeyPatch) -> None:
+ monkeypatch.setenv("COLUMNS", "42")
+ assert terminalwriter.get_terminal_width() == 42
+ monkeypatch.delenv("COLUMNS", raising=False)
+
+
+def test_terminalwriter_width_bogus(monkeypatch: MonkeyPatch) -> None:
+ monkeypatch.setattr(shutil, "get_terminal_size", mock.Mock(return_value=(10, 10)))
+ monkeypatch.delenv("COLUMNS", raising=False)
+ tw = terminalwriter.TerminalWriter()
+ assert tw.fullwidth == 80
+
+
+def test_terminalwriter_computes_width(monkeypatch: MonkeyPatch) -> None:
+ monkeypatch.setattr(terminalwriter, "get_terminal_width", lambda: 42)
+ tw = terminalwriter.TerminalWriter()
+ assert tw.fullwidth == 42
+
+
+def test_terminalwriter_dumb_term_no_markup(monkeypatch: MonkeyPatch) -> None:
+ monkeypatch.setattr(os, "environ", {"TERM": "dumb", "PATH": ""})
+
+ class MyFile:
+ closed = False
+
+ def isatty(self):
+ return True
+
+ with monkeypatch.context() as m:
+ m.setattr(sys, "stdout", MyFile())
+ assert sys.stdout.isatty()
+ tw = terminalwriter.TerminalWriter()
+ assert not tw.hasmarkup
+
+
+def test_terminalwriter_not_unicode() -> None:
+ """If the file doesn't support Unicode, the string is unicode-escaped (#7475)."""
+ buffer = io.BytesIO()
+ file = io.TextIOWrapper(buffer, encoding="cp1252")
+ tw = terminalwriter.TerminalWriter(file)
+ tw.write("hello 🌀 wôrld אבג", flush=True)
+ assert buffer.getvalue() == rb"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2"
+
+
+win32 = int(sys.platform == "win32")
+
+
+class TestTerminalWriter:
+ @pytest.fixture(params=["path", "stringio"])
+ def tw(self, request, tmp_path: Path) -> Generator[terminalwriter.TerminalWriter]:
+ f: io.TextIOWrapper | StringIO
+ if request.param == "path":
+ p = tmp_path.joinpath("tmpfile")
+ f = open(str(p), "w+", encoding="utf8")
+ tw = terminalwriter.TerminalWriter(f)
+
+ def getlines():
+ f.flush()
+ with open(str(p), encoding="utf8") as fp:
+ return fp.readlines()
+
+ elif request.param == "stringio":
+ f = io.StringIO()
+ tw = terminalwriter.TerminalWriter(f)
+
+ def getlines():
+ f.seek(0)
+ return f.readlines()
+
+ tw.getlines = getlines # type: ignore
+ tw.getvalue = lambda: "".join(getlines()) # type: ignore
+
+ with f:
+ yield tw
+
+ def test_line(self, tw) -> None:
+ tw.line("hello")
+ lines = tw.getlines()
+ assert len(lines) == 1
+ assert lines[0] == "hello\n"
+
+ def test_line_unicode(self, tw) -> None:
+ msg = "b\u00f6y"
+ tw.line(msg)
+ lines = tw.getlines()
+ assert lines[0] == msg + "\n"
+
+ def test_sep_no_title(self, tw) -> None:
+ tw.sep("-", fullwidth=60)
+ lines = tw.getlines()
+ assert len(lines) == 1
+ assert lines[0] == "-" * (60 - win32) + "\n"
+
+ def test_sep_with_title(self, tw) -> None:
+ tw.sep("-", "hello", fullwidth=60)
+ lines = tw.getlines()
+ assert len(lines) == 1
+ assert lines[0] == "-" * 26 + " hello " + "-" * (27 - win32) + "\n"
+
+ def test_sep_longer_than_width(self, tw) -> None:
+ tw.sep("-", "a" * 10, fullwidth=5)
+ (line,) = tw.getlines()
+ # even though the string is wider than the line, still have a separator
+ assert line == "- aaaaaaaaaa -\n"
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi")
+ @pytest.mark.parametrize("bold", (True, False))
+ @pytest.mark.parametrize("color", ("red", "green"))
+ def test_markup(self, tw, bold: bool, color: str) -> None:
+ text = tw.markup("hello", **{color: True, "bold": bold})
+ assert "hello" in text
+
+ def test_markup_bad(self, tw) -> None:
+ with pytest.raises(ValueError):
+ tw.markup("x", wronkw=3)
+ with pytest.raises(ValueError):
+ tw.markup("x", wronkw=0)
+
+ def test_line_write_markup(self, tw) -> None:
+ tw.hasmarkup = True
+ tw.line("x", bold=True)
+ tw.write("x\n", red=True)
+ lines = tw.getlines()
+ if sys.platform != "win32":
+ assert len(lines[0]) >= 2, lines
+ assert len(lines[1]) >= 2, lines
+
+ def test_attr_fullwidth(self, tw) -> None:
+ tw.sep("-", "hello", fullwidth=70)
+ tw.fullwidth = 70
+ tw.sep("-", "hello")
+ lines = tw.getlines()
+ assert len(lines[0]) == len(lines[1])
+
+
+@pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi")
+def test_attr_hasmarkup() -> None:
+ file = io.StringIO()
+ tw = terminalwriter.TerminalWriter(file)
+ assert not tw.hasmarkup
+ tw.hasmarkup = True
+ tw.line("hello", bold=True)
+ s = file.getvalue()
+ assert len(s) > len("hello\n")
+ assert "\x1b[1m" in s
+ assert "\x1b[0m" in s
+
+
+def assert_color(expected: bool, default: bool | None = None) -> None:
+ file = io.StringIO()
+ if default is None:
+ default = not expected
+ file.isatty = lambda: default # type: ignore
+ tw = terminalwriter.TerminalWriter(file=file)
+ assert tw.hasmarkup is expected
+ tw.line("hello", bold=True)
+ s = file.getvalue()
+ if expected:
+ assert len(s) > len("hello\n")
+ assert "\x1b[1m" in s
+ assert "\x1b[0m" in s
+ else:
+ assert s == "hello\n"
+
+
+def test_should_do_markup_PY_COLORS_eq_1(monkeypatch: MonkeyPatch) -> None:
+ monkeypatch.setitem(os.environ, "PY_COLORS", "1")
+ assert_color(True)
+
+
+def test_should_not_do_markup_PY_COLORS_eq_0(monkeypatch: MonkeyPatch) -> None:
+ monkeypatch.setitem(os.environ, "PY_COLORS", "0")
+ assert_color(False)
+
+
+def test_should_not_do_markup_NO_COLOR(monkeypatch: MonkeyPatch) -> None:
+ monkeypatch.setitem(os.environ, "NO_COLOR", "1")
+ assert_color(False)
+
+
+def test_should_do_markup_FORCE_COLOR(monkeypatch: MonkeyPatch) -> None:
+ monkeypatch.setitem(os.environ, "FORCE_COLOR", "1")
+ assert_color(True)
+
+
+@pytest.mark.parametrize(
+ ["NO_COLOR", "FORCE_COLOR", "expected"],
+ [
+ ("1", "1", False),
+ ("", "1", True),
+ ("1", "", False),
+ ],
+)
+def test_NO_COLOR_and_FORCE_COLOR(
+ monkeypatch: MonkeyPatch,
+ NO_COLOR: str,
+ FORCE_COLOR: str,
+ expected: bool,
+) -> None:
+ monkeypatch.setitem(os.environ, "NO_COLOR", NO_COLOR)
+ monkeypatch.setitem(os.environ, "FORCE_COLOR", FORCE_COLOR)
+ assert_color(expected)
+
+
+def test_empty_NO_COLOR_and_FORCE_COLOR_ignored(monkeypatch: MonkeyPatch) -> None:
+ monkeypatch.setenv("TERM", "xterm-256color")
+ monkeypatch.setitem(os.environ, "NO_COLOR", "")
+ monkeypatch.setitem(os.environ, "FORCE_COLOR", "")
+ assert_color(True, True)
+ assert_color(False, False)
+
+
+class TestTerminalWriterLineWidth:
+ def test_init(self) -> None:
+ tw = terminalwriter.TerminalWriter()
+ assert tw.width_of_current_line == 0
+
+ def test_update(self) -> None:
+ tw = terminalwriter.TerminalWriter()
+ tw.write("hello world")
+ assert tw.width_of_current_line == 11
+
+ def test_update_with_newline(self) -> None:
+ tw = terminalwriter.TerminalWriter()
+ tw.write("hello\nworld")
+ assert tw.width_of_current_line == 5
+
+ def test_update_with_wide_text(self) -> None:
+ tw = terminalwriter.TerminalWriter()
+ tw.write("乇乂ㄒ尺卂 ㄒ卄丨匚匚")
+ assert tw.width_of_current_line == 21 # 5*2 + 1 + 5*2
+
+ def test_composed(self) -> None:
+ tw = terminalwriter.TerminalWriter()
+ text = "café food"
+ assert len(text) == 9
+ tw.write(text)
+ assert tw.width_of_current_line == 9
+
+ def test_combining(self) -> None:
+ tw = terminalwriter.TerminalWriter()
+ text = "café food"
+ assert len(text) == 10
+ tw.write(text)
+ assert tw.width_of_current_line == 9
+
+
+@pytest.mark.parametrize(
+ ("has_markup", "code_highlight", "expected"),
+ [
+ pytest.param(
+ True,
+ True,
+ "{reset}{kw}assert{hl-reset} {number}0{hl-reset}{endline}\n",
+ id="with markup and code_highlight",
+ ),
+ pytest.param(
+ True,
+ False,
+ "assert 0\n",
+ id="with markup but no code_highlight",
+ ),
+ pytest.param(
+ False,
+ True,
+ "assert 0\n",
+ id="without markup but with code_highlight",
+ ),
+ pytest.param(
+ False,
+ False,
+ "assert 0\n",
+ id="neither markup nor code_highlight",
+ ),
+ ],
+)
+def test_code_highlight(has_markup, code_highlight, expected, color_mapping):
+ f = io.StringIO()
+ tw = terminalwriter.TerminalWriter(f)
+ tw.hasmarkup = has_markup
+ tw.code_highlight = code_highlight
+ tw._write_source(["assert 0"])
+
+ assert f.getvalue().splitlines(keepends=True) == color_mapping.format([expected])
+
+ with pytest.raises(
+ ValueError,
+ match=re.escape("indents size (2) should have same size as lines (1)"),
+ ):
+ tw._write_source(["assert 0"], [" ", " "])
+
+
+def test_highlight_empty_source() -> None:
+ """Don't crash trying to highlight empty source code.
+
+ Issue #11758.
+ """
+ f = io.StringIO()
+ tw = terminalwriter.TerminalWriter(f)
+ tw.hasmarkup = True
+ tw.code_highlight = True
+ tw._write_source([])
+
+ assert f.getvalue() == ""
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_wcwidth.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_wcwidth.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ff1ad06e6029b4b887a9d1d508e8ecd68969516
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_wcwidth.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+from _pytest._io.wcwidth import wcswidth
+from _pytest._io.wcwidth import wcwidth
+import pytest
+
+
+@pytest.mark.parametrize(
+ ("c", "expected"),
+ [
+ ("\0", 0),
+ ("\n", -1),
+ ("a", 1),
+ ("1", 1),
+ ("א", 1),
+ ("\u200b", 0),
+ ("\u1abe", 0),
+ ("\u0591", 0),
+ ("🉐", 2),
+ ("$", 2), # noqa: RUF001
+ ],
+)
+def test_wcwidth(c: str, expected: int) -> None:
+ assert wcwidth(c) == expected
+
+
+@pytest.mark.parametrize(
+ ("s", "expected"),
+ [
+ ("", 0),
+ ("hello, world!", 13),
+ ("hello, world!\n", -1),
+ ("0123456789", 10),
+ ("שלום, עולם!", 11),
+ ("שְבֻעָיים", 6),
+ ("🉐🉐🉐", 6),
+ ],
+)
+def test_wcswidth(s: str, expected: int) -> None:
+ assert wcswidth(s) == expected
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_fixture.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_fixture.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f94cb8508a9156dcbb50f49b809fb254410f4ba
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_fixture.py
@@ -0,0 +1,483 @@
+# mypy: disable-error-code="attr-defined"
+# mypy: disallow-untyped-defs
+from __future__ import annotations
+
+from collections.abc import Iterator
+import logging
+
+from _pytest.logging import caplog_records_key
+from _pytest.pytester import Pytester
+import pytest
+
+
+logger = logging.getLogger(__name__)
+sublogger = logging.getLogger(__name__ + ".baz")
+
+
+@pytest.fixture(autouse=True)
+def cleanup_disabled_logging() -> Iterator[None]:
+ """Simple fixture that ensures that a test doesn't disable logging.
+
+ This is necessary because ``logging.disable()`` is global, so a test disabling logging
+ and not cleaning up after will break every test that runs after it.
+
+ This behavior was moved to a fixture so that logging will be un-disabled even if the test fails an assertion.
+ """
+ yield
+ logging.disable(logging.NOTSET)
+
+
+def test_fixture_help(pytester: Pytester) -> None:
+ result = pytester.runpytest("--fixtures")
+ result.stdout.fnmatch_lines(["*caplog*"])
+
+
+def test_change_level(caplog: pytest.LogCaptureFixture) -> None:
+ caplog.set_level(logging.INFO)
+ logger.debug("handler DEBUG level")
+ logger.info("handler INFO level")
+
+ caplog.set_level(logging.CRITICAL, logger=sublogger.name)
+ sublogger.warning("logger WARNING level")
+ sublogger.critical("logger CRITICAL level")
+
+ assert "DEBUG" not in caplog.text
+ assert "INFO" in caplog.text
+ assert "WARNING" not in caplog.text
+ assert "CRITICAL" in caplog.text
+
+
+def test_change_level_logging_disabled(caplog: pytest.LogCaptureFixture) -> None:
+ logging.disable(logging.CRITICAL)
+ assert logging.root.manager.disable == logging.CRITICAL
+ caplog.set_level(logging.WARNING)
+ logger.info("handler INFO level")
+ logger.warning("handler WARNING level")
+
+ caplog.set_level(logging.CRITICAL, logger=sublogger.name)
+ sublogger.warning("logger SUB_WARNING level")
+ sublogger.critical("logger SUB_CRITICAL level")
+
+ assert "INFO" not in caplog.text
+ assert "WARNING" in caplog.text
+ assert "SUB_WARNING" not in caplog.text
+ assert "SUB_CRITICAL" in caplog.text
+
+
+def test_change_level_undo(pytester: Pytester) -> None:
+ """Ensure that 'set_level' is undone after the end of the test.
+
+ Tests the logging output themselves (affected both by logger and handler levels).
+ """
+ pytester.makepyfile(
+ """
+ import logging
+
+ def test1(caplog):
+ caplog.set_level(logging.INFO)
+ # using + operator here so fnmatch_lines doesn't match the code in the traceback
+ logging.info('log from ' + 'test1')
+ assert 0
+
+ def test2(caplog):
+ # using + operator here so fnmatch_lines doesn't match the code in the traceback
+ logging.info('log from ' + 'test2')
+ assert 0
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"])
+ result.stdout.no_fnmatch_line("*log from test2*")
+
+
+def test_change_disabled_level_undo(pytester: Pytester) -> None:
+ """Ensure that '_force_enable_logging' in 'set_level' is undone after the end of the test.
+
+ Tests the logging output themselves (affected by disabled logging level).
+ """
+ pytester.makepyfile(
+ """
+ import logging
+
+ def test1(caplog):
+ logging.disable(logging.CRITICAL)
+ caplog.set_level(logging.INFO)
+ # using + operator here so fnmatch_lines doesn't match the code in the traceback
+ logging.info('log from ' + 'test1')
+ assert 0
+
+ def test2(caplog):
+ # using + operator here so fnmatch_lines doesn't match the code in the traceback
+ # use logging.warning because we need a level that will show up if logging.disabled
+ # isn't reset to ``CRITICAL`` after test1.
+ logging.warning('log from ' + 'test2')
+ assert 0
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"])
+ result.stdout.no_fnmatch_line("*log from test2*")
+
+
+def test_change_level_undoes_handler_level(pytester: Pytester) -> None:
+ """Ensure that 'set_level' is undone after the end of the test (handler).
+
+ Issue #7569. Tests the handler level specifically.
+ """
+ pytester.makepyfile(
+ """
+ import logging
+
+ def test1(caplog):
+ assert caplog.handler.level == 0
+ caplog.set_level(9999)
+ caplog.set_level(41)
+ assert caplog.handler.level == 41
+
+ def test2(caplog):
+ assert caplog.handler.level == 0
+
+ def test3(caplog):
+ assert caplog.handler.level == 0
+ caplog.set_level(43)
+ assert caplog.handler.level == 43
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=3)
+
+
+def test_with_statement_at_level(caplog: pytest.LogCaptureFixture) -> None:
+ with caplog.at_level(logging.INFO):
+ logger.debug("handler DEBUG level")
+ logger.info("handler INFO level")
+
+ with caplog.at_level(logging.CRITICAL, logger=sublogger.name):
+ sublogger.warning("logger WARNING level")
+ sublogger.critical("logger CRITICAL level")
+
+ assert "DEBUG" not in caplog.text
+ assert "INFO" in caplog.text
+ assert "WARNING" not in caplog.text
+ assert "CRITICAL" in caplog.text
+
+
+def test_with_statement_at_level_logging_disabled(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ logging.disable(logging.CRITICAL)
+ assert logging.root.manager.disable == logging.CRITICAL
+ with caplog.at_level(logging.WARNING):
+ logger.debug("handler DEBUG level")
+ logger.info("handler INFO level")
+ logger.warning("handler WARNING level")
+ logger.error("handler ERROR level")
+ logger.critical("handler CRITICAL level")
+
+ assert logging.root.manager.disable == logging.INFO
+
+ with caplog.at_level(logging.CRITICAL, logger=sublogger.name):
+ sublogger.warning("logger SUB_WARNING level")
+ sublogger.critical("logger SUB_CRITICAL level")
+
+ assert "DEBUG" not in caplog.text
+ assert "INFO" not in caplog.text
+ assert "WARNING" in caplog.text
+ assert "ERROR" in caplog.text
+ assert " CRITICAL" in caplog.text
+ assert "SUB_WARNING" not in caplog.text
+ assert "SUB_CRITICAL" in caplog.text
+ assert logging.root.manager.disable == logging.CRITICAL
+
+
+def test_with_statement_filtering(caplog: pytest.LogCaptureFixture) -> None:
+ class TestFilter(logging.Filter):
+ def filter(self, record: logging.LogRecord) -> bool:
+ record.msg = "filtered handler call"
+ return True
+
+ with caplog.at_level(logging.INFO):
+ with caplog.filtering(TestFilter()):
+ logger.info("handler call")
+ logger.info("handler call")
+
+ filtered_tuple, unfiltered_tuple = caplog.record_tuples
+ assert filtered_tuple == ("test_fixture", 20, "filtered handler call")
+ assert unfiltered_tuple == ("test_fixture", 20, "handler call")
+
+
+@pytest.mark.parametrize(
+ "level_str,expected_disable_level",
+ [
+ ("CRITICAL", logging.ERROR),
+ ("ERROR", logging.WARNING),
+ ("WARNING", logging.INFO),
+ ("INFO", logging.DEBUG),
+ ("DEBUG", logging.NOTSET),
+ ("NOTSET", logging.NOTSET),
+ ("NOTVALIDLEVEL", logging.NOTSET),
+ ],
+)
+def test_force_enable_logging_level_string(
+ caplog: pytest.LogCaptureFixture, level_str: str, expected_disable_level: int
+) -> None:
+ """Test _force_enable_logging using a level string.
+
+ ``expected_disable_level`` is one level below ``level_str`` because the disabled log level
+ always needs to be *at least* one level lower than the level that caplog is trying to capture.
+ """
+ test_logger = logging.getLogger("test_str_level_force_enable")
+ # Emulate a testing environment where all logging is disabled.
+ logging.disable(logging.CRITICAL)
+ # Make sure all logging is disabled.
+ assert not test_logger.isEnabledFor(logging.CRITICAL)
+ # Un-disable logging for `level_str`.
+ caplog._force_enable_logging(level_str, test_logger)
+ # Make sure that the disabled level is now one below the requested logging level.
+ # We don't use `isEnabledFor` here because that also checks the level set by
+ # `logging.setLevel()` which is irrelevant to `logging.disable()`.
+ assert test_logger.manager.disable == expected_disable_level
+
+
+def test_log_access(caplog: pytest.LogCaptureFixture) -> None:
+ caplog.set_level(logging.INFO)
+ logger.info("boo %s", "arg")
+ assert caplog.records[0].levelname == "INFO"
+ assert caplog.records[0].msg == "boo %s"
+ assert "boo arg" in caplog.text
+
+
+def test_messages(caplog: pytest.LogCaptureFixture) -> None:
+ caplog.set_level(logging.INFO)
+ logger.info("boo %s", "arg")
+ logger.info("bar %s\nbaz %s", "arg1", "arg2")
+ assert "boo arg" == caplog.messages[0]
+ assert "bar arg1\nbaz arg2" == caplog.messages[1]
+ assert caplog.text.count("\n") > len(caplog.messages)
+ assert len(caplog.text.splitlines()) > len(caplog.messages)
+
+ try:
+ raise Exception("test")
+ except Exception:
+ logger.exception("oops")
+
+ assert "oops" in caplog.text
+ assert "oops" in caplog.messages[-1]
+ # Tracebacks are stored in the record and not added until the formatter or handler.
+ assert "Exception" in caplog.text
+ assert "Exception" not in caplog.messages[-1]
+
+
+def test_record_tuples(caplog: pytest.LogCaptureFixture) -> None:
+ caplog.set_level(logging.INFO)
+ logger.info("boo %s", "arg")
+
+ assert caplog.record_tuples == [(__name__, logging.INFO, "boo arg")]
+
+
+def test_unicode(caplog: pytest.LogCaptureFixture) -> None:
+ caplog.set_level(logging.INFO)
+ logger.info("bū")
+ assert caplog.records[0].levelname == "INFO"
+ assert caplog.records[0].msg == "bū"
+ assert "bū" in caplog.text
+
+
+def test_clear(caplog: pytest.LogCaptureFixture) -> None:
+ caplog.set_level(logging.INFO)
+ logger.info("bū")
+ assert len(caplog.records)
+ assert caplog.text
+ caplog.clear()
+ assert not len(caplog.records)
+ assert not caplog.text
+
+
+@pytest.fixture
+def logging_during_setup_and_teardown(
+ caplog: pytest.LogCaptureFixture,
+) -> Iterator[None]:
+ caplog.set_level("INFO")
+ logger.info("a_setup_log")
+ yield
+ logger.info("a_teardown_log")
+ assert [x.message for x in caplog.get_records("teardown")] == ["a_teardown_log"]
+
+
+def private_assert_caplog_records_is_setup_call(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # This reaches into private API, don't use this type of thing in real tests!
+ caplog_records = caplog._item.stash[caplog_records_key]
+ assert set(caplog_records) == {"setup", "call"}
+
+
+def test_captures_for_all_stages(
+ caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None
+) -> None:
+ assert not caplog.records
+ assert not caplog.get_records("call")
+ logger.info("a_call_log")
+ assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
+
+ assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
+
+ private_assert_caplog_records_is_setup_call(caplog)
+
+
+def test_clear_for_call_stage(
+ caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None
+) -> None:
+ logger.info("a_call_log")
+ assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
+ assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
+ private_assert_caplog_records_is_setup_call(caplog)
+
+ caplog.clear()
+
+ assert caplog.get_records("call") == []
+ assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
+ private_assert_caplog_records_is_setup_call(caplog)
+
+ logging.info("a_call_log_after_clear")
+ assert [x.message for x in caplog.get_records("call")] == ["a_call_log_after_clear"]
+ assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
+ private_assert_caplog_records_is_setup_call(caplog)
+
+
+def test_ini_controls_global_log_level(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_level_override(request, caplog):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_level == logging.ERROR
+ logger = logging.getLogger('catchlog')
+ logger.warning("WARNING message won't be shown")
+ logger.error("ERROR message will be shown")
+ assert 'WARNING' not in caplog.text
+ assert 'ERROR' in caplog.text
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_level=ERROR
+ """
+ )
+
+ result = pytester.runpytest()
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+
+
+def test_can_override_global_log_level(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_level_override(request, caplog):
+ logger = logging.getLogger('catchlog')
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_level == logging.WARNING
+
+ logger.info("INFO message won't be shown")
+
+ caplog.set_level(logging.INFO, logger.name)
+
+ with caplog.at_level(logging.DEBUG, logger.name):
+ logger.debug("DEBUG message will be shown")
+
+ logger.debug("DEBUG message won't be shown")
+
+ with caplog.at_level(logging.CRITICAL, logger.name):
+ logger.warning("WARNING message won't be shown")
+
+ logger.debug("DEBUG message won't be shown")
+ logger.info("INFO message will be shown")
+
+ assert "message won't be shown" not in caplog.text
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_level=WARNING
+ """
+ )
+
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+
+def test_captures_despite_exception(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_level_override(request, caplog):
+ logger = logging.getLogger('catchlog')
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_level == logging.WARNING
+
+ logger.error("ERROR message " + "will be shown")
+
+ with caplog.at_level(logging.DEBUG, logger.name):
+ logger.debug("DEBUG message " + "won't be shown")
+ raise Exception()
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_level=WARNING
+ """
+ )
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*ERROR message will be shown*"])
+ result.stdout.no_fnmatch_line("*DEBUG message won't be shown*")
+ assert result.ret == 1
+
+
+def test_log_report_captures_according_to_config_option_upon_failure(
+ pytester: Pytester,
+) -> None:
+ """Test that upon failure:
+ (1) `caplog` succeeded to capture the DEBUG message and assert on it => No `Exception` is raised.
+ (2) The `DEBUG` message does NOT appear in the `Captured log call` report.
+ (3) The stdout, `INFO`, and `WARNING` messages DO appear in the test reports due to `--log-level=INFO`.
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+
+ def function_that_logs():
+ logging.debug('DEBUG log ' + 'message')
+ logging.info('INFO log ' + 'message')
+ logging.warning('WARNING log ' + 'message')
+ print('Print ' + 'message')
+
+ def test_that_fails(request, caplog):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_level == logging.INFO
+
+ with caplog.at_level(logging.DEBUG):
+ function_that_logs()
+
+ if 'DEBUG log ' + 'message' not in caplog.text:
+ raise Exception('caplog failed to ' + 'capture DEBUG')
+
+ assert False
+ """
+ )
+
+ result = pytester.runpytest("--log-level=INFO")
+ result.stdout.no_fnmatch_line("*Exception: caplog failed to capture DEBUG*")
+ result.stdout.no_fnmatch_line("*DEBUG log message*")
+ result.stdout.fnmatch_lines(
+ ["*Print message*", "*INFO log message*", "*WARNING log message*"]
+ )
+ assert result.ret == 1
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_formatter.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_formatter.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfe3bee68c4e0f92796ae75621c2656576b7e508
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_formatter.py
@@ -0,0 +1,175 @@
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from _pytest._io import TerminalWriter
+from _pytest.logging import ColoredLevelFormatter
+
+
+def test_coloredlogformatter() -> None:
+ logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"
+
+ record = logging.LogRecord(
+ name="dummy",
+ level=logging.INFO,
+ pathname="dummypath",
+ lineno=10,
+ msg="Test Message",
+ args=(),
+ exc_info=None,
+ )
+
+ tw = TerminalWriter()
+ tw.hasmarkup = True
+ formatter = ColoredLevelFormatter(tw, logfmt)
+ output = formatter.format(record)
+ assert output == (
+ "dummypath 10 \x1b[32mINFO \x1b[0m Test Message"
+ )
+
+ tw.hasmarkup = False
+ formatter = ColoredLevelFormatter(tw, logfmt)
+ output = formatter.format(record)
+ assert output == ("dummypath 10 INFO Test Message")
+
+
+def test_coloredlogformatter_with_width_precision() -> None:
+ logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8.8s %(message)s"
+
+ record = logging.LogRecord(
+ name="dummy",
+ level=logging.INFO,
+ pathname="dummypath",
+ lineno=10,
+ msg="Test Message",
+ args=(),
+ exc_info=None,
+ )
+
+ tw = TerminalWriter()
+ tw.hasmarkup = True
+ formatter = ColoredLevelFormatter(tw, logfmt)
+ output = formatter.format(record)
+ assert output == (
+ "dummypath 10 \x1b[32mINFO \x1b[0m Test Message"
+ )
+
+ tw.hasmarkup = False
+ formatter = ColoredLevelFormatter(tw, logfmt)
+ output = formatter.format(record)
+ assert output == ("dummypath 10 INFO Test Message")
+
+
+def test_multiline_message() -> None:
+ from _pytest.logging import PercentStyleMultiline
+
+ logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"
+
+ record: Any = logging.LogRecord(
+ name="dummy",
+ level=logging.INFO,
+ pathname="dummypath",
+ lineno=10,
+ msg="Test Message line1\nline2",
+ args=(),
+ exc_info=None,
+ )
+ # this is called by logging.Formatter.format
+ record.message = record.getMessage()
+
+ ai_on_style = PercentStyleMultiline(logfmt, True)
+ output = ai_on_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\n"
+ " line2"
+ )
+
+ ai_off_style = PercentStyleMultiline(logfmt, False)
+ output = ai_off_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\nline2"
+ )
+
+ ai_none_style = PercentStyleMultiline(logfmt, None)
+ output = ai_none_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\nline2"
+ )
+
+ record.auto_indent = False
+ output = ai_on_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\nline2"
+ )
+
+ record.auto_indent = True
+ output = ai_off_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\n"
+ " line2"
+ )
+
+ record.auto_indent = "False"
+ output = ai_on_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\nline2"
+ )
+
+ record.auto_indent = "True"
+ output = ai_off_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\n"
+ " line2"
+ )
+
+ # bad string values default to False
+ record.auto_indent = "junk"
+ output = ai_off_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\nline2"
+ )
+
+ # anything other than string or int will default to False
+ record.auto_indent = dict()
+ output = ai_off_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\nline2"
+ )
+
+ record.auto_indent = "5"
+ output = ai_off_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\n line2"
+ )
+
+ record.auto_indent = 5
+ output = ai_off_style.format(record)
+ assert output == (
+ "dummypath 10 INFO Test Message line1\n line2"
+ )
+
+
+def test_colored_short_level() -> None:
+ logfmt = "%(levelname).1s %(message)s"
+
+ record = logging.LogRecord(
+ name="dummy",
+ level=logging.INFO,
+ pathname="dummypath",
+ lineno=10,
+ msg="Test Message",
+ args=(),
+ exc_info=None,
+ )
+
+ class ColorConfig:
+ class option:
+ pass
+
+ tw = TerminalWriter()
+ tw.hasmarkup = True
+ formatter = ColoredLevelFormatter(tw, logfmt)
+ output = formatter.format(record)
+ # the I (of INFO) is colored
+ assert output == ("\x1b[32mI\x1b[0m Test Message")
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_reporting.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_reporting.py
new file mode 100644
index 0000000000000000000000000000000000000000..4974532e888be76f4bcf47427cc10346e619ab67
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_reporting.py
@@ -0,0 +1,1549 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import io
+import os
+import re
+from typing import cast
+
+from _pytest.capture import CaptureManager
+from _pytest.config import ExitCode
+from _pytest.fixtures import FixtureRequest
+from _pytest.pytester import Pytester
+from _pytest.terminal import TerminalReporter
+import pytest
+
+
+def test_nothing_logged(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import sys
+
+ def test_foo():
+ sys.stdout.write('text going to stdout')
+ sys.stderr.write('text going to stderr')
+ assert False
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
+ result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
+ with pytest.raises(pytest.fail.Exception):
+ result.stdout.fnmatch_lines(["*- Captured *log call -*"])
+
+
+def test_messages_logged(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import sys
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def test_foo():
+ sys.stdout.write('text going to stdout')
+ sys.stderr.write('text going to stderr')
+ logger.info('text going to logger')
+ assert False
+ """
+ )
+ result = pytester.runpytest("--log-level=INFO")
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*- Captured *log call -*", "*text going to logger*"])
+ result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
+ result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
+
+
+def test_root_logger_affected(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import logging
+ logger = logging.getLogger()
+
+ def test_foo():
+ logger.info('info text ' + 'going to logger')
+ logger.warning('warning text ' + 'going to logger')
+ logger.error('error text ' + 'going to logger')
+
+ assert 0
+ """
+ )
+ log_file = str(pytester.path.joinpath("pytest.log"))
+ result = pytester.runpytest("--log-level=ERROR", "--log-file=pytest.log")
+ assert result.ret == 1
+
+ # The capture log calls in the stdout section only contain the
+ # logger.error msg, because of --log-level=ERROR.
+ result.stdout.fnmatch_lines(["*error text going to logger*"])
+ stdout = result.stdout.str()
+ assert "warning text going to logger" not in stdout
+ assert "info text going to logger" not in stdout
+
+ # The log file should only contain the error log messages and
+ # not the warning or info ones, because the root logger is set to
+ # ERROR using --log-level=ERROR.
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "info text going to logger" not in contents
+ assert "warning text going to logger" not in contents
+ assert "error text going to logger" in contents
+
+
+def test_log_cli_level_log_level_interaction(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import logging
+ logger = logging.getLogger()
+
+ def test_foo():
+ logger.debug('debug text ' + 'going to logger')
+ logger.info('info text ' + 'going to logger')
+ logger.warning('warning text ' + 'going to logger')
+ logger.error('error text ' + 'going to logger')
+ assert 0
+ """
+ )
+
+ result = pytester.runpytest("--log-cli-level=INFO", "--log-level=ERROR")
+ assert result.ret == 1
+
+ result.stdout.fnmatch_lines(
+ [
+ "*-- live log call --*",
+ "*INFO*info text going to logger",
+ "*WARNING*warning text going to logger",
+ "*ERROR*error text going to logger",
+ "=* 1 failed in *=",
+ ]
+ )
+ result.stdout.no_re_match_line("DEBUG")
+
+
+def test_setup_logging(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def setup_function(function):
+ logger.info('text going to logger from setup')
+
+ def test_foo():
+ logger.info('text going to logger from call')
+ assert False
+ """
+ )
+ result = pytester.runpytest("--log-level=INFO")
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(
+ [
+ "*- Captured *log setup -*",
+ "*text going to logger from setup*",
+ "*- Captured *log call -*",
+ "*text going to logger from call*",
+ ]
+ )
+
+
+def test_teardown_logging(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def test_foo():
+ logger.info('text going to logger from call')
+
+ def teardown_function(function):
+ logger.info('text going to logger from teardown')
+ assert False
+ """
+ )
+ result = pytester.runpytest("--log-level=INFO")
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(
+ [
+ "*- Captured *log call -*",
+ "*text going to logger from call*",
+ "*- Captured *log teardown -*",
+ "*text going to logger from teardown*",
+ ]
+ )
+
+
+@pytest.mark.parametrize("enabled", [True, False])
+def test_log_cli_enabled_disabled(pytester: Pytester, enabled: bool) -> None:
+ msg = "critical message logged by test"
+ pytester.makepyfile(
+ f"""
+ import logging
+ def test_log_cli():
+ logging.critical("{msg}")
+ """
+ )
+ if enabled:
+ pytester.makeini(
+ """
+ [pytest]
+ log_cli=true
+ """
+ )
+ result = pytester.runpytest()
+ if enabled:
+ result.stdout.fnmatch_lines(
+ [
+ "test_log_cli_enabled_disabled.py::test_log_cli ",
+ "*-- live log call --*",
+ "CRITICAL *test_log_cli_enabled_disabled.py* critical message logged by test",
+ "PASSED*",
+ ]
+ )
+ else:
+ assert msg not in result.stdout.str()
+
+
+def test_log_cli_default_level(pytester: Pytester) -> None:
+ # Default log file level
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_cli(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_cli_handler.level == logging.NOTSET
+ logging.getLogger('catchlog').info("INFO message won't be shown")
+ logging.getLogger('catchlog').warning("WARNING message will be shown")
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_cli=true
+ """
+ )
+
+ result = pytester.runpytest()
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(
+ [
+ "test_log_cli_default_level.py::test_log_cli ",
+ "WARNING*test_log_cli_default_level.py* message will be shown*",
+ ]
+ )
+ result.stdout.no_fnmatch_line("*INFO message won't be shown*")
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+
+
+def test_log_cli_default_level_multiple_tests(
+ pytester: Pytester, request: FixtureRequest
+) -> None:
+ """Ensure we reset the first newline added by the live logger between tests"""
+ filename = request.node.name + ".py"
+ pytester.makepyfile(
+ """
+ import logging
+
+ def test_log_1():
+ logging.warning("log message from test_log_1")
+
+ def test_log_2():
+ logging.warning("log message from test_log_2")
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_cli=true
+ """
+ )
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ f"{filename}::test_log_1 ",
+ "*WARNING*log message from test_log_1*",
+ "PASSED *50%*",
+ f"{filename}::test_log_2 ",
+ "*WARNING*log message from test_log_2*",
+ "PASSED *100%*",
+ "=* 2 passed in *=",
+ ]
+ )
+
+
+def test_log_cli_default_level_sections(
+ pytester: Pytester, request: FixtureRequest
+) -> None:
+ """Check that with live logging enable we are printing the correct headers during
+ start/setup/call/teardown/finish."""
+ filename = request.node.name + ".py"
+ pytester.makeconftest(
+ """
+ import pytest
+ import logging
+
+ def pytest_runtest_logstart():
+ logging.warning('>>>>> START >>>>>')
+
+ def pytest_runtest_logfinish():
+ logging.warning('<<<<< END <<<<<<<')
+ """
+ )
+
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+
+ @pytest.fixture
+ def fix(request):
+ logging.warning("log message from setup of {}".format(request.node.name))
+ yield
+ logging.warning("log message from teardown of {}".format(request.node.name))
+
+ def test_log_1(fix):
+ logging.warning("log message from test_log_1")
+
+ def test_log_2(fix):
+ logging.warning("log message from test_log_2")
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_cli=true
+ """
+ )
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ f"{filename}::test_log_1 ",
+ "*-- live log start --*",
+ "*WARNING* >>>>> START >>>>>*",
+ "*-- live log setup --*",
+ "*WARNING*log message from setup of test_log_1*",
+ "*-- live log call --*",
+ "*WARNING*log message from test_log_1*",
+ "PASSED *50%*",
+ "*-- live log teardown --*",
+ "*WARNING*log message from teardown of test_log_1*",
+ "*-- live log finish --*",
+ "*WARNING* <<<<< END <<<<<<<*",
+ f"{filename}::test_log_2 ",
+ "*-- live log start --*",
+ "*WARNING* >>>>> START >>>>>*",
+ "*-- live log setup --*",
+ "*WARNING*log message from setup of test_log_2*",
+ "*-- live log call --*",
+ "*WARNING*log message from test_log_2*",
+ "PASSED *100%*",
+ "*-- live log teardown --*",
+ "*WARNING*log message from teardown of test_log_2*",
+ "*-- live log finish --*",
+ "*WARNING* <<<<< END <<<<<<<*",
+ "=* 2 passed in *=",
+ ]
+ )
+
+
+def test_live_logs_unknown_sections(
+ pytester: Pytester, request: FixtureRequest
+) -> None:
+ """Check that with live logging enable we are printing the correct headers during
+ start/setup/call/teardown/finish."""
+ filename = request.node.name + ".py"
+ pytester.makeconftest(
+ """
+ import pytest
+ import logging
+
+ def pytest_runtest_protocol(item, nextitem):
+ logging.warning('Unknown Section!')
+
+ def pytest_runtest_logstart():
+ logging.warning('>>>>> START >>>>>')
+
+ def pytest_runtest_logfinish():
+ logging.warning('<<<<< END <<<<<<<')
+ """
+ )
+
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+
+ @pytest.fixture
+ def fix(request):
+ logging.warning("log message from setup of {}".format(request.node.name))
+ yield
+ logging.warning("log message from teardown of {}".format(request.node.name))
+
+ def test_log_1(fix):
+ logging.warning("log message from test_log_1")
+
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_cli=true
+ """
+ )
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*WARNING*Unknown Section*",
+ f"{filename}::test_log_1 ",
+ "*WARNING* >>>>> START >>>>>*",
+ "*-- live log setup --*",
+ "*WARNING*log message from setup of test_log_1*",
+ "*-- live log call --*",
+ "*WARNING*log message from test_log_1*",
+ "PASSED *100%*",
+ "*-- live log teardown --*",
+ "*WARNING*log message from teardown of test_log_1*",
+ "*WARNING* <<<<< END <<<<<<<*",
+ "=* 1 passed in *=",
+ ]
+ )
+
+
+def test_sections_single_new_line_after_test_outcome(
+ pytester: Pytester, request: FixtureRequest
+) -> None:
+ """Check that only a single new line is written between log messages during
+ teardown/finish."""
+ filename = request.node.name + ".py"
+ pytester.makeconftest(
+ """
+ import pytest
+ import logging
+
+ def pytest_runtest_logstart():
+ logging.warning('>>>>> START >>>>>')
+
+ def pytest_runtest_logfinish():
+ logging.warning('<<<<< END <<<<<<<')
+ logging.warning('<<<<< END <<<<<<<')
+ """
+ )
+
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+
+ @pytest.fixture
+ def fix(request):
+ logging.warning("log message from setup of {}".format(request.node.name))
+ yield
+ logging.warning("log message from teardown of {}".format(request.node.name))
+ logging.warning("log message from teardown of {}".format(request.node.name))
+
+ def test_log_1(fix):
+ logging.warning("log message from test_log_1")
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_cli=true
+ """
+ )
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ f"{filename}::test_log_1 ",
+ "*-- live log start --*",
+ "*WARNING* >>>>> START >>>>>*",
+ "*-- live log setup --*",
+ "*WARNING*log message from setup of test_log_1*",
+ "*-- live log call --*",
+ "*WARNING*log message from test_log_1*",
+ "PASSED *100%*",
+ "*-- live log teardown --*",
+ "*WARNING*log message from teardown of test_log_1*",
+ "*-- live log finish --*",
+ "*WARNING* <<<<< END <<<<<<<*",
+ "*WARNING* <<<<< END <<<<<<<*",
+ "=* 1 passed in *=",
+ ]
+ )
+ assert (
+ re.search(
+ r"(.+)live log teardown(.+)\nWARNING(.+)\nWARNING(.+)",
+ result.stdout.str(),
+ re.MULTILINE,
+ )
+ is not None
+ )
+ assert (
+ re.search(
+ r"(.+)live log finish(.+)\nWARNING(.+)\nWARNING(.+)",
+ result.stdout.str(),
+ re.MULTILINE,
+ )
+ is not None
+ )
+
+
+def test_log_cli_level(pytester: Pytester) -> None:
+ # Default log file level
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_cli(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_cli_handler.level == logging.INFO
+ logging.getLogger('catchlog').debug("This log message won't be shown")
+ logging.getLogger('catchlog').info("This log message will be shown")
+ print('PASSED')
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_cli=true
+ """
+ )
+
+ result = pytester.runpytest("-s", "--log-cli-level=INFO")
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(
+ [
+ "*test_log_cli_level.py*This log message will be shown",
+ "PASSED", # 'PASSED' on its own line because the log message prints a new line
+ ]
+ )
+ result.stdout.no_fnmatch_line("*This log message won't be shown*")
+
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+
+ result = pytester.runpytest("-s", "--log-level=INFO")
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(
+ [
+ "*test_log_cli_level.py* This log message will be shown",
+ "PASSED", # 'PASSED' on its own line because the log message prints a new line
+ ]
+ )
+ result.stdout.no_fnmatch_line("*This log message won't be shown*")
+
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+
+
+def test_log_cli_ini_level(pytester: Pytester) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ log_cli=true
+ log_cli_level = INFO
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_cli(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_cli_handler.level == logging.INFO
+ logging.getLogger('catchlog').debug("This log message won't be shown")
+ logging.getLogger('catchlog').info("This log message will be shown")
+ print('PASSED')
+ """
+ )
+
+ result = pytester.runpytest("-s")
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(
+ [
+ "*test_log_cli_ini_level.py* This log message will be shown",
+ "PASSED", # 'PASSED' on its own line because the log message prints a new line
+ ]
+ )
+ result.stdout.no_fnmatch_line("*This log message won't be shown*")
+
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+
+
+@pytest.mark.parametrize(
+ "cli_args",
+ ["", "--log-level=WARNING", "--log-file-level=WARNING", "--log-cli-level=WARNING"],
+)
+def test_log_cli_auto_enable(pytester: Pytester, cli_args: str) -> None:
+ """Check that live logs are enabled if --log-level or --log-cli-level is passed on the CLI.
+
+ It should not be auto enabled if the same configs are set on the configuration file.
+ """
+ pytester.makepyfile(
+ """
+ import logging
+
+ def test_log_1():
+ logging.info("log message from test_log_1 not to be shown")
+ logging.warning("log message from test_log_1")
+
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_level=INFO
+ log_cli_level=INFO
+ """
+ )
+
+ result = pytester.runpytest(cli_args)
+ stdout = result.stdout.str()
+ if cli_args == "--log-cli-level=WARNING":
+ result.stdout.fnmatch_lines(
+ [
+ "*::test_log_1 ",
+ "*-- live log call --*",
+ "*WARNING*log message from test_log_1*",
+ "PASSED *100%*",
+ "=* 1 passed in *=",
+ ]
+ )
+ assert "INFO" not in stdout
+ else:
+ result.stdout.fnmatch_lines(
+ ["*test_log_cli_auto_enable*100%*", "=* 1 passed in *="]
+ )
+ assert "INFO" not in stdout
+ assert "WARNING" not in stdout
+
+
+def test_log_file_cli(pytester: Pytester) -> None:
+ # Default log file level
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_file(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_file_handler.level == logging.WARNING
+ logging.getLogger('catchlog').info("This log message won't be shown")
+ logging.getLogger('catchlog').warning("This log message will be shown")
+ print('PASSED')
+ """
+ )
+
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ result = pytester.runpytest(
+ "-s", f"--log-file={log_file}", "--log-file-level=WARNING"
+ )
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(["test_log_file_cli.py PASSED"])
+
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "This log message will be shown" in contents
+ assert "This log message won't be shown" not in contents
+
+
+def test_log_file_mode_cli(pytester: Pytester) -> None:
+ # Default log file level
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_file(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_file_handler.level == logging.WARNING
+ logging.getLogger('catchlog').info("This log message won't be shown")
+ logging.getLogger('catchlog').warning("This log message will be shown")
+ print('PASSED')
+ """
+ )
+
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ with open(log_file, mode="w", encoding="utf-8") as wfh:
+ wfh.write("A custom header\n")
+
+ result = pytester.runpytest(
+ "-s",
+ f"--log-file={log_file}",
+ "--log-file-mode=a",
+ "--log-file-level=WARNING",
+ )
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(["test_log_file_mode_cli.py PASSED"])
+
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "A custom header" in contents
+ assert "This log message will be shown" in contents
+ assert "This log message won't be shown" not in contents
+
+
+def test_log_file_mode_cli_invalid(pytester: Pytester) -> None:
+ # Default log file level
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_file(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_file_handler.level == logging.WARNING
+ logging.getLogger('catchlog').info("This log message won't be shown")
+ logging.getLogger('catchlog').warning("This log message will be shown")
+ """
+ )
+
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ result = pytester.runpytest(
+ "-s",
+ f"--log-file={log_file}",
+ "--log-file-mode=b",
+ "--log-file-level=WARNING",
+ )
+
+ # make sure that we get a '4' exit code for the testsuite
+ assert result.ret == ExitCode.USAGE_ERROR
+
+
+def test_log_file_cli_level(pytester: Pytester) -> None:
+ # Default log file level
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_file(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_file_handler.level == logging.INFO
+ logging.getLogger('catchlog').debug("This log message won't be shown")
+ logging.getLogger('catchlog').info("This log message will be shown")
+ print('PASSED')
+ """
+ )
+
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ result = pytester.runpytest("-s", f"--log-file={log_file}", "--log-file-level=INFO")
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(["test_log_file_cli_level.py PASSED"])
+
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "This log message will be shown" in contents
+ assert "This log message won't be shown" not in contents
+
+
+def test_log_level_not_changed_by_default(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import logging
+ def test_log_file():
+ assert logging.getLogger().level == logging.WARNING
+ """
+ )
+ result = pytester.runpytest("-s")
+ result.stdout.fnmatch_lines(["* 1 passed in *"])
+
+
+def test_log_file_ini(pytester: Pytester) -> None:
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ pytester.makeini(
+ f"""
+ [pytest]
+ log_file={log_file}
+ log_file_level=WARNING
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_file(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_file_handler.level == logging.WARNING
+ logging.getLogger('catchlog').info("This log message won't be shown")
+ logging.getLogger('catchlog').warning("This log message will be shown")
+ print('PASSED')
+ """
+ )
+
+ result = pytester.runpytest("-s")
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(["test_log_file_ini.py PASSED"])
+
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "This log message will be shown" in contents
+ assert "This log message won't be shown" not in contents
+
+
+def test_log_file_mode_ini(pytester: Pytester) -> None:
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ pytester.makeini(
+ f"""
+ [pytest]
+ log_file={log_file}
+ log_file_mode=a
+ log_file_level=WARNING
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_file(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_file_handler.level == logging.WARNING
+ logging.getLogger('catchlog').info("This log message won't be shown")
+ logging.getLogger('catchlog').warning("This log message will be shown")
+ print('PASSED')
+ """
+ )
+
+ with open(log_file, mode="w", encoding="utf-8") as wfh:
+ wfh.write("A custom header\n")
+
+ result = pytester.runpytest("-s")
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(["test_log_file_mode_ini.py PASSED"])
+
+ assert result.ret == ExitCode.OK
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "A custom header" in contents
+ assert "This log message will be shown" in contents
+ assert "This log message won't be shown" not in contents
+
+
+def test_log_file_ini_level(pytester: Pytester) -> None:
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ pytester.makeini(
+ f"""
+ [pytest]
+ log_file={log_file}
+ log_file_level = INFO
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+ import logging
+ def test_log_file(request):
+ plugin = request.config.pluginmanager.getplugin('logging-plugin')
+ assert plugin.log_file_handler.level == logging.INFO
+ logging.getLogger('catchlog').debug("This log message won't be shown")
+ logging.getLogger('catchlog').info("This log message will be shown")
+ print('PASSED')
+ """
+ )
+
+ result = pytester.runpytest("-s")
+
+ # fnmatch_lines does an assertion internally
+ result.stdout.fnmatch_lines(["test_log_file_ini_level.py PASSED"])
+
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "This log message will be shown" in contents
+ assert "This log message won't be shown" not in contents
+
+
+def test_log_file_unicode(pytester: Pytester) -> None:
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ pytester.makeini(
+ f"""
+ [pytest]
+ log_file={log_file}
+ log_file_level = INFO
+ """
+ )
+ pytester.makepyfile(
+ """\
+ import logging
+
+ def test_log_file():
+ logging.getLogger('catchlog').info("Normal message")
+ logging.getLogger('catchlog').info("├")
+ logging.getLogger('catchlog').info("Another normal message")
+ """
+ )
+
+ result = pytester.runpytest()
+
+ # make sure that we get a '0' exit code for the testsuite
+ assert result.ret == 0
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "Normal message" in contents
+ assert "├" in contents
+ assert "Another normal message" in contents
+
+
+@pytest.mark.parametrize("has_capture_manager", [True, False])
+def test_live_logging_suspends_capture(
+ has_capture_manager: bool, request: FixtureRequest
+) -> None:
+ """Test that capture manager is suspended when we emitting messages for live logging.
+
+ This tests the implementation calls instead of behavior because it is difficult/impossible to do it using
+ ``pytester`` facilities because they do their own capturing.
+
+ We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin
+ is installed.
+ """
+ import contextlib
+ from functools import partial
+ import logging
+
+ from _pytest.logging import _LiveLoggingStreamHandler
+
+ class MockCaptureManager:
+ calls = []
+
+ @contextlib.contextmanager
+ def global_and_fixture_disabled(self):
+ self.calls.append("enter disabled")
+ yield
+ self.calls.append("exit disabled")
+
+ class DummyTerminal(io.StringIO):
+ def section(self, *args, **kwargs):
+ pass
+
+ out_file = cast(TerminalReporter, DummyTerminal())
+ capture_manager = (
+ cast(CaptureManager, MockCaptureManager()) if has_capture_manager else None
+ )
+ handler = _LiveLoggingStreamHandler(out_file, capture_manager)
+ handler.set_when("call")
+
+ logger = logging.getLogger(__name__ + ".test_live_logging_suspends_capture")
+ logger.addHandler(handler)
+ request.addfinalizer(partial(logger.removeHandler, handler))
+
+ logger.critical("some message")
+ if has_capture_manager:
+ assert MockCaptureManager.calls == ["enter disabled", "exit disabled"]
+ else:
+ assert MockCaptureManager.calls == []
+ assert cast(io.StringIO, out_file).getvalue() == "\nsome message\n"
+
+
+def test_collection_live_logging(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import logging
+
+ logging.getLogger().info("Normal message")
+ """
+ )
+
+ result = pytester.runpytest("--log-cli-level=INFO")
+ result.stdout.fnmatch_lines(
+ ["*--- live log collection ---*", "*Normal message*", "collected 0 items"]
+ )
+
+
+@pytest.mark.parametrize("verbose", ["", "-q", "-qq"])
+def test_collection_collect_only_live_logging(pytester: Pytester, verbose: str) -> None:
+ pytester.makepyfile(
+ """
+ def test_simple():
+ pass
+ """
+ )
+
+ result = pytester.runpytest("--collect-only", "--log-cli-level=INFO", verbose)
+
+ expected_lines = []
+
+ if not verbose:
+ expected_lines.extend(
+ [
+ "*collected 1 item*",
+ "**",
+ "*1 test collected*",
+ ]
+ )
+ elif verbose == "-q":
+ result.stdout.no_fnmatch_line("*collected 1 item**")
+ expected_lines.extend(
+ [
+ "*test_collection_collect_only_live_logging.py::test_simple*",
+ "1 test collected in [0-9].[0-9][0-9]s",
+ ]
+ )
+ elif verbose == "-qq":
+ result.stdout.no_fnmatch_line("*collected 1 item**")
+ expected_lines.extend(["*test_collection_collect_only_live_logging.py: 1*"])
+
+ result.stdout.fnmatch_lines(expected_lines)
+
+
+def test_collection_logging_to_file(pytester: Pytester) -> None:
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ pytester.makeini(
+ f"""
+ [pytest]
+ log_file={log_file}
+ log_file_level = INFO
+ """
+ )
+
+ pytester.makepyfile(
+ """
+ import logging
+
+ logging.getLogger().info("Normal message")
+
+ def test_simple():
+ logging.getLogger().debug("debug message in test_simple")
+ logging.getLogger().info("info message in test_simple")
+ """
+ )
+
+ result = pytester.runpytest()
+
+ result.stdout.no_fnmatch_line("*--- live log collection ---*")
+
+ assert result.ret == 0
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "Normal message" in contents
+ assert "debug message in test_simple" not in contents
+ assert "info message in test_simple" in contents
+
+
+def test_log_in_hooks(pytester: Pytester) -> None:
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ pytester.makeini(
+ f"""
+ [pytest]
+ log_file={log_file}
+ log_file_level = INFO
+ log_cli=true
+ """
+ )
+ pytester.makeconftest(
+ """
+ import logging
+
+ def pytest_runtestloop(session):
+ logging.info('runtestloop')
+
+ def pytest_sessionstart(session):
+ logging.info('sessionstart')
+
+ def pytest_sessionfinish(session, exitstatus):
+ logging.info('sessionfinish')
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*sessionstart*", "*runtestloop*", "*sessionfinish*"])
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert "sessionstart" in contents
+ assert "runtestloop" in contents
+ assert "sessionfinish" in contents
+
+
+def test_log_in_runtest_logreport(pytester: Pytester) -> None:
+ log_file = str(pytester.path.joinpath("pytest.log"))
+
+ pytester.makeini(
+ f"""
+ [pytest]
+ log_file={log_file}
+ log_file_level = INFO
+ log_cli=true
+ """
+ )
+ pytester.makeconftest(
+ """
+ import logging
+ logger = logging.getLogger(__name__)
+
+ def pytest_runtest_logreport(report):
+ logger.info("logreport")
+ """
+ )
+ pytester.makepyfile(
+ """
+ def test_first():
+ assert True
+ """
+ )
+ pytester.runpytest()
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert contents.count("logreport") == 3
+
+
+def test_log_set_path(pytester: Pytester) -> None:
+ report_dir_base = str(pytester.path)
+
+ pytester.makeini(
+ """
+ [pytest]
+ log_file_level = DEBUG
+ log_cli=true
+ """
+ )
+ pytester.makeconftest(
+ f"""
+ import os
+ import pytest
+ @pytest.hookimpl(wrapper=True, tryfirst=True)
+ def pytest_runtest_setup(item):
+ config = item.config
+ logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
+ report_file = os.path.join({report_dir_base!r}, item._request.node.name)
+ logging_plugin.set_log_path(report_file)
+ return (yield)
+ """
+ )
+ pytester.makepyfile(
+ """
+ import logging
+ logger = logging.getLogger("testcase-logger")
+ def test_first():
+ logger.info("message from test 1")
+ assert True
+
+ def test_second():
+ logger.debug("message from test 2")
+ assert True
+ """
+ )
+ pytester.runpytest()
+ with open(os.path.join(report_dir_base, "test_first"), encoding="utf-8") as rfh:
+ content = rfh.read()
+ assert "message from test 1" in content
+
+ with open(os.path.join(report_dir_base, "test_second"), encoding="utf-8") as rfh:
+ content = rfh.read()
+ assert "message from test 2" in content
+
+
+def test_log_set_path_with_log_file_mode(pytester: Pytester) -> None:
+ report_dir_base = str(pytester.path)
+
+ pytester.makeini(
+ """
+ [pytest]
+ log_file_level = DEBUG
+ log_cli=true
+ log_file_mode=a
+ """
+ )
+ pytester.makeconftest(
+ f"""
+ import os
+ import pytest
+ @pytest.hookimpl(wrapper=True, tryfirst=True)
+ def pytest_runtest_setup(item):
+ config = item.config
+ logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
+ report_file = os.path.join({report_dir_base!r}, item._request.node.name)
+ logging_plugin.set_log_path(report_file)
+ return (yield)
+ """
+ )
+ pytester.makepyfile(
+ """
+ import logging
+ logger = logging.getLogger("testcase-logger")
+ def test_first():
+ logger.info("message from test 1")
+ assert True
+
+ def test_second():
+ logger.debug("message from test 2")
+ assert True
+ """
+ )
+
+ test_first_log_file = os.path.join(report_dir_base, "test_first")
+ test_second_log_file = os.path.join(report_dir_base, "test_second")
+ with open(test_first_log_file, mode="w", encoding="utf-8") as wfh:
+ wfh.write("A custom header for test 1\n")
+
+ with open(test_second_log_file, mode="w", encoding="utf-8") as wfh:
+ wfh.write("A custom header for test 2\n")
+
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.OK
+
+ with open(test_first_log_file, encoding="utf-8") as rfh:
+ content = rfh.read()
+ assert "A custom header for test 1" in content
+ assert "message from test 1" in content
+
+ with open(test_second_log_file, encoding="utf-8") as rfh:
+ content = rfh.read()
+ assert "A custom header for test 2" in content
+ assert "message from test 2" in content
+
+
+def test_colored_captured_log(pytester: Pytester) -> None:
+ """Test that the level names of captured log messages of a failing test
+ are colored."""
+ pytester.makepyfile(
+ """
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def test_foo():
+ logger.info('text going to logger from call')
+ assert False
+ """
+ )
+ result = pytester.runpytest("--log-level=INFO", "--color=yes")
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(
+ [
+ "*-- Captured log call --*",
+ "\x1b[32mINFO \x1b[0m*text going to logger from call",
+ ]
+ )
+
+
+def test_colored_ansi_esc_caplogtext(pytester: Pytester) -> None:
+ """Make sure that caplog.text does not contain ANSI escape sequences."""
+ pytester.makepyfile(
+ """
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def test_foo(caplog):
+ logger.info('text going to logger from call')
+ assert '\x1b' not in caplog.text
+ """
+ )
+ result = pytester.runpytest("--log-level=INFO", "--color=yes")
+ assert result.ret == 0
+
+
+def test_logging_emit_error(pytester: Pytester) -> None:
+ """An exception raised during emit() should fail the test.
+
+ The default behavior of logging is to print "Logging error"
+ to stderr with the call stack and some extra details.
+
+ pytest overrides this behavior to propagate the exception.
+ """
+ pytester.makepyfile(
+ """
+ import logging
+
+ def test_bad_log():
+ logging.warning('oops', 'first', 2)
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(failed=1)
+ result.stdout.fnmatch_lines(
+ [
+ "====* FAILURES *====",
+ "*not all arguments converted during string formatting*",
+ ]
+ )
+
+
+def test_logging_emit_error_supressed(pytester: Pytester) -> None:
+ """If logging is configured to silently ignore errors, pytest
+ doesn't propagate errors either."""
+ pytester.makepyfile(
+ """
+ import logging
+
+ def test_bad_log(monkeypatch):
+ monkeypatch.setattr(logging, 'raiseExceptions', False)
+ logging.warning('oops', 'first', 2)
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+
+
+def test_log_file_cli_subdirectories_are_successfully_created(
+ pytester: Pytester,
+) -> None:
+ path = pytester.makepyfile(""" def test_logger(): pass """)
+ expected = os.path.join(os.path.dirname(str(path)), "foo", "bar")
+ result = pytester.runpytest("--log-file=foo/bar/logf.log")
+ assert "logf.log" in os.listdir(expected)
+ assert result.ret == ExitCode.OK
+
+
+def test_disable_loggers(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import logging
+ import os
+ disabled_log = logging.getLogger('disabled')
+ test_log = logging.getLogger('test')
+ def test_logger_propagation(caplog):
+ with caplog.at_level(logging.DEBUG):
+ disabled_log.warning("no log; no stderr")
+ test_log.debug("Visible text!")
+ assert caplog.record_tuples == [('test', 10, 'Visible text!')]
+ """
+ )
+ result = pytester.runpytest("--log-disable=disabled", "-s")
+ assert result.ret == ExitCode.OK
+ assert not result.stderr.lines
+
+
+def test_disable_loggers_does_not_propagate(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import logging
+ import os
+
+ parent_logger = logging.getLogger("parent")
+ child_logger = parent_logger.getChild("child")
+
+ def test_logger_propagation_to_parent(caplog):
+ with caplog.at_level(logging.DEBUG):
+ parent_logger.warning("some parent logger message")
+ child_logger.warning("some child logger message")
+ assert len(caplog.record_tuples) == 1
+ assert caplog.record_tuples[0][0] == "parent"
+ assert caplog.record_tuples[0][2] == "some parent logger message"
+ """
+ )
+
+ result = pytester.runpytest("--log-disable=parent.child", "-s")
+ assert result.ret == ExitCode.OK
+ assert not result.stderr.lines
+
+
+def test_log_disabling_works_with_log_cli(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import logging
+ disabled_log = logging.getLogger('disabled')
+ test_log = logging.getLogger('test')
+
+ def test_log_cli_works(caplog):
+ test_log.info("Visible text!")
+ disabled_log.warning("This string will be suppressed.")
+ """
+ )
+ result = pytester.runpytest(
+ "--log-cli-level=DEBUG",
+ "--log-disable=disabled",
+ )
+ assert result.ret == ExitCode.OK
+ result.stdout.fnmatch_lines(
+ "INFO test:test_log_disabling_works_with_log_cli.py:6 Visible text!"
+ )
+ result.stdout.no_fnmatch_line(
+ "WARNING disabled:test_log_disabling_works_with_log_cli.py:7 This string will be suppressed."
+ )
+ assert not result.stderr.lines
+
+
+def test_without_date_format_log(pytester: Pytester) -> None:
+ """Check that date is not printed by default."""
+ pytester.makepyfile(
+ """
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def test_foo():
+ logger.warning('text')
+ assert False
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(
+ ["WARNING test_without_date_format_log:test_without_date_format_log.py:6 text"]
+ )
+
+
+def test_date_format_log(pytester: Pytester) -> None:
+ """Check that log_date_format affects output."""
+ pytester.makepyfile(
+ """
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def test_foo():
+ logger.warning('text')
+ assert False
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_format=%(asctime)s; %(levelname)s; %(message)s
+ log_date_format=%Y-%m-%d %H:%M:%S
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.re_match_lines([r"^[0-9-]{10} [0-9:]{8}; WARNING; text"])
+
+
+def test_date_format_percentf_log(pytester: Pytester) -> None:
+ """Make sure that microseconds are printed in log."""
+ pytester.makepyfile(
+ """
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def test_foo():
+ logger.warning('text')
+ assert False
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_format=%(asctime)s; %(levelname)s; %(message)s
+ log_date_format=%Y-%m-%d %H:%M:%S.%f
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.re_match_lines([r"^[0-9-]{10} [0-9:]{8}.[0-9]{6}; WARNING; text"])
+
+
+def test_date_format_percentf_tz_log(pytester: Pytester) -> None:
+ """Make sure that timezone and microseconds are properly formatted together."""
+ pytester.makepyfile(
+ """
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def test_foo():
+ logger.warning('text')
+ assert False
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ log_format=%(asctime)s; %(levelname)s; %(message)s
+ log_date_format=%Y-%m-%d %H:%M:%S.%f%z
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.re_match_lines(
+ [r"^[0-9-]{10} [0-9:]{8}.[0-9]{6}[+-][0-9\.]+; WARNING; text"]
+ )
+
+
+def test_log_file_cli_fallback_options(pytester: Pytester) -> None:
+ """Make sure that fallback values for log-file formats and level works."""
+ pytester.makepyfile(
+ """
+ import logging
+ logger = logging.getLogger()
+
+ def test_foo():
+ logger.info('info text going to logger')
+ logger.warning('warning text going to logger')
+ logger.error('error text going to logger')
+
+ assert 0
+ """
+ )
+ log_file = str(pytester.path.joinpath("pytest.log"))
+ result = pytester.runpytest(
+ "--log-level=ERROR",
+ "--log-format=%(asctime)s %(message)s",
+ "--log-date-format=%H:%M",
+ "--log-file=pytest.log",
+ )
+ assert result.ret == 1
+
+ # The log file should only contain the error log messages
+ # not the warning or info ones and the format and date format
+ # should match the formats provided using --log-format and --log-date-format
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert re.match(r"[0-9]{2}:[0-9]{2} error text going to logger\s*", contents)
+ assert "info text going to logger" not in contents
+ assert "warning text going to logger" not in contents
+ assert "error text going to logger" in contents
+
+ # Try with a different format and date format to make sure that the formats
+ # are being used
+ result = pytester.runpytest(
+ "--log-level=ERROR",
+ "--log-format=%(asctime)s : %(message)s",
+ "--log-date-format=%H:%M:%S",
+ "--log-file=pytest.log",
+ )
+ assert result.ret == 1
+
+ # The log file should only contain the error log messages
+ # not the warning or info ones and the format and date format
+ # should match the formats provided using --log-format and --log-date-format
+ assert os.path.isfile(log_file)
+ with open(log_file, encoding="utf-8") as rfh:
+ contents = rfh.read()
+ assert re.match(
+ r"[0-9]{2}:[0-9]{2}:[0-9]{2} : error text going to logger\s*", contents
+ )
+ assert "info text going to logger" not in contents
+ assert "warning text going to logger" not in contents
+ assert "error text going to logger" in contents
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/.gitignore b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..d934447a03bd4728a38c11d6811593b79f3a542c
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/.gitignore
@@ -0,0 +1,2 @@
+*.html
+assets/
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/README.rst b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/README.rst
new file mode 100644
index 0000000000000000000000000000000000000000..7d813c5026e56a675e73fad2e3ae173d8d705542
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/README.rst
@@ -0,0 +1,13 @@
+This directory contains tests and support files for smoke testing popular plugins against the current pytest version.
+
+The objective is to gauge if any intentional or unintentional changes in pytest break plugins.
+
+As a rule of thumb, we should add plugins here:
+
+1. That are used at large. This might be subjective in some cases, but if answer is yes to
+ the question: *if a new release of pytest causes pytest-X to break, will this break a ton of test suites out there?*.
+2. That don't have large external dependencies: such as external services.
+
+Besides adding the plugin as dependency, we should also add a quick test which uses some
+minimal part of the plugin, a smoke test. Also consider reusing one of the existing tests if that's
+possible.
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.feature b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.feature
new file mode 100644
index 0000000000000000000000000000000000000000..e404c4948e943c153e29f4886e37d4f58ece27ae
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.feature
@@ -0,0 +1,9 @@
+Feature: Buy things with apple
+
+ Scenario: Buy fruits
+ Given A wallet with 50
+
+ When I buy some apples for 1
+ And I buy some bananas for 2
+
+ Then I have 47 left
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.py
new file mode 100644
index 0000000000000000000000000000000000000000..d748028842a2f6f73ddb9938538d0977d1e47a43
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.py
@@ -0,0 +1,42 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from pytest_bdd import given
+from pytest_bdd import scenario
+from pytest_bdd import then
+from pytest_bdd import when
+
+import pytest
+
+
+@scenario("bdd_wallet.feature", "Buy fruits")
+def test_publish():
+ pass
+
+
+@pytest.fixture
+def wallet():
+ class Wallet:
+ amount = 0
+
+ return Wallet()
+
+
+@given("A wallet with 50")
+def fill_wallet(wallet):
+ wallet.amount = 50
+
+
+@when("I buy some apples for 1")
+def buy_apples(wallet):
+ wallet.amount -= 1
+
+
+@when("I buy some bananas for 2")
+def buy_bananas(wallet):
+ wallet.amount -= 2
+
+
+@then("I have 47 left")
+def check(wallet):
+ assert wallet.amount == 47
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/django_settings.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/django_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..e36e554db9a2c91fb167f5ca3fef690e26d01b9a
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/django_settings.py
@@ -0,0 +1,4 @@
+from __future__ import annotations
+
+
+SECRET_KEY = "mysecret"
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest.ini b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest.ini
new file mode 100644
index 0000000000000000000000000000000000000000..b0eb9c3806f172a8b851c8d5e98e4f7e8b05d96f
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest.ini
@@ -0,0 +1,7 @@
+[pytest]
+strict_markers = True
+asyncio_mode = strict
+filterwarnings =
+ error::pytest.PytestWarning
+ ignore:usefixtures.* without arguments has no effect:pytest.PytestWarning
+ ignore:.*.fspath is deprecated and will be replaced by .*.path.*:pytest.PytestDeprecationWarning
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_anyio_integration.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_anyio_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..41ffad18a6e42a76ad0f0274e1ae43d867342c2b
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_anyio_integration.py
@@ -0,0 +1,11 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import anyio
+
+import pytest
+
+
+@pytest.mark.anyio
+async def test_sleep():
+ await anyio.sleep(0)
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_asyncio_integration.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_asyncio_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..cef67f83ea691454dbb33509eed064d434e5cc3c
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_asyncio_integration.py
@@ -0,0 +1,11 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+
+@pytest.mark.asyncio
+async def test_sleep():
+ await asyncio.sleep(0)
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_mock_integration.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_mock_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..a49129cf0c9a4d9572f84b9d29832a42c877fb81
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_mock_integration.py
@@ -0,0 +1,6 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+
+def test_mocker(mocker):
+ mocker.MagicMock()
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_rerunfailures_integration.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_rerunfailures_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..449661f7294b883fd7d184d30001ffacd19be18b
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_rerunfailures_integration.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+import unittest
+
+
+class MyTestCase(unittest.TestCase):
+ first_time = True
+
+ def test_fail_the_first_time(self) -> None:
+ """Regression test for issue #12424."""
+ if self.first_time:
+ type(self).first_time = False
+ self.fail()
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_trio_integration.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_trio_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..eceac5076a99304d9a78e8cd442a3d90c189335d
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_trio_integration.py
@@ -0,0 +1,11 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import trio
+
+import pytest
+
+
+@pytest.mark.trio
+async def test_sleep():
+ await trio.sleep(0)
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_twisted_integration.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_twisted_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f386bf1b9fdf30077b4be34fac7605014e409b1
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_twisted_integration.py
@@ -0,0 +1,21 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import pytest_twisted
+from twisted.internet.task import deferLater
+
+
+def sleep():
+ import twisted.internet.reactor
+
+ return deferLater(clock=twisted.internet.reactor, delay=0)
+
+
+@pytest_twisted.inlineCallbacks
+def test_inlineCallbacks():
+ yield sleep()
+
+
+@pytest_twisted.ensureDeferred
+async def test_inlineCallbacks_async():
+ await sleep()
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/requirements.txt b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..cb130820c74f50e75c056a8950ef55aa49cf3bed
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/requirements.txt
@@ -0,0 +1,15 @@
+anyio[trio]==4.13.0
+django==6.0.4
+pytest-asyncio==1.3.0
+pytest-bdd==8.1.0
+pytest-cov==7.1.0
+pytest-django==4.12.0
+pytest-flakes==4.0.5
+pytest-html==4.2.0
+pytest-mock==3.15.1
+pytest-rerunfailures==16.1
+pytest-sugar==1.1.1
+pytest-trio==0.8.0
+pytest-twisted==1.14.3
+twisted==25.5.0
+pytest-xvfb==3.1.1
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/simple_integration.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/simple_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed504ae4bf12fcfde4f8768810b09321a20126a9
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/simple_integration.py
@@ -0,0 +1,13 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import pytest
+
+
+def test_foo():
+ assert True
+
+
+@pytest.mark.parametrize("i", range(3))
+def test_bar(i):
+ assert True
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/approx.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/approx.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfbb59fb61d04e74ecf6eca1c5a3674de3742381
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/approx.py
@@ -0,0 +1,1162 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from contextlib import contextmanager
+import decimal
+from decimal import Decimal
+from fractions import Fraction
+from math import inf
+from math import nan
+from math import sqrt
+import operator
+from operator import eq
+from operator import ne
+import re
+
+from _pytest.pytester import Pytester
+from _pytest.python_api import _recursive_sequence_map
+import pytest
+from pytest import approx
+
+
+@pytest.fixture
+def mocked_doctest_runner(monkeypatch):
+ import doctest
+
+ class MockedPdb:
+ def __init__(self, out):
+ pass
+
+ def set_trace(self):
+ raise NotImplementedError("not used")
+
+ def reset(self):
+ pass
+
+ def set_continue(self):
+ pass
+
+ monkeypatch.setattr("doctest._OutputRedirectingPdb", MockedPdb)
+
+ class MyDocTestRunner(doctest.DocTestRunner):
+ def report_failure(self, out, test, example, got):
+ raise AssertionError(
+ f"'{example.source.strip()}' evaluates to '{got.strip()}', not '{example.want.strip()}'"
+ )
+
+ return MyDocTestRunner()
+
+
+@contextmanager
+def temporary_verbosity(config, verbosity=0):
+ original_verbosity = config.getoption("verbose")
+ config.option.verbose = verbosity
+ try:
+ yield
+ finally:
+ config.option.verbose = original_verbosity
+
+
+@pytest.fixture
+def assert_approx_raises_regex(pytestconfig):
+ def do_assert(lhs, rhs, expected_message, verbosity_level=0):
+ import re
+
+ with temporary_verbosity(pytestconfig, verbosity_level):
+ with pytest.raises(AssertionError) as e:
+ assert lhs == approx(rhs)
+
+ nl = "\n"
+ obtained_message = str(e.value).splitlines()[1:]
+ assert len(obtained_message) == len(expected_message), (
+ "Regex message length doesn't match obtained.\n"
+ "Obtained:\n"
+ f"{nl.join(obtained_message)}\n\n"
+ "Expected regex:\n"
+ f"{nl.join(expected_message)}\n\n"
+ )
+
+ for i, (obtained_line, expected_line) in enumerate(
+ zip(obtained_message, expected_message, strict=True)
+ ):
+ regex = re.compile(expected_line)
+ assert regex.match(obtained_line) is not None, (
+ "Unexpected error message:\n"
+ f"{nl.join(obtained_message)}\n\n"
+ "Did not match regex:\n"
+ f"{nl.join(expected_message)}\n\n"
+ f"With verbosity level = {verbosity_level}, on line {i}"
+ )
+
+ return do_assert
+
+
+SOME_FLOAT = r"[+-]?((?:([0-9]*[.])?[0-9]+(e-?[0-9]+)?)|inf|nan)\s*"
+SOME_INT = r"[0-9]+\s*"
+SOME_TOLERANCE = rf"({SOME_FLOAT}|[+-]?[0-9]+(\.[0-9]+)?[eE][+-]?[0-9]+\s*)"
+
+
+class TestApprox:
+ def test_error_messages_native_dtypes(self, assert_approx_raises_regex):
+ # Treat bool exactly.
+ assert_approx_raises_regex(
+ {"a": 1.0, "b": True},
+ {"a": 1.0, "b": False},
+ [
+ "",
+ " comparison failed. Mismatched elements: 1 / 2:",
+ f" Max absolute difference: {SOME_FLOAT}",
+ f" Max relative difference: {SOME_FLOAT}",
+ r" Index\s+\| Obtained\s+\| Expected",
+ r".*(True|False)\s+",
+ ],
+ )
+ assert_approx_raises_regex(
+ 2.0,
+ 1.0,
+ [
+ "",
+ " comparison failed",
+ f" Obtained: {SOME_FLOAT}",
+ f" Expected: {SOME_FLOAT} ± {SOME_TOLERANCE}",
+ ],
+ )
+
+ assert_approx_raises_regex(
+ {"a": 1.0, "b": 1000.0, "c": 1000000.0},
+ {
+ "a": 2.0,
+ "b": 1000.0,
+ "c": 3000000.0,
+ },
+ [
+ r"",
+ r" comparison failed. Mismatched elements: 2 / 3:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ rf" Max relative difference: {SOME_FLOAT}",
+ r" Index \| Obtained\s+\| Expected\s+",
+ rf" a \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}",
+ rf" c \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}",
+ ],
+ )
+
+ assert_approx_raises_regex(
+ {"a": 1.0, "b": None, "c": None},
+ {
+ "a": None,
+ "b": 1000.0,
+ "c": None,
+ },
+ [
+ r"",
+ r" comparison failed. Mismatched elements: 2 / 3:",
+ r" Max absolute difference: -inf",
+ r" Max relative difference: -inf",
+ r" Index \| Obtained\s+\| Expected\s+",
+ rf" a \| {SOME_FLOAT} \| None",
+ rf" b \| None\s+\| {SOME_FLOAT} ± {SOME_FLOAT}",
+ ],
+ )
+
+ assert_approx_raises_regex(
+ [1.0, 2.0, 3.0, 4.0],
+ [1.0, 3.0, 3.0, 5.0],
+ [
+ r"",
+ r" comparison failed. Mismatched elements: 2 / 4:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ rf" Max relative difference: {SOME_FLOAT}",
+ r" Index \| Obtained\s+\| Expected ",
+ rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ rf" 3 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ ],
+ )
+
+ assert_approx_raises_regex(
+ (1, 2.2, 4),
+ (1, 3.2, 4),
+ [
+ r"",
+ r" comparison failed. Mismatched elements: 1 / 3:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ rf" Max relative difference: {SOME_FLOAT}",
+ r" Index \| Obtained\s+\| Expected ",
+ rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ ],
+ )
+
+ # Specific test for comparison with 0.0 (relative diff will be 'inf')
+ assert_approx_raises_regex(
+ [0.0],
+ [1.0],
+ [
+ r"",
+ r" comparison failed. Mismatched elements: 1 / 1:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ r" Max relative difference: inf",
+ r" Index \| Obtained\s+\| Expected ",
+ rf"\s*0\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ ],
+ )
+
+ def test_error_messages_numpy_dtypes(self, assert_approx_raises_regex):
+ np = pytest.importorskip("numpy")
+
+ a = np.linspace(0, 100, 20)
+ b = np.linspace(0, 100, 20)
+ a[10] += 0.5
+ assert_approx_raises_regex(
+ a,
+ b,
+ [
+ r"",
+ r" comparison failed. Mismatched elements: 1 / 20:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ rf" Max relative difference: {SOME_FLOAT}",
+ r" Index \| Obtained\s+\| Expected",
+ rf" \(10,\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ ],
+ )
+
+ assert_approx_raises_regex(
+ np.array(
+ [
+ [[1.1987311, 12412342.3], [3.214143244, 1423412423415.677]],
+ [[1, 2], [3, 219371297321973]],
+ ]
+ ),
+ np.array(
+ [
+ [[1.12313, 12412342.3], [3.214143244, 534523542345.677]],
+ [[1, 2], [3, 7]],
+ ]
+ ),
+ [
+ r"",
+ r" comparison failed. Mismatched elements: 3 / 8:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ rf" Max relative difference: {SOME_FLOAT}",
+ r" Index\s+\| Obtained\s+\| Expected\s+",
+ rf" \(0, 0, 0\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ rf" \(0, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ rf" \(1, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ ],
+ )
+
+ # Specific test for comparison with 0.0 (relative diff will be 'inf')
+ assert_approx_raises_regex(
+ np.array([0.0]),
+ np.array([1.0]),
+ [
+ r"",
+ r" comparison failed. Mismatched elements: 1 / 1:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ r" Max relative difference: inf",
+ r" Index \| Obtained\s+\| Expected ",
+ rf"\s*\(0,\)\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ ],
+ )
+
+ def test_error_messages_invalid_args(self, assert_approx_raises_regex):
+ np = pytest.importorskip("numpy")
+ with pytest.raises(AssertionError) as e:
+ assert np.array([[1.2, 3.4], [4.0, 5.0]]) == pytest.approx(
+ np.array([[4.0], [5.0]])
+ )
+ message = "\n".join(str(e.value).split("\n")[1:])
+ assert message == "\n".join(
+ [
+ " ",
+ " Impossible to compare arrays with different shapes.",
+ " Shapes: (2, 1) and (2, 2)",
+ ]
+ )
+
+ with pytest.raises(AssertionError) as e:
+ assert [1.0, 2.0, 3.0] == pytest.approx([4.0, 5.0])
+ message = "\n".join(str(e.value).split("\n")[1:])
+ assert message == "\n".join(
+ [
+ " ",
+ " Impossible to compare lists with different sizes.",
+ " Lengths: 2 and 3",
+ ]
+ )
+
+ def test_error_messages_with_different_verbosity(self, assert_approx_raises_regex):
+ np = pytest.importorskip("numpy")
+ for v in [0, 1, 2]:
+ # Verbosity level doesn't affect the error message for scalars
+ assert_approx_raises_regex(
+ 2.0,
+ 1.0,
+ [
+ "",
+ " comparison failed",
+ f" Obtained: {SOME_FLOAT}",
+ f" Expected: {SOME_FLOAT} ± {SOME_FLOAT}",
+ ],
+ verbosity_level=v,
+ )
+
+ a = np.linspace(1, 101, 20)
+ b = np.linspace(2, 102, 20)
+ assert_approx_raises_regex(
+ a,
+ b,
+ [
+ r"^ $",
+ r"^ comparison failed. Mismatched elements: 20 / 20:$",
+ rf"^ Max absolute difference: {SOME_FLOAT}$",
+ rf"^ Max relative difference: {SOME_FLOAT}$",
+ r"^ Index \| Obtained\s+\| Expected\s+$",
+ rf"^ \(0,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}$",
+ rf"^ \(1,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}\.\.\.$",
+ "^ $",
+ rf"^ ...Full output truncated \({SOME_INT} lines hidden\), use '-vv' to show$",
+ ],
+ verbosity_level=0,
+ )
+
+ assert_approx_raises_regex(
+ a,
+ b,
+ [
+ r" ",
+ r" comparison failed. Mismatched elements: 20 / 20:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ rf" Max relative difference: {SOME_FLOAT}",
+ r" Index \| Obtained\s+\| Expected",
+ ]
+ + [
+ rf" \({i},\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}"
+ for i in range(20)
+ ],
+ verbosity_level=2,
+ )
+
+ def test_repr_string(self):
+ assert repr(approx(1.0)) == "1.0 ± 1.0e-06"
+ assert repr(approx([1.0, 2.0])) == "approx([1.0 ± 1.0e-06, 2.0 ± 2.0e-06])"
+ assert repr(approx((1.0, 2.0))) == "approx((1.0 ± 1.0e-06, 2.0 ± 2.0e-06))"
+ assert repr(approx(inf)) == "inf"
+ assert repr(approx(1.0, rel=nan)) == "1.0 ± ???"
+ assert repr(approx(1.0, rel=inf)) == "1.0 ± inf"
+
+ # Dictionaries aren't ordered, so we need to check both orders.
+ assert repr(approx({"a": 1.0, "b": 2.0})) in (
+ "approx({'a': 1.0 ± 1.0e-06, 'b': 2.0 ± 2.0e-06})",
+ "approx({'b': 2.0 ± 2.0e-06, 'a': 1.0 ± 1.0e-06})",
+ )
+
+ assert repr(approx(42, abs=1)) == "42 ± 1"
+ assert repr(approx(5, rel=0.01)) == "5 ± 0.05"
+ assert repr(approx(24000, abs=500)) == "24000 ± 500"
+ assert repr(approx(1500, abs=555)) == "1500 ± 555"
+
+ def test_repr_complex_numbers(self):
+ assert repr(approx(inf + 1j)) == "(inf+1j)"
+ assert repr(approx(1.0j, rel=inf)) == "1j ± inf"
+
+ # can't compute a sensible tolerance
+ assert repr(approx(nan + 1j)) == "(nan+1j) ± ???"
+
+ assert repr(approx(1.0j)) == "1j ± 1.0e-06 ∠ ±180°"
+
+ # relative tolerance is scaled to |3+4j| = 5
+ assert repr(approx(3 + 4 * 1j)) == "(3+4j) ± 5.0e-06 ∠ ±180°"
+
+ # absolute tolerance is not scaled
+ assert repr(approx(3.3 + 4.4 * 1j, abs=0.02)) == "(3.3+4.4j) ± 0.02 ∠ ±180°"
+
+ @pytest.mark.parametrize(
+ "value, expected_repr_string",
+ [
+ (5.0, "approx(5.0 ± 5.0e-06)"),
+ ([5.0], "approx([5.0 ± 5.0e-06])"),
+ ([[5.0]], "approx([[5.0 ± 5.0e-06]])"),
+ ([[5.0, 6.0]], "approx([[5.0 ± 5.0e-06, 6.0 ± 6.0e-06]])"),
+ ([[5.0], [6.0]], "approx([[5.0 ± 5.0e-06], [6.0 ± 6.0e-06]])"),
+ ],
+ )
+ def test_repr_nd_array(self, value, expected_repr_string):
+ """Make sure that arrays of all different dimensions are repr'd correctly."""
+ np = pytest.importorskip("numpy")
+ np_array = np.array(value)
+ assert repr(approx(np_array)) == expected_repr_string
+
+ def test_bool(self):
+ with pytest.raises(AssertionError) as err:
+ assert approx(1)
+
+ assert err.match(r"approx\(\) is not supported in a boolean context")
+
+ def test_mixed_sequence(self, assert_approx_raises_regex) -> None:
+ """Approx should work on sequences that also contain non-numbers (#13010)."""
+ assert_approx_raises_regex(
+ [1.1, 2, "word"],
+ [1.0, 2, "different"],
+ [
+ "",
+ r" comparison failed. Mismatched elements: 2 / 3:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ rf" Max relative difference: {SOME_FLOAT}",
+ r" Index \| Obtained\s+\| Expected\s+",
+ r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*",
+ r"\s*2\s*\|\s*word\s*\|\s*different\s*",
+ ],
+ verbosity_level=2,
+ )
+ assert_approx_raises_regex(
+ [1.1, 2, "word"],
+ [1.0, 2, "word"],
+ [
+ "",
+ r" comparison failed. Mismatched elements: 1 / 3:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ rf" Max relative difference: {SOME_FLOAT}",
+ r" Index \| Obtained\s+\| Expected\s+",
+ r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*",
+ ],
+ verbosity_level=2,
+ )
+ assert [1.1, 2, "word"] == pytest.approx([1.1, 2, "word"])
+
+ def test_operator_overloading(self):
+ assert 1 == approx(1, rel=1e-6, abs=1e-12)
+ assert not (1 != approx(1, rel=1e-6, abs=1e-12))
+ assert 10 != approx(1, rel=1e-6, abs=1e-12)
+ assert not (10 == approx(1, rel=1e-6, abs=1e-12))
+
+ def test_exactly_equal(self):
+ examples = [
+ (2.0, 2.0),
+ (0.1e200, 0.1e200),
+ (1.123e-300, 1.123e-300),
+ (12345, 12345.0),
+ (0.0, -0.0),
+ (345678, 345678),
+ (Decimal("1.0001"), Decimal("1.0001")),
+ (Fraction(1, 3), Fraction(-1, -3)),
+ ]
+ for a, x in examples:
+ assert a == approx(x)
+
+ def test_opposite_sign(self):
+ examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)]
+ for op, a, x in examples:
+ assert op(a, approx(x))
+
+ def test_zero_tolerance(self):
+ within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)]
+ for a, x in within_1e10:
+ assert x == approx(x, rel=0.0, abs=0.0)
+ assert a != approx(x, rel=0.0, abs=0.0)
+ assert a == approx(x, rel=0.0, abs=5e-101)
+ assert a != approx(x, rel=0.0, abs=5e-102)
+ assert a == approx(x, rel=5e-1, abs=0.0)
+ assert a != approx(x, rel=5e-2, abs=0.0)
+
+ @pytest.mark.parametrize(
+ ("rel", "abs"),
+ [
+ (-1e100, None),
+ (None, -1e100),
+ (1e100, -1e100),
+ (-1e100, 1e100),
+ (-1e100, -1e100),
+ ],
+ )
+ def test_negative_tolerance(self, rel: float | None, abs: float | None) -> None:
+ # Negative tolerances are not allowed.
+ with pytest.raises(ValueError):
+ 1.1 == approx(1, rel, abs)
+
+ def test_negative_tolerance_message(self):
+ # Error message for negative tolerance should include the value.
+ with pytest.raises(ValueError, match="-3"):
+ 0 == approx(1, abs=-3)
+ with pytest.raises(ValueError, match="-3"):
+ 0 == approx(1, rel=-3)
+
+ def test_inf_tolerance(self):
+ # Everything should be equal if the tolerance is infinite.
+ large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)]
+ for a, x in large_diffs:
+ assert a != approx(x, rel=0.0, abs=0.0)
+ assert a == approx(x, rel=inf, abs=0.0)
+ assert a == approx(x, rel=0.0, abs=inf)
+ assert a == approx(x, rel=inf, abs=inf)
+
+ def test_inf_tolerance_expecting_zero(self) -> None:
+ # If the relative tolerance is zero but the expected value is infinite,
+ # the actual tolerance is a NaN, which should be an error.
+ with pytest.raises(ValueError):
+ 1 == approx(0, rel=inf, abs=0.0)
+ with pytest.raises(ValueError):
+ 1 == approx(0, rel=inf, abs=inf)
+
+ def test_nan_tolerance(self) -> None:
+ with pytest.raises(ValueError):
+ 1.1 == approx(1, rel=nan)
+ with pytest.raises(ValueError):
+ 1.1 == approx(1, abs=nan)
+ with pytest.raises(ValueError):
+ 1.1 == approx(1, rel=nan, abs=nan)
+
+ def test_reasonable_defaults(self):
+ # Whatever the defaults are, they should work for numbers close to 1
+ # than have a small amount of floating-point error.
+ assert 0.1 + 0.2 == approx(0.3)
+
+ def test_default_tolerances(self):
+ # This tests the defaults as they are currently set. If you change the
+ # defaults, this test will fail but you should feel free to change it.
+ # None of the other tests (except the doctests) should be affected by
+ # the choice of defaults.
+ examples = [
+ # Relative tolerance used.
+ (eq, 1e100 + 1e94, 1e100),
+ (ne, 1e100 + 2e94, 1e100),
+ (eq, 1e0 + 1e-6, 1e0),
+ (ne, 1e0 + 2e-6, 1e0),
+ # Absolute tolerance used.
+ (eq, 1e-100, +1e-106),
+ (eq, 1e-100, +2e-106),
+ (eq, 1e-100, 0),
+ ]
+ for op, a, x in examples:
+ assert op(a, approx(x))
+
+ def test_custom_tolerances(self):
+ assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0)
+ assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0)
+ assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e-1)
+ assert 1e8 + 1e0 != approx(1e8, rel=5e-9, abs=5e-1)
+
+ assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-8)
+ assert 1e0 + 1e-8 == approx(1e0, rel=5e-9, abs=5e-8)
+ assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-9)
+ assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9)
+
+ assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16)
+ assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16)
+ assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17)
+ assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17)
+
+ def test_relative_tolerance(self):
+ within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)]
+ for a, x in within_1e8_rel:
+ assert a == approx(x, rel=5e-8, abs=0.0)
+ assert a != approx(x, rel=5e-9, abs=0.0)
+
+ def test_absolute_tolerance(self):
+ within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)]
+ for a, x in within_1e8_abs:
+ assert a == approx(x, rel=0, abs=5e-8)
+ assert a != approx(x, rel=0, abs=5e-9)
+
+ def test_expecting_zero(self):
+ examples = [
+ (ne, 1e-6, 0.0),
+ (ne, -1e-6, 0.0),
+ (eq, 1e-12, 0.0),
+ (eq, -1e-12, 0.0),
+ (ne, 2e-12, 0.0),
+ (ne, -2e-12, 0.0),
+ (ne, inf, 0.0),
+ (ne, nan, 0.0),
+ ]
+ for op, a, x in examples:
+ assert op(a, approx(x, rel=0.0, abs=1e-12))
+ assert op(a, approx(x, rel=1e-6, abs=1e-12))
+
+ def test_expecting_inf(self):
+ examples = [
+ (eq, inf, inf),
+ (eq, -inf, -inf),
+ (ne, inf, -inf),
+ (ne, 0.0, inf),
+ (ne, nan, inf),
+ ]
+ for op, a, x in examples:
+ assert op(a, approx(x))
+
+ def test_expecting_nan(self):
+ examples = [
+ (eq, nan, nan),
+ (eq, -nan, -nan),
+ (eq, nan, -nan),
+ (ne, 0.0, nan),
+ (ne, inf, nan),
+ ]
+ for op, a, x in examples:
+ # Nothing is equal to NaN by default.
+ assert a != approx(x)
+
+ # If ``nan_ok=True``, then NaN is equal to NaN.
+ assert op(a, approx(x, nan_ok=True))
+
+ def test_int(self):
+ within_1e6 = [(1000001, 1000000), (-1000001, -1000000)]
+ for a, x in within_1e6:
+ assert a == approx(x, rel=5e-6, abs=0)
+ assert a != approx(x, rel=5e-7, abs=0)
+ assert approx(x, rel=5e-6, abs=0) == a
+ assert approx(x, rel=5e-7, abs=0) != a
+
+ def test_decimal(self):
+ within_1e6 = [
+ (Decimal("1.000001"), Decimal("1.0")),
+ (Decimal("-1.000001"), Decimal("-1.0")),
+ ]
+ for a, x in within_1e6:
+ assert a == approx(x)
+ assert a == approx(x, rel=Decimal("5e-6"), abs=0)
+ assert a != approx(x, rel=Decimal("5e-7"), abs=0)
+ assert approx(x, rel=Decimal("5e-6"), abs=0) == a
+ assert approx(x, rel=Decimal("5e-7"), abs=0) != a
+ assert approx(x, rel=0, abs=Decimal("5e-3")) == a
+ assert approx(x, rel=0, abs=Decimal("5e-7")) != a
+
+ def test_fraction(self):
+ within_1e6 = [
+ (1 + Fraction(1, 1000000), Fraction(1)),
+ (-1 - Fraction(-1, 1000000), Fraction(-1)),
+ ]
+ for a, x in within_1e6:
+ assert a == approx(x, rel=5e-6, abs=0)
+ assert a != approx(x, rel=5e-7, abs=0)
+ assert approx(x, rel=5e-6, abs=0) == a
+ assert approx(x, rel=5e-7, abs=0) != a
+
+ def test_complex(self):
+ within_1e6 = [
+ (1.000001 + 1.0j, 1.0 + 1.0j),
+ (1.0 + 1.000001j, 1.0 + 1.0j),
+ (-1.000001 + 1.0j, -1.0 + 1.0j),
+ (1.0 - 1.000001j, 1.0 - 1.0j),
+ ]
+ for a, x in within_1e6:
+ assert a == approx(x, rel=5e-6, abs=0)
+ assert a != approx(x, rel=5e-7, abs=0)
+ assert approx(x, rel=5e-6, abs=0) == a
+ assert approx(x, rel=5e-7, abs=0) != a
+
+ def test_expecting_bool(self) -> None:
+ assert True == approx(True) # noqa: E712
+ assert False == approx(False) # noqa: E712
+ assert True != approx(False) # noqa: E712
+ assert True != approx(False, abs=2) # noqa: E712
+ assert 1 != approx(True)
+
+ def test_expecting_bool_numpy(self) -> None:
+ """Check approx comparing with numpy.bool (#13047)."""
+ np = pytest.importorskip("numpy")
+ assert np.False_ != approx(True)
+ assert np.True_ != approx(False)
+ assert np.True_ == approx(True)
+ assert np.False_ == approx(False)
+ assert np.True_ != approx(False, abs=2)
+
+ def test_list(self):
+ actual = [1 + 1e-7, 2 + 1e-8]
+ expected = [1, 2]
+
+ # Return false if any element is outside the tolerance.
+ assert actual == approx(expected, rel=5e-7, abs=0)
+ assert actual != approx(expected, rel=5e-8, abs=0)
+ assert approx(expected, rel=5e-7, abs=0) == actual
+ assert approx(expected, rel=5e-8, abs=0) != actual
+
+ def test_list_decimal(self):
+ actual = [Decimal("1.000001"), Decimal("2.000001")]
+ expected = [Decimal("1"), Decimal("2")]
+
+ assert actual == approx(expected)
+
+ def test_list_wrong_len(self):
+ assert [1, 2] != approx([1])
+ assert [1, 2] != approx([1, 2, 3])
+
+ def test_tuple(self):
+ actual = (1 + 1e-7, 2 + 1e-8)
+ expected = (1, 2)
+
+ # Return false if any element is outside the tolerance.
+ assert actual == approx(expected, rel=5e-7, abs=0)
+ assert actual != approx(expected, rel=5e-8, abs=0)
+ assert approx(expected, rel=5e-7, abs=0) == actual
+ assert approx(expected, rel=5e-8, abs=0) != actual
+
+ def test_tuple_wrong_len(self):
+ assert (1, 2) != approx((1,))
+ assert (1, 2) != approx((1, 2, 3))
+
+ def test_tuple_vs_other(self):
+ assert 1 != approx((1,))
+
+ def test_dict(self):
+ actual = {"a": 1 + 1e-7, "b": 2 + 1e-8}
+ # Dictionaries became ordered in python3.6, so switch up the order here
+ # to make sure it doesn't matter.
+ expected = {"b": 2, "a": 1}
+
+ # Return false if any element is outside the tolerance.
+ assert actual == approx(expected, rel=5e-7, abs=0)
+ assert actual != approx(expected, rel=5e-8, abs=0)
+ assert approx(expected, rel=5e-7, abs=0) == actual
+ assert approx(expected, rel=5e-8, abs=0) != actual
+
+ def test_dict_decimal(self):
+ actual = {"a": Decimal("1.000001"), "b": Decimal("2.000001")}
+ # Dictionaries became ordered in python3.6, so switch up the order here
+ # to make sure it doesn't matter.
+ expected = {"b": Decimal("2"), "a": Decimal("1")}
+
+ assert actual == approx(expected)
+
+ def test_dict_wrong_len(self):
+ assert {"a": 1, "b": 2} != approx({"a": 1})
+ assert {"a": 1, "b": 2} != approx({"a": 1, "c": 2})
+ assert {"a": 1, "b": 2} != approx({"a": 1, "b": 2, "c": 3})
+
+ def test_dict_nonnumeric(self):
+ assert {"a": 1.0, "b": None} == pytest.approx({"a": 1.0, "b": None})
+ assert {"a": 1.0, "b": 1} != pytest.approx({"a": 1.0, "b": None})
+ assert {"a": 1.0, "b": True} != pytest.approx({"a": 1.0, "b": False}, abs=2)
+
+ def test_dict_vs_other(self):
+ assert 1 != approx({"a": 0})
+
+ def test_dict_for_div_by_zero(self, assert_approx_raises_regex):
+ assert_approx_raises_regex(
+ {"foo": 42.0},
+ {"foo": 0.0},
+ [
+ r"",
+ r" comparison failed. Mismatched elements: 1 / 1:",
+ rf" Max absolute difference: {SOME_FLOAT}",
+ r" Max relative difference: inf",
+ r" Index \| Obtained\s+\| Expected ",
+ rf" foo | {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
+ ],
+ )
+
+ def test_dict_differing_lengths(self, assert_approx_raises_regex):
+ assert_approx_raises_regex(
+ {"a": 0},
+ {"a": 0, "b": 1},
+ [
+ " ",
+ r" Impossible to compare mappings with different sizes\.",
+ r" Lengths: 2 and 1",
+ ],
+ )
+
+ def test_numpy_array(self):
+ np = pytest.importorskip("numpy")
+
+ actual = np.array([1 + 1e-7, 2 + 1e-8])
+ expected = np.array([1, 2])
+
+ # Return false if any element is outside the tolerance.
+ assert actual == approx(expected, rel=5e-7, abs=0)
+ assert actual != approx(expected, rel=5e-8, abs=0)
+ assert approx(expected, rel=5e-7, abs=0) == expected
+ assert approx(expected, rel=5e-8, abs=0) != actual
+
+ # Should be able to compare lists with numpy arrays.
+ assert list(actual) == approx(expected, rel=5e-7, abs=0)
+ assert list(actual) != approx(expected, rel=5e-8, abs=0)
+ assert actual == approx(list(expected), rel=5e-7, abs=0)
+ assert actual != approx(list(expected), rel=5e-8, abs=0)
+
+ def test_numpy_tolerance_args(self):
+ """
+ Check that numpy rel/abs args are handled correctly
+ for comparison against an np.array
+ Check both sides of the operator, hopefully it doesn't impact things.
+ Test all permutations of where the approx and np.array() can show up
+ """
+ np = pytest.importorskip("numpy")
+ expected = 100.0
+ actual = 99.0
+ abs_diff = expected - actual
+ rel_diff = (expected - actual) / expected
+
+ tests = [
+ (eq, abs_diff, 0),
+ (eq, 0, rel_diff),
+ (ne, 0, rel_diff / 2.0), # rel diff fail
+ (ne, abs_diff / 2.0, 0), # abs diff fail
+ ]
+
+ for op, _abs, _rel in tests:
+ assert op(np.array(actual), approx(expected, abs=_abs, rel=_rel)) # a, b
+ assert op(approx(expected, abs=_abs, rel=_rel), np.array(actual)) # b, a
+
+ assert op(actual, approx(np.array(expected), abs=_abs, rel=_rel)) # a, b
+ assert op(approx(np.array(expected), abs=_abs, rel=_rel), actual) # b, a
+
+ assert op(np.array(actual), approx(np.array(expected), abs=_abs, rel=_rel))
+ assert op(approx(np.array(expected), abs=_abs, rel=_rel), np.array(actual))
+
+ def test_numpy_expecting_nan(self):
+ np = pytest.importorskip("numpy")
+ examples = [
+ (eq, nan, nan),
+ (eq, -nan, -nan),
+ (eq, nan, -nan),
+ (ne, 0.0, nan),
+ (ne, inf, nan),
+ ]
+ for op, a, x in examples:
+ # Nothing is equal to NaN by default.
+ assert np.array(a) != approx(x)
+ assert a != approx(np.array(x))
+
+ # If ``nan_ok=True``, then NaN is equal to NaN.
+ assert op(np.array(a), approx(x, nan_ok=True))
+ assert op(a, approx(np.array(x), nan_ok=True))
+
+ def test_numpy_expecting_inf(self):
+ np = pytest.importorskip("numpy")
+ examples = [
+ (eq, inf, inf),
+ (eq, -inf, -inf),
+ (ne, inf, -inf),
+ (ne, 0.0, inf),
+ (ne, nan, inf),
+ ]
+ for op, a, x in examples:
+ assert op(np.array(a), approx(x))
+ assert op(a, approx(np.array(x)))
+ assert op(np.array(a), approx(np.array(x)))
+
+ def test_numpy_array_wrong_shape(self):
+ np = pytest.importorskip("numpy")
+
+ a12 = np.array([[1, 2]])
+ a21 = np.array([[1], [2]])
+
+ assert a12 != approx(a21)
+ assert a21 != approx(a12)
+
+ def test_numpy_array_implicit_conversion(self):
+ np = pytest.importorskip("numpy")
+
+ class ImplicitArray:
+ """Type which is implicitly convertible to a numpy array."""
+
+ def __init__(self, vals):
+ self.vals = vals
+
+ def __array__(self, dtype=None, copy=None):
+ return np.array(self.vals)
+
+ vec1 = ImplicitArray([1.0, 2.0, 3.0])
+ vec2 = ImplicitArray([1.0, 2.0, 4.0])
+ # see issue #12114 for test case
+ assert vec1 != approx(vec2)
+
+ def test_numpy_array_protocol(self):
+ """
+ array-like objects such as tensorflow's DeviceArray are handled like ndarray.
+ See issue #8132
+ """
+ np = pytest.importorskip("numpy")
+
+ class DeviceArray:
+ def __init__(self, value, size):
+ self.value = value
+ self.size = size
+
+ def __array__(self):
+ return self.value * np.ones(self.size)
+
+ class DeviceScalar:
+ def __init__(self, value):
+ self.value = value
+
+ def __array__(self):
+ return np.array(self.value)
+
+ expected = 1
+ actual = 1 + 1e-6
+ assert approx(expected) == DeviceArray(actual, size=1)
+ assert approx(expected) == DeviceArray(actual, size=2)
+ assert approx(expected) == DeviceScalar(actual)
+ assert approx(DeviceScalar(expected)) == actual
+ assert approx(DeviceScalar(expected)) == DeviceScalar(actual)
+
+ def test_doctests(self, mocked_doctest_runner) -> None:
+ import doctest
+
+ parser = doctest.DocTestParser()
+ assert approx.__doc__ is not None
+ test = parser.get_doctest(
+ approx.__doc__, {"approx": approx}, approx.__name__, None, None
+ )
+ mocked_doctest_runner.run(test)
+
+ def test_unicode_plus_minus(self, pytester: Pytester) -> None:
+ """
+ Comparing approx instances inside lists should not produce an error in the detailed diff.
+ Integration test for issue #2111.
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+ def test_foo():
+ assert [3] == [pytest.approx(4)]
+ """
+ )
+ expected = "4.0e-06"
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [f"*At index 0 diff: 3 != 4 ± {expected}", "=* 1 failed in *="]
+ )
+
+ @pytest.mark.parametrize(
+ "x, name",
+ [
+ pytest.param([[1]], "data structures", id="nested-list"),
+ pytest.param({"key": {"key": 1}}, "dictionaries", id="nested-dict"),
+ ],
+ )
+ def test_expected_value_type_error(self, x, name):
+ with pytest.raises(
+ TypeError,
+ match=rf"pytest.approx\(\) does not support nested {name}:",
+ ):
+ approx(x)
+
+ @pytest.mark.parametrize(
+ "x",
+ [
+ pytest.param(None),
+ pytest.param("string"),
+ pytest.param(["string"], id="nested-str"),
+ pytest.param({"key": "string"}, id="dict-with-string"),
+ ],
+ )
+ def test_nonnumeric_okay_if_equal(self, x):
+ assert x == approx(x)
+
+ @pytest.mark.parametrize(
+ "x",
+ [
+ pytest.param("string"),
+ pytest.param(["string"], id="nested-str"),
+ pytest.param({"key": "string"}, id="dict-with-string"),
+ ],
+ )
+ def test_nonnumeric_false_if_unequal(self, x):
+ """For non-numeric types, x != pytest.approx(y) reduces to x != y"""
+ assert "ab" != approx("abc")
+ assert ["ab"] != approx(["abc"])
+ # in particular, both of these should return False
+ assert {"a": 1.0} != approx({"a": None})
+ assert {"a": None} != approx({"a": 1.0})
+
+ assert 1.0 != approx(None)
+ assert None != approx(1.0) # noqa: E711
+
+ assert 1.0 != approx([None])
+ assert None != approx([1.0]) # noqa: E711
+
+ def test_nonnumeric_dict_repr(self):
+ """Dicts with non-numerics and infinites have no tolerances"""
+ x1 = {"foo": 1.0000005, "bar": None, "foobar": inf}
+ assert (
+ repr(approx(x1))
+ == "approx({'foo': 1.0000005 ± 1.0e-06, 'bar': None, 'foobar': inf})"
+ )
+
+ def test_nonnumeric_list_repr(self):
+ """Lists with non-numerics and infinites have no tolerances"""
+ x1 = [1.0000005, None, inf]
+ assert repr(approx(x1)) == "approx([1.0000005 ± 1.0e-06, None, inf])"
+
+ @pytest.mark.parametrize(
+ "op",
+ [
+ pytest.param(operator.le, id="<="),
+ pytest.param(operator.lt, id="<"),
+ pytest.param(operator.ge, id=">="),
+ pytest.param(operator.gt, id=">"),
+ ],
+ )
+ def test_comparison_operator_type_error(self, op):
+ """pytest.approx should raise TypeError for operators other than == and != (#2003)."""
+ with pytest.raises(TypeError):
+ op(1, approx(1, rel=1e-6, abs=1e-12))
+
+ def test_numpy_array_with_scalar(self):
+ np = pytest.importorskip("numpy")
+
+ actual = np.array([1 + 1e-7, 1 - 1e-8])
+ expected = 1.0
+
+ assert actual == approx(expected, rel=5e-7, abs=0)
+ assert actual != approx(expected, rel=5e-8, abs=0)
+ assert approx(expected, rel=5e-7, abs=0) == actual
+ assert approx(expected, rel=5e-8, abs=0) != actual
+
+ def test_numpy_scalar_with_array(self):
+ np = pytest.importorskip("numpy")
+
+ actual = 1.0
+ expected = np.array([1 + 1e-7, 1 - 1e-8])
+
+ assert actual == approx(expected, rel=5e-7, abs=0)
+ assert actual != approx(expected, rel=5e-8, abs=0)
+ assert approx(expected, rel=5e-7, abs=0) == actual
+ assert approx(expected, rel=5e-8, abs=0) != actual
+
+ def test_generic_ordered_sequence(self):
+ class MySequence:
+ def __getitem__(self, i):
+ return [1, 2, 3, 4][i]
+
+ def __len__(self):
+ return 4
+
+ expected = MySequence()
+ assert [1, 2, 3, 4] == approx(expected, abs=1e-4)
+
+ expected_repr = "approx([1 ± 1.0e-06, 2 ± 2.0e-06, 3 ± 3.0e-06, 4 ± 4.0e-06])"
+ assert repr(approx(expected)) == expected_repr
+
+ def test_decimal_approx_repr(self, monkeypatch) -> None:
+ monkeypatch.setitem(decimal.getcontext().traps, decimal.FloatOperation, True)
+ approx_obj = pytest.approx(decimal.Decimal("2.60"))
+ assert decimal.Decimal("2.600001") == approx_obj
+
+ def test_allow_ordered_sequences_only(self) -> None:
+ """pytest.approx() should raise an error on unordered sequences (#9692)."""
+ with pytest.raises(TypeError, match="only supports ordered sequences"):
+ assert {1, 2, 3} == approx({1, 2, 3})
+
+ def test_strange_sequence(self):
+ """https://github.com/pytest-dev/pytest/issues/11797"""
+ a = MyVec3(1, 2, 3)
+ b = MyVec3(0, 1, 2)
+
+ # this would trigger the error inside the test
+ pytest.approx(a, abs=0.5)._repr_compare(b)
+
+ assert b == pytest.approx(a, abs=2)
+ assert b != pytest.approx(a, abs=0.5)
+
+ def test_approx_dicts_with_mismatch_on_keys(self) -> None:
+ """https://github.com/pytest-dev/pytest/issues/13816"""
+ expected = {"a": 1, "b": 3}
+ actual = {"a": 1, "c": 3}
+
+ with pytest.raises(
+ AssertionError,
+ match=re.escape(
+ "comparison failed.\n Mappings has different keys: "
+ "expected dict_keys(['a', 'b']) but got dict_keys(['a', 'c'])"
+ ),
+ ):
+ assert actual == approx(expected)
+
+ def test_approx_on_unordered_mapping_with_mismatch(
+ self, pytester: Pytester
+ ) -> None:
+ """https://github.com/pytest-dev/pytest/issues/12444"""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ def test_approx_on_unordered_mapping_with_mismatch():
+ expected = {"a": 1, "b": 2, "c": 3, "d": 4}
+ actual = {"d": 4, "c": 5, "a": 8, "b": 2}
+ assert actual == pytest.approx(expected)
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(failed=1)
+ result.stdout.fnmatch_lines(
+ [
+ "*comparison failed.**Mismatched elements: 2 / 4:*",
+ "*Max absolute difference: 7*",
+ "*Index | Obtained | Expected *",
+ "* a * | 8 * | 1 *",
+ "* c * | 5 * | 3 *",
+ ]
+ )
+
+ def test_approx_on_unordered_mapping_matching(self, pytester: Pytester) -> None:
+ """https://github.com/pytest-dev/pytest/issues/12444"""
+ pytester.makepyfile(
+ """
+ import pytest
+ def test_approx_on_unordered_mapping_matching():
+ expected = {"a": 1, "b": 2, "c": 3, "d": 4}
+ actual = {"d": 4, "c": 3, "a": 1, "b": 2}
+ assert actual == pytest.approx(expected)
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+
+
+class MyVec3: # incomplete
+ """sequence like"""
+
+ _x: int
+ _y: int
+ _z: int
+
+ def __init__(self, x: int, y: int, z: int):
+ self._x, self._y, self._z = x, y, z
+
+ def __repr__(self) -> str:
+ return f""
+
+ def __len__(self) -> int:
+ return 3
+
+ def __getitem__(self, key: int) -> int:
+ if key == 0:
+ return self._x
+ if key == 1:
+ return self._y
+ if key == 2:
+ return self._z
+ raise IndexError(key)
+
+
+class TestRecursiveSequenceMap:
+ def test_map_over_scalar(self):
+ assert _recursive_sequence_map(sqrt, 16) == 4
+
+ def test_map_over_empty_list(self):
+ assert _recursive_sequence_map(sqrt, []) == []
+
+ def test_map_over_list(self):
+ assert _recursive_sequence_map(sqrt, [4, 16, 25, 676]) == [2, 4, 5, 26]
+
+ def test_map_over_tuple(self):
+ assert _recursive_sequence_map(sqrt, (4, 16, 25, 676)) == (2, 4, 5, 26)
+
+ def test_map_over_nested_lists(self):
+ assert _recursive_sequence_map(sqrt, [4, [25, 64], [[49]]]) == [
+ 2,
+ [5, 8],
+ [[7]],
+ ]
+
+ def test_map_over_mixed_sequence(self):
+ assert _recursive_sequence_map(sqrt, [4, (25, 64), [49]]) == [
+ 2,
+ (5, 8),
+ [7],
+ ]
+
+ def test_map_over_sequence_like(self):
+ assert _recursive_sequence_map(int, MyVec3(1, 2, 3)) == [1, 2, 3]
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/collect.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/collect.py
new file mode 100644
index 0000000000000000000000000000000000000000..2aa3aae7b1a48224056455677213baccc974b101
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/collect.py
@@ -0,0 +1,1725 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import os
+import sys
+import textwrap
+from typing import Any
+
+import _pytest._code
+from _pytest.config import ExitCode
+from _pytest.main import Session
+from _pytest.monkeypatch import MonkeyPatch
+from _pytest.nodes import Collector
+from _pytest.pytester import Pytester
+from _pytest.python import Class
+from _pytest.python import Function
+import pytest
+
+
+class TestModule:
+ def test_failing_import(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol("import alksdjalskdjalkjals")
+ with pytest.raises(Collector.CollectError):
+ modcol.collect()
+
+ def test_import_duplicate(self, pytester: Pytester) -> None:
+ a = pytester.mkdir("a")
+ b = pytester.mkdir("b")
+ p1 = a.joinpath("test_whatever.py")
+ p1.touch()
+ p2 = b.joinpath("test_whatever.py")
+ p2.touch()
+ # ensure we don't have it imported already
+ sys.modules.pop(p1.stem, None)
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*import*mismatch*",
+ "*imported*test_whatever*",
+ f"*{p1}*",
+ "*not the same*",
+ f"*{p2}*",
+ "*HINT*",
+ ]
+ )
+
+ def test_import_prepend_append(
+ self, pytester: Pytester, monkeypatch: MonkeyPatch
+ ) -> None:
+ root1 = pytester.mkdir("root1")
+ root2 = pytester.mkdir("root2")
+ root1.joinpath("x456.py").touch()
+ root2.joinpath("x456.py").touch()
+ p = root2.joinpath("test_x456.py")
+ monkeypatch.syspath_prepend(str(root1))
+ p.write_text(
+ textwrap.dedent(
+ f"""\
+ import x456
+ def test():
+ assert x456.__file__.startswith({str(root2)!r})
+ """
+ ),
+ encoding="utf-8",
+ )
+ with monkeypatch.context() as mp:
+ mp.chdir(root2)
+ reprec = pytester.inline_run("--import-mode=append")
+ reprec.assertoutcome(passed=0, failed=1)
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_syntax_error_in_module(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol("this is a syntax error")
+ with pytest.raises(modcol.CollectError):
+ modcol.collect()
+ with pytest.raises(modcol.CollectError):
+ modcol.collect()
+
+ def test_module_considers_pluginmanager_at_import(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol("pytest_plugins='xasdlkj',")
+ with pytest.raises(ImportError):
+ modcol.obj()
+
+ def test_invalid_test_module_name(self, pytester: Pytester) -> None:
+ a = pytester.mkdir("a")
+ a.joinpath("test_one.part1.py").touch()
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "ImportError while importing test module*test_one.part1*",
+ "Hint: make sure your test modules/packages have valid Python names.",
+ ]
+ )
+
+ @pytest.mark.parametrize("verbose", [0, 1, 2])
+ def test_show_traceback_import_error(
+ self, pytester: Pytester, verbose: int
+ ) -> None:
+ """Import errors when collecting modules should display the traceback (#1976).
+
+ With low verbosity we omit pytest and internal modules, otherwise show all traceback entries.
+ """
+ pytester.makepyfile(
+ foo_traceback_import_error="""
+ from bar_traceback_import_error import NOT_AVAILABLE
+ """,
+ bar_traceback_import_error="",
+ )
+ pytester.makepyfile(
+ """
+ import foo_traceback_import_error
+ """
+ )
+ args = ("-v",) * verbose
+ result = pytester.runpytest(*args)
+ result.stdout.fnmatch_lines(
+ [
+ "ImportError while importing test module*",
+ "Traceback:",
+ "*from bar_traceback_import_error import NOT_AVAILABLE",
+ "*cannot import name *NOT_AVAILABLE*",
+ ]
+ )
+ assert result.ret == 2
+
+ stdout = result.stdout.str()
+ if verbose == 2:
+ assert "_pytest" in stdout
+ else:
+ assert "_pytest" not in stdout
+
+ def test_show_traceback_import_error_unicode(self, pytester: Pytester) -> None:
+ """Check test modules collected which raise ImportError with unicode messages
+ are handled properly (#2336).
+ """
+ pytester.makepyfile("raise ImportError('Something bad happened ☺')")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "ImportError while importing test module*",
+ "Traceback:",
+ "*raise ImportError*Something bad happened*",
+ ]
+ )
+ assert result.ret == 2
+
+
+class TestClass:
+ def test_class_with_init_warning(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ class TestClass1(object):
+ def __init__(self):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*cannot collect test class 'TestClass1' because it has "
+ "a __init__ constructor (from: test_class_with_init_warning.py)"
+ ]
+ )
+
+ def test_class_with_new_warning(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ class TestClass1(object):
+ def __new__(self):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*cannot collect test class 'TestClass1' because it has "
+ "a __new__ constructor (from: test_class_with_new_warning.py)"
+ ]
+ )
+
+ def test_class_subclassobject(self, pytester: Pytester) -> None:
+ pytester.getmodulecol(
+ """
+ class test(object):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*collected 0*"])
+
+ def test_static_method(self, pytester: Pytester) -> None:
+ """Support for collecting staticmethod tests (#2528, #2699)"""
+ pytester.getmodulecol(
+ """
+ import pytest
+ class Test(object):
+ @staticmethod
+ def test_something():
+ pass
+
+ @pytest.fixture
+ def fix(self):
+ return 1
+
+ @staticmethod
+ def test_fix(fix):
+ assert fix == 1
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*collected 2 items*", "*2 passed in*"])
+
+ def test_setup_teardown_class_as_classmethod(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ test_mod1="""
+ class TestClassMethod(object):
+ @classmethod
+ def setup_class(cls):
+ pass
+ def test_1(self):
+ pass
+ @classmethod
+ def teardown_class(cls):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_issue1035_obj_has_getattr(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ class Chameleon(object):
+ def __getattr__(self, name):
+ return True
+ chameleon = Chameleon()
+ """
+ )
+ colitems = modcol.collect()
+ assert len(colitems) == 0
+
+ def test_issue1579_namedtuple(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import collections
+
+ TestCase = collections.namedtuple('TestCase', ['a'])
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ "*cannot collect test class 'TestCase' "
+ "because it has a __new__ constructor*"
+ )
+
+ def test_issue2234_property(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ class TestCase(object):
+ @property
+ def prop(self):
+ raise NotImplementedError()
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+
+ def test_does_not_discover_properties(self, pytester: Pytester) -> None:
+ """Regression test for #12446."""
+ pytester.makepyfile(
+ """\
+ class TestCase:
+ @property
+ def oops(self):
+ raise SystemExit('do not call me!')
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+
+ def test_does_not_discover_instance_descriptors(self, pytester: Pytester) -> None:
+ """Regression test for #12446."""
+ pytester.makepyfile(
+ """\
+ # not `@property`, but it acts like one
+ # this should cover the case of things like `@cached_property` / etc.
+ class MyProperty:
+ def __init__(self, func):
+ self._func = func
+ def __get__(self, inst, owner):
+ if inst is None:
+ return self
+ else:
+ return self._func.__get__(inst, owner)()
+
+ class TestCase:
+ @MyProperty
+ def oops(self):
+ raise SystemExit('do not call me!')
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+
+ def test_abstract_class_is_not_collected(self, pytester: Pytester) -> None:
+ """Regression test for #12275 (non-unittest version)."""
+ pytester.makepyfile(
+ """
+ import abc
+
+ class TestBase(abc.ABC):
+ @abc.abstractmethod
+ def abstract1(self): pass
+
+ @abc.abstractmethod
+ def abstract2(self): pass
+
+ def test_it(self): pass
+
+ class TestPartial(TestBase):
+ def abstract1(self): pass
+
+ class TestConcrete(TestPartial):
+ def abstract2(self): pass
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.OK
+ result.assert_outcomes(passed=1)
+
+
+class TestFunction:
+ def test_getmodulecollector(self, pytester: Pytester) -> None:
+ item = pytester.getitem("def test_func(): pass")
+ modcol = item.getparent(pytest.Module)
+ assert isinstance(modcol, pytest.Module)
+ assert hasattr(modcol.obj, "test_func")
+
+ @pytest.mark.filterwarnings("default")
+ def test_function_as_object_instance_ignored(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ class A(object):
+ def __call__(self, tmp_path):
+ 0/0
+
+ test_a = A()
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "collected 0 items",
+ "*test_function_as_object_instance_ignored.py:2: "
+ "*cannot collect 'test_a' because it is not a function.",
+ ]
+ )
+
+ @staticmethod
+ def make_function(pytester: Pytester, **kwargs: Any) -> Any:
+ from _pytest.fixtures import FixtureManager
+
+ config = pytester.parseconfigure()
+ session = Session.from_config(config)
+ session._fixturemanager = FixtureManager(session)
+
+ return pytest.Function.from_parent(parent=session, **kwargs)
+
+ def test_function_equality(self, pytester: Pytester) -> None:
+ def func1():
+ pass
+
+ def func2():
+ pass
+
+ f1 = self.make_function(pytester, name="name", callobj=func1)
+ assert f1 == f1
+ f2 = self.make_function(
+ pytester, name="name", callobj=func2, originalname="foobar"
+ )
+ assert f1 != f2
+
+ def test_repr_produces_actual_test_id(self, pytester: Pytester) -> None:
+ f = self.make_function(
+ pytester, name=r"test[\xe5]", callobj=self.test_repr_produces_actual_test_id
+ )
+ assert repr(f) == r""
+
+ def test_issue197_parametrize_emptyset(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.mark.parametrize('arg', [])
+ def test_function(arg):
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(skipped=1)
+
+ def test_single_tuple_unwraps_values(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.mark.parametrize(('arg',), [(1,)])
+ def test_function(arg):
+ assert arg == 1
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_issue213_parametrize_value_no_equal(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ class A(object):
+ def __eq__(self, other):
+ raise ValueError("not possible")
+ @pytest.mark.parametrize('arg', [A()])
+ def test_function(arg):
+ assert arg.__class__.__name__ == "A"
+ """
+ )
+ reprec = pytester.inline_run("--fulltrace")
+ reprec.assertoutcome(passed=1)
+
+ def test_parametrize_with_non_hashable_values(self, pytester: Pytester) -> None:
+ """Test parametrization with non-hashable values."""
+ pytester.makepyfile(
+ """
+ archival_mapping = {
+ '1.0': {'tag': '1.0'},
+ '1.2.2a1': {'tag': 'release-1.2.2a1'},
+ }
+
+ import pytest
+ @pytest.mark.parametrize('key value'.split(),
+ archival_mapping.items())
+ def test_archival_to_version(key, value):
+ assert key in archival_mapping
+ assert value == archival_mapping[key]
+ """
+ )
+ rec = pytester.inline_run()
+ rec.assertoutcome(passed=2)
+
+ def test_parametrize_with_non_hashable_values_indirect(
+ self, pytester: Pytester
+ ) -> None:
+ """Test parametrization with non-hashable values with indirect parametrization."""
+ pytester.makepyfile(
+ """
+ archival_mapping = {
+ '1.0': {'tag': '1.0'},
+ '1.2.2a1': {'tag': 'release-1.2.2a1'},
+ }
+
+ import pytest
+
+ @pytest.fixture
+ def key(request):
+ return request.param
+
+ @pytest.fixture
+ def value(request):
+ return request.param
+
+ @pytest.mark.parametrize('key value'.split(),
+ archival_mapping.items(), indirect=True)
+ def test_archival_to_version(key, value):
+ assert key in archival_mapping
+ assert value == archival_mapping[key]
+ """
+ )
+ rec = pytester.inline_run()
+ rec.assertoutcome(passed=2)
+
+ def test_parametrize_overrides_fixture(self, pytester: Pytester) -> None:
+ """Test parametrization when parameter overrides existing fixture with same name."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def value():
+ return 'value'
+
+ @pytest.mark.parametrize('value',
+ ['overridden'])
+ def test_overridden_via_param(value):
+ assert value == 'overridden'
+
+ @pytest.mark.parametrize('somevalue', ['overridden'])
+ def test_not_overridden(value, somevalue):
+ assert value == 'value'
+ assert somevalue == 'overridden'
+
+ @pytest.mark.parametrize('other,value', [('foo', 'overridden')])
+ def test_overridden_via_multiparam(other, value):
+ assert other == 'foo'
+ assert value == 'overridden'
+ """
+ )
+ rec = pytester.inline_run()
+ rec.assertoutcome(passed=3)
+
+ def test_parametrize_overrides_parametrized_fixture(
+ self, pytester: Pytester
+ ) -> None:
+ """Test parametrization when parameter overrides existing parametrized fixture with same name."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=[1, 2])
+ def value(request):
+ return request.param
+
+ @pytest.mark.parametrize('value',
+ ['overridden'])
+ def test_overridden_via_param(value):
+ assert value == 'overridden'
+ """
+ )
+ rec = pytester.inline_run()
+ rec.assertoutcome(passed=1)
+
+ def test_parametrize_overrides_parametrized_fixture_with_unrelated_indirect(
+ self, pytester: Pytester
+ ) -> None:
+ """Test parametrization when parameter overrides existing parametrized fixture with same name,
+ and there is an unrelated indirect param.
+
+ Regression test for #13974.
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=["a", "b"])
+ def target(request):
+ return request.param
+
+ @pytest.fixture
+ def val(request):
+ return int(request.param)
+
+ @pytest.mark.parametrize(
+ ["val", "target"],
+ [
+ ("1", 1),
+ ("2", 2),
+ ],
+ indirect=["val"],
+ )
+ def test(val, target):
+ assert val == target
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+ result.assert_outcomes(passed=2)
+
+ def test_parametrize_overrides_indirect_dependency_fixture(
+ self, pytester: Pytester
+ ) -> None:
+ """Test parametrization when parameter overrides a fixture that a test indirectly depends on"""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ fix3_instantiated = False
+
+ @pytest.fixture
+ def fix1(fix2):
+ return fix2 + '1'
+
+ @pytest.fixture
+ def fix2(fix3):
+ return fix3 + '2'
+
+ @pytest.fixture
+ def fix3():
+ global fix3_instantiated
+ fix3_instantiated = True
+ return '3'
+
+ @pytest.mark.parametrize('fix2', ['2'])
+ def test_it(fix1):
+ assert fix1 == '21'
+ assert not fix3_instantiated
+ """
+ )
+ rec = pytester.inline_run()
+ rec.assertoutcome(passed=1)
+
+ def test_parametrize_with_mark(self, pytester: Pytester) -> None:
+ items = pytester.getitems(
+ """
+ import pytest
+ @pytest.mark.foo
+ @pytest.mark.parametrize('arg', [
+ 1,
+ pytest.param(2, marks=[pytest.mark.baz, pytest.mark.bar])
+ ])
+ def test_function(arg):
+ pass
+ """
+ )
+ keywords = [item.keywords for item in items]
+ assert (
+ "foo" in keywords[0]
+ and "bar" not in keywords[0]
+ and "baz" not in keywords[0]
+ )
+ assert "foo" in keywords[1] and "bar" in keywords[1] and "baz" in keywords[1]
+
+ def test_parametrize_with_empty_string_arguments(self, pytester: Pytester) -> None:
+ items = pytester.getitems(
+ """\
+ import pytest
+
+ @pytest.mark.parametrize('v', ('', ' '))
+ @pytest.mark.parametrize('w', ('', ' '))
+ def test(v, w): ...
+ """
+ )
+ names = {item.name for item in items}
+ assert names == {"test[-]", "test[ -]", "test[- ]", "test[ - ]"}
+
+ def test_function_equality_with_callspec(self, pytester: Pytester) -> None:
+ items = pytester.getitems(
+ """
+ import pytest
+ @pytest.mark.parametrize('arg', [1,2])
+ def test_function(arg):
+ pass
+ """
+ )
+ assert items[0] != items[1]
+ assert not (items[0] == items[1])
+
+ def test_pyfunc_call(self, pytester: Pytester) -> None:
+ item = pytester.getitem("def test_func(): raise ValueError")
+ config = item.config
+
+ class MyPlugin1:
+ def pytest_pyfunc_call(self):
+ raise ValueError
+
+ class MyPlugin2:
+ def pytest_pyfunc_call(self):
+ return True
+
+ config.pluginmanager.register(MyPlugin1())
+ config.pluginmanager.register(MyPlugin2())
+ config.hook.pytest_runtest_setup(item=item)
+ config.hook.pytest_pyfunc_call(pyfuncitem=item)
+
+ def test_multiple_parametrize(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ import pytest
+ @pytest.mark.parametrize('x', [0, 1])
+ @pytest.mark.parametrize('y', [2, 3])
+ def test1(x, y):
+ pass
+ """
+ )
+ colitems = modcol.collect()
+ assert colitems[0].name == "test1[2-0]"
+ assert colitems[1].name == "test1[2-1]"
+ assert colitems[2].name == "test1[3-0]"
+ assert colitems[3].name == "test1[3-1]"
+
+ def test_issue751_multiple_parametrize_with_ids(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ import pytest
+ @pytest.mark.parametrize('x', [0], ids=['c'])
+ @pytest.mark.parametrize('y', [0, 1], ids=['a', 'b'])
+ class Test(object):
+ def test1(self, x, y):
+ pass
+ def test2(self, x, y):
+ pass
+ """
+ )
+ colitems = modcol.collect()[0].collect()
+ assert colitems[0].name == "test1[a-c]"
+ assert colitems[1].name == "test1[b-c]"
+ assert colitems[2].name == "test2[a-c]"
+ assert colitems[3].name == "test2[b-c]"
+
+ def test_parametrize_skipif(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ m = pytest.mark.skipif('True')
+
+ @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
+ def test_skip_if(x):
+ assert x < 2
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 2 passed, 1 skipped in *"])
+
+ def test_parametrize_skip(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ m = pytest.mark.skip('')
+
+ @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
+ def test_skip(x):
+ assert x < 2
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 2 passed, 1 skipped in *"])
+
+ def test_parametrize_skipif_no_skip(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ m = pytest.mark.skipif('False')
+
+ @pytest.mark.parametrize('x', [0, 1, m(2)])
+ def test_skipif_no_skip(x):
+ assert x < 2
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 1 failed, 2 passed in *"])
+
+ def test_parametrize_xfail(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ m = pytest.mark.xfail('True')
+
+ @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
+ def test_xfail(x):
+ assert x < 2
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 2 passed, 1 xfailed in *"])
+
+ def test_parametrize_passed(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ m = pytest.mark.xfail('True')
+
+ @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
+ def test_xfail(x):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 2 passed, 1 xpassed in *"])
+
+ def test_parametrize_xfail_passed(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ m = pytest.mark.xfail('False')
+
+ @pytest.mark.parametrize('x', [0, 1, m(2)])
+ def test_passed(x):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 3 passed in *"])
+
+ def test_function_originalname(self, pytester: Pytester) -> None:
+ items = pytester.getitems(
+ """
+ import pytest
+
+ @pytest.mark.parametrize('arg', [1,2])
+ def test_func(arg):
+ pass
+
+ def test_no_param():
+ pass
+ """
+ )
+ originalnames = []
+ for x in items:
+ assert isinstance(x, pytest.Function)
+ originalnames.append(x.originalname)
+ assert originalnames == [
+ "test_func",
+ "test_func",
+ "test_no_param",
+ ]
+
+ def test_function_with_square_brackets(self, pytester: Pytester) -> None:
+ """Check that functions with square brackets don't cause trouble."""
+ p1 = pytester.makepyfile(
+ """
+ locals()["test_foo[name]"] = lambda: None
+ """
+ )
+ result = pytester.runpytest("-v", str(p1))
+ result.stdout.fnmatch_lines(
+ [
+ "test_function_with_square_brackets.py::test_foo[[]name[]] PASSED *",
+ "*= 1 passed in *",
+ ]
+ )
+
+
+class TestSorting:
+ def test_check_equality(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ def test_pass(): pass
+ def test_fail(): assert 0
+ """
+ )
+ fn1 = pytester.collect_by_name(modcol, "test_pass")
+ assert isinstance(fn1, pytest.Function)
+ fn2 = pytester.collect_by_name(modcol, "test_pass")
+ assert isinstance(fn2, pytest.Function)
+
+ assert fn1 == fn2
+ assert fn1 != modcol
+ assert hash(fn1) == hash(fn2)
+
+ fn3 = pytester.collect_by_name(modcol, "test_fail")
+ assert isinstance(fn3, pytest.Function)
+ assert not (fn1 == fn3)
+ assert fn1 != fn3
+
+ for fn in fn1, fn2, fn3:
+ assert fn != 3 # type: ignore[comparison-overlap]
+ assert fn != modcol
+ assert fn != [1, 2, 3] # type: ignore[comparison-overlap]
+ assert [1, 2, 3] != fn # type: ignore[comparison-overlap]
+ assert modcol != fn
+
+ def test_allow_sane_sorting_for_decorators(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ def dec(f):
+ g = lambda: f(2)
+ g.place_as = f
+ return g
+
+
+ def test_b(y):
+ pass
+ test_b = dec(test_b)
+
+ def test_a(y):
+ pass
+ test_a = dec(test_a)
+ """
+ )
+ colitems = modcol.collect()
+ assert len(colitems) == 2
+ assert [item.name for item in colitems] == ["test_b", "test_a"]
+
+ def test_ordered_by_definition_order(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """\
+ class Test1:
+ def test_foo(self): pass
+ def test_bar(self): pass
+ class Test2:
+ def test_foo(self): pass
+ test_bar = Test1.test_bar
+ class Test3(Test2):
+ def test_baz(self): pass
+ """
+ )
+ result = pytester.runpytest("--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ "*Class Test1*",
+ "*Function test_foo*",
+ "*Function test_bar*",
+ "*Class Test2*",
+ # previously the order was flipped due to Test1.test_bar reference
+ "*Function test_foo*",
+ "*Function test_bar*",
+ "*Class Test3*",
+ "*Function test_foo*",
+ "*Function test_bar*",
+ "*Function test_baz*",
+ ]
+ )
+
+
+class TestConftestCustomization:
+ def test_pytest_pycollect_module(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ class MyModule(pytest.Module):
+ pass
+ def pytest_pycollect_makemodule(module_path, parent):
+ if module_path.name == "test_xyz.py":
+ return MyModule.from_parent(path=module_path, parent=parent)
+ """
+ )
+ pytester.makepyfile("def test_some(): pass")
+ pytester.makepyfile(test_xyz="def test_func(): pass")
+ result = pytester.runpytest("--collect-only")
+ result.stdout.fnmatch_lines(["* None:
+ b = pytester.path.joinpath("a", "b")
+ b.mkdir(parents=True)
+ b.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ @pytest.hookimpl(wrapper=True)
+ def pytest_pycollect_makemodule():
+ mod = yield
+ mod.obj.hello = "world"
+ return mod
+ """
+ ),
+ encoding="utf-8",
+ )
+ b.joinpath("test_module.py").write_text(
+ textwrap.dedent(
+ """\
+ def test_hello():
+ assert hello == "world"
+ """
+ ),
+ encoding="utf-8",
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_customized_pymakeitem(self, pytester: Pytester) -> None:
+ b = pytester.path.joinpath("a", "b")
+ b.mkdir(parents=True)
+ b.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ @pytest.hookimpl(wrapper=True)
+ def pytest_pycollect_makeitem():
+ result = yield
+ if result:
+ for func in result:
+ func._some123 = "world"
+ return result
+ """
+ ),
+ encoding="utf-8",
+ )
+ b.joinpath("test_module.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+
+ @pytest.fixture()
+ def obj(request):
+ return request.node._some123
+ def test_hello(obj):
+ assert obj == "world"
+ """
+ ),
+ encoding="utf-8",
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_pytest_pycollect_makeitem(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ class MyFunction(pytest.Function):
+ pass
+ def pytest_pycollect_makeitem(collector, name, obj):
+ if name == "some":
+ return MyFunction.from_parent(name=name, parent=collector)
+ """
+ )
+ pytester.makepyfile("def some(): pass")
+ result = pytester.runpytest("--collect-only")
+ result.stdout.fnmatch_lines(["*MyFunction*some*"])
+
+ def test_issue2369_collect_module_fileext(self, pytester: Pytester) -> None:
+ """Ensure we can collect files with weird file extensions as Python
+ modules (#2369)"""
+ # Implement a little meta path finder to import files containing
+ # Python source code whose file extension is ".narf".
+ pytester.makeconftest(
+ """
+ import sys
+ import os.path
+ from importlib.util import spec_from_loader
+ from importlib.machinery import SourceFileLoader
+ from _pytest.python import Module
+
+ class MetaPathFinder:
+ def find_spec(self, fullname, path, target=None):
+ if os.path.exists(fullname + ".narf"):
+ return spec_from_loader(
+ fullname,
+ SourceFileLoader(fullname, fullname + ".narf"),
+ )
+ sys.meta_path.append(MetaPathFinder())
+
+ def pytest_collect_file(file_path, parent):
+ if file_path.suffix == ".narf":
+ return Module.from_parent(path=file_path, parent=parent)
+ """
+ )
+ pytester.makefile(
+ ".narf",
+ """\
+ def test_something():
+ assert 1 + 1 == 2""",
+ )
+ # Use runpytest_subprocess, since we're futzing with sys.meta_path.
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_early_ignored_attributes(self, pytester: Pytester) -> None:
+ """Builtin attributes should be ignored early on, even if
+ configuration would otherwise allow them.
+
+ This tests a performance optimization, not correctness, really,
+ although it tests PytestCollectionWarning is not raised, while
+ it would have been raised otherwise.
+ """
+ pytester.makeini(
+ """
+ [pytest]
+ python_classes=*
+ python_functions=*
+ """
+ )
+ pytester.makepyfile(
+ """
+ class TestEmpty:
+ pass
+ test_empty = TestEmpty()
+ def test_real():
+ pass
+ """
+ )
+ items, rec = pytester.inline_genitems()
+ assert rec.ret == 0
+ assert len(items) == 1
+
+
+def test_setup_only_available_in_subdir(pytester: Pytester) -> None:
+ sub1 = pytester.mkpydir("sub1")
+ sub2 = pytester.mkpydir("sub2")
+ sub1.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ def pytest_runtest_setup(item):
+ assert item.path.stem == "test_in_sub1"
+ def pytest_runtest_call(item):
+ assert item.path.stem == "test_in_sub1"
+ def pytest_runtest_teardown(item):
+ assert item.path.stem == "test_in_sub1"
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub2.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ def pytest_runtest_setup(item):
+ assert item.path.stem == "test_in_sub2"
+ def pytest_runtest_call(item):
+ assert item.path.stem == "test_in_sub2"
+ def pytest_runtest_teardown(item):
+ assert item.path.stem == "test_in_sub2"
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub1.joinpath("test_in_sub1.py").write_text("def test_1(): pass", encoding="utf-8")
+ sub2.joinpath("test_in_sub2.py").write_text("def test_2(): pass", encoding="utf-8")
+ result = pytester.runpytest("-v", "-s")
+ result.assert_outcomes(passed=2)
+
+
+def test_modulecol_roundtrip(pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol("pass", withinit=False)
+ trail = modcol.nodeid
+ newcol = modcol.session.perform_collect([trail], genitems=0)[0]
+ assert modcol.name == newcol.name
+
+
+class TestTracebackCutting:
+ def test_skip_simple(self):
+ with pytest.raises(pytest.skip.Exception) as excinfo:
+ pytest.skip("xxx")
+ if sys.version_info >= (3, 11):
+ assert excinfo.traceback[-1].frame.code.raw.co_qualname == "_Skip.__call__"
+ assert excinfo.traceback[-1].ishidden(excinfo)
+ assert excinfo.traceback[-2].frame.code.name == "test_skip_simple"
+ assert not excinfo.traceback[-2].ishidden(excinfo)
+
+ def test_traceback_argsetup(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def hello(request):
+ raise ValueError("xyz")
+ """
+ )
+ p = pytester.makepyfile("def test(hello): pass")
+ result = pytester.runpytest(p)
+ assert result.ret != 0
+ out = result.stdout.str()
+ assert "xyz" in out
+ assert "conftest.py:5: ValueError" in out
+ numentries = out.count("_ _ _") # separator for traceback entries
+ assert numentries == 0
+
+ result = pytester.runpytest("--fulltrace", p)
+ out = result.stdout.str()
+ assert "conftest.py:5: ValueError" in out
+ numentries = out.count("_ _ _ _") # separator for traceback entries
+ assert numentries > 3
+
+ def test_traceback_error_during_import(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ x = 1
+ x = 2
+ x = 17
+ asd
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret != 0
+ out = result.stdout.str()
+ assert "x = 1" not in out
+ assert "x = 2" not in out
+ result.stdout.fnmatch_lines([" *asd*", "E*NameError*"])
+ result = pytester.runpytest("--fulltrace")
+ out = result.stdout.str()
+ assert "x = 1" in out
+ assert "x = 2" in out
+ result.stdout.fnmatch_lines([">*asd*", "E*NameError*"])
+
+ def test_traceback_filter_error_during_fixture_collection(
+ self, pytester: Pytester
+ ) -> None:
+ """Integration test for issue #995."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ def fail_me(func):
+ ns = {}
+ exec('def w(): raise ValueError("fail me")', ns)
+ return ns['w']
+
+ @pytest.fixture(scope='class')
+ @fail_me
+ def fail_fixture():
+ pass
+
+ def test_failing_fixture(fail_fixture):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret != 0
+ out = result.stdout.str()
+ assert "INTERNALERROR>" not in out
+ result.stdout.fnmatch_lines(["*ValueError: fail me*", "* 1 error in *"])
+
+ def test_filter_traceback_generated_code(self) -> None:
+ """Test that filter_traceback() works with the fact that
+ _pytest._code.code.Code.path attribute might return an str object.
+
+ In this case, one of the entries on the traceback was produced by
+ dynamically generated code.
+ See: https://bitbucket.org/pytest-dev/py/issues/71
+ This fixes #995.
+ """
+ from _pytest._code import filter_traceback
+
+ tb = None
+ try:
+ ns: dict[str, Any] = {}
+ exec("def foo(): raise ValueError", ns)
+ ns["foo"]()
+ except ValueError:
+ _, _, tb = sys.exc_info()
+
+ assert tb is not None
+ traceback = _pytest._code.Traceback(tb)
+ assert isinstance(traceback[-1].path, str)
+ assert not filter_traceback(traceback[-1])
+
+ def test_filter_traceback_path_no_longer_valid(self, pytester: Pytester) -> None:
+ """Test that filter_traceback() works with the fact that
+ _pytest._code.code.Code.path attribute might return an str object.
+
+ In this case, one of the files in the traceback no longer exists.
+ This fixes #1133.
+ """
+ from _pytest._code import filter_traceback
+
+ pytester.syspathinsert()
+ pytester.makepyfile(
+ filter_traceback_entry_as_str="""
+ def foo():
+ raise ValueError
+ """
+ )
+ tb = None
+ try:
+ import filter_traceback_entry_as_str
+
+ filter_traceback_entry_as_str.foo()
+ except ValueError:
+ _, _, tb = sys.exc_info()
+
+ assert tb is not None
+ pytester.path.joinpath("filter_traceback_entry_as_str.py").unlink()
+ traceback = _pytest._code.Traceback(tb)
+ assert isinstance(traceback[-1].path, str)
+ assert filter_traceback(traceback[-1])
+
+
+class TestReportInfo:
+ def test_itemreport_reportinfo(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ class MyFunction(pytest.Function):
+ def reportinfo(self):
+ return "ABCDE", 42, "custom"
+ def pytest_pycollect_makeitem(collector, name, obj):
+ if name == "test_func":
+ return MyFunction.from_parent(name=name, parent=collector)
+ """
+ )
+ item = pytester.getitem("def test_func(): pass")
+ item.config.pluginmanager.getplugin("runner")
+ assert item.location == ("ABCDE", 42, "custom")
+
+ def test_func_reportinfo(self, pytester: Pytester) -> None:
+ item = pytester.getitem("def test_func(): pass")
+ path, lineno, modpath = item.reportinfo()
+ assert os.fspath(path) == str(item.path)
+ assert lineno == 0
+ assert modpath == "test_func"
+
+ def test_class_reportinfo(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ # lineno 0
+ class TestClass(object):
+ def test_hello(self): pass
+ """
+ )
+ classcol = pytester.collect_by_name(modcol, "TestClass")
+ assert isinstance(classcol, Class)
+ path, lineno, msg = classcol.reportinfo()
+ assert os.fspath(path) == str(modcol.path)
+ assert lineno == 1
+ assert msg == "TestClass"
+
+ @pytest.mark.filterwarnings(
+ "ignore:usage of Generator.Function is deprecated, please use pytest.Function instead"
+ )
+ def test_reportinfo_with_nasty_getattr(self, pytester: Pytester) -> None:
+ # https://github.com/pytest-dev/pytest/issues/1204
+ modcol = pytester.getmodulecol(
+ """
+ # lineno 0
+ class TestClass:
+ def __getattr__(self, name):
+ return "this is not an int"
+
+ def __class_getattr__(cls, name):
+ return "this is not an int"
+
+ def intest_foo(self):
+ pass
+
+ def test_bar(self):
+ pass
+ """
+ )
+ classcol = pytester.collect_by_name(modcol, "TestClass")
+ assert isinstance(classcol, Class)
+ _path, _lineno, _msg = classcol.reportinfo()
+ func = next(iter(classcol.collect()))
+ assert isinstance(func, Function)
+ _path, _lineno, _msg = func.reportinfo()
+
+
+def test_customized_python_discovery(pytester: Pytester) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ python_files=check_*.py
+ python_classes=Check
+ python_functions=check
+ """
+ )
+ p = pytester.makepyfile(
+ """
+ def check_simple():
+ pass
+ class CheckMyApp(object):
+ def check_meth(self):
+ pass
+ """
+ )
+ p2 = p.with_name(p.name.replace("test", "check"))
+ p.rename(p2)
+ result = pytester.runpytest("--collect-only", "-s")
+ result.stdout.fnmatch_lines(
+ ["*check_customized*", "*check_simple*", "*CheckMyApp*", "*check_meth*"]
+ )
+
+ result = pytester.runpytest()
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*2 passed*"])
+
+
+def test_customized_python_discovery_functions(pytester: Pytester) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ python_functions=_test
+ """
+ )
+ pytester.makepyfile(
+ """
+ def _test_underscore():
+ pass
+ """
+ )
+ result = pytester.runpytest("--collect-only", "-s")
+ result.stdout.fnmatch_lines(["*_test_underscore*"])
+
+ result = pytester.runpytest()
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+
+def test_unorderable_types(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ class TestJoinEmpty(object):
+ pass
+
+ def make_test():
+ class Test(object):
+ pass
+ Test.__name__ = "TestFoo"
+ return Test
+ TestFoo = make_test()
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.no_fnmatch_line("*TypeError*")
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+
+
+@pytest.mark.filterwarnings("default::pytest.PytestCollectionWarning")
+def test_dont_collect_non_function_callable(pytester: Pytester) -> None:
+ """Test for issue https://github.com/pytest-dev/pytest/issues/331
+
+ In this case an INTERNALERROR occurred trying to report the failure of
+ a test like this one because pytest failed to get the source lines.
+ """
+ pytester.makepyfile(
+ """
+ class Oh(object):
+ def __call__(self):
+ pass
+
+ test_a = Oh()
+
+ def test_real():
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*collected 1 item*",
+ "*test_dont_collect_non_function_callable.py:2: *cannot collect 'test_a' because it is not a function*",
+ "*1 passed, 1 warning in *",
+ ]
+ )
+
+
+def test_class_injection_does_not_break_collection(pytester: Pytester) -> None:
+ """Tests whether injection during collection time will terminate testing.
+
+ In this case the error should not occur if the TestClass itself
+ is modified during collection time, and the original method list
+ is still used for collection.
+ """
+ pytester.makeconftest(
+ """
+ from test_inject import TestClass
+ def pytest_generate_tests(metafunc):
+ TestClass.changed_var = {}
+ """
+ )
+ pytester.makepyfile(
+ test_inject='''
+ class TestClass(object):
+ def test_injection(self):
+ """Test being parametrized."""
+ pass
+ '''
+ )
+ result = pytester.runpytest()
+ assert (
+ "RuntimeError: dictionary changed size during iteration"
+ not in result.stdout.str()
+ )
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+
+def test_syntax_error_with_non_ascii_chars(pytester: Pytester) -> None:
+ """Fix decoding issue while formatting SyntaxErrors during collection (#578)."""
+ pytester.makepyfile("☃")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*ERROR collecting*", "*SyntaxError*", "*1 error in*"])
+
+
+def test_collect_error_with_fulltrace(pytester: Pytester) -> None:
+ pytester.makepyfile("assert 0")
+ result = pytester.runpytest("--fulltrace")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 0 items / 1 error",
+ "",
+ "*= ERRORS =*",
+ "*_ ERROR collecting test_collect_error_with_fulltrace.py _*",
+ "",
+ "> assert 0",
+ "E assert 0",
+ "",
+ "test_collect_error_with_fulltrace.py:1: AssertionError",
+ "*! Interrupted: 1 error during collection !*",
+ ]
+ )
+
+
+def test_skip_duplicates_by_default(pytester: Pytester) -> None:
+ """Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)
+
+ Ignore duplicate directories.
+ """
+ a = pytester.mkdir("a")
+ fh = a.joinpath("test_a.py")
+ fh.write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ def test_real():
+ pass
+ """
+ ),
+ encoding="utf-8",
+ )
+ result = pytester.runpytest(str(a), str(a))
+ result.stdout.fnmatch_lines(["*collected 1 item*"])
+
+
+def test_keep_duplicates(pytester: Pytester) -> None:
+ """Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)
+
+ Use --keep-duplicates to collect tests from duplicate directories.
+ """
+ a = pytester.mkdir("a")
+ fh = a.joinpath("test_a.py")
+ fh.write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ def test_real():
+ pass
+ """
+ ),
+ encoding="utf-8",
+ )
+ result = pytester.runpytest("--keep-duplicates", str(a), str(a))
+ result.stdout.fnmatch_lines(["*collected 2 item*"])
+
+
+def test_package_collection_infinite_recursion(pytester: Pytester) -> None:
+ pytester.copy_example("collect/package_infinite_recursion")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+
+def test_package_collection_init_given_as_argument(pytester: Pytester) -> None:
+ """Regression test for #3749, #8976, #9263, #9313.
+
+ Specifying an __init__.py file directly should collect only the __init__.py
+ Module, not the entire package.
+ """
+ p = pytester.copy_example("collect/package_init_given_as_arg")
+ items, _hookrecorder = pytester.inline_genitems(p / "pkg" / "__init__.py")
+ assert len(items) == 1
+ assert items[0].name == "test_init"
+
+
+def test_package_with_modules(pytester: Pytester) -> None:
+ """
+ .
+ └── root
+ ├── __init__.py
+ ├── sub1
+ │ ├── __init__.py
+ │ └── sub1_1
+ │ ├── __init__.py
+ │ └── test_in_sub1.py
+ └── sub2
+ └── test
+ └── test_in_sub2.py
+
+ """
+ root = pytester.mkpydir("root")
+ sub1 = root.joinpath("sub1")
+ sub1_test = sub1.joinpath("sub1_1")
+ sub1_test.mkdir(parents=True)
+ for d in (sub1, sub1_test):
+ d.joinpath("__init__.py").touch()
+
+ sub2 = root.joinpath("sub2")
+ sub2_test = sub2.joinpath("test")
+ sub2_test.mkdir(parents=True)
+
+ sub1_test.joinpath("test_in_sub1.py").write_text(
+ "def test_1(): pass", encoding="utf-8"
+ )
+ sub2_test.joinpath("test_in_sub2.py").write_text(
+ "def test_2(): pass", encoding="utf-8"
+ )
+
+ # Execute from .
+ result = pytester.runpytest("-v", "-s")
+ result.assert_outcomes(passed=2)
+
+ # Execute from . with one argument "root"
+ result = pytester.runpytest("-v", "-s", "root")
+ result.assert_outcomes(passed=2)
+
+ # Chdir into package's root and execute with no args
+ os.chdir(root)
+ result = pytester.runpytest("-v", "-s")
+ result.assert_outcomes(passed=2)
+
+
+def test_package_ordering(pytester: Pytester) -> None:
+ """
+ .
+ └── root
+ ├── Test_root.py
+ ├── __init__.py
+ ├── sub1
+ │ ├── Test_sub1.py
+ │ └── __init__.py
+ └── sub2
+ └── test
+ └── test_sub2.py
+
+ """
+ pytester.makeini(
+ """
+ [pytest]
+ python_files=*.py
+ """
+ )
+ root = pytester.mkpydir("root")
+ sub1 = root.joinpath("sub1")
+ sub1.mkdir()
+ sub1.joinpath("__init__.py").touch()
+ sub2 = root.joinpath("sub2")
+ sub2_test = sub2.joinpath("test")
+ sub2_test.mkdir(parents=True)
+
+ root.joinpath("Test_root.py").write_text("def test_1(): pass", encoding="utf-8")
+ sub1.joinpath("Test_sub1.py").write_text("def test_2(): pass", encoding="utf-8")
+ sub2_test.joinpath("test_sub2.py").write_text(
+ "def test_3(): pass", encoding="utf-8"
+ )
+
+ # Execute from .
+ result = pytester.runpytest("-v", "-s")
+ result.assert_outcomes(passed=3)
+
+
+def test_collection_hierarchy(pytester: Pytester) -> None:
+ """A general test checking that a filesystem hierarchy is collected as
+ expected in various scenarios.
+
+ top/
+ ├── aaa
+ │ ├── pkg
+ │ │ ├── __init__.py
+ │ │ └── test_pkg.py
+ │ └── test_aaa.py
+ ├── test_a.py
+ ├── test_b
+ │ ├── __init__.py
+ │ └── test_b.py
+ ├── test_c.py
+ └── zzz
+ ├── dir
+ │ └── test_dir.py
+ ├── __init__.py
+ └── test_zzz.py
+ """
+ pytester.makepyfile(
+ **{
+ "top/aaa/test_aaa.py": "def test_it(): pass",
+ "top/aaa/pkg/__init__.py": "",
+ "top/aaa/pkg/test_pkg.py": "def test_it(): pass",
+ "top/test_a.py": "def test_it(): pass",
+ "top/test_b/__init__.py": "",
+ "top/test_b/test_b.py": "def test_it(): pass",
+ "top/test_c.py": "def test_it(): pass",
+ "top/zzz/__init__.py": "",
+ "top/zzz/test_zzz.py": "def test_it(): pass",
+ "top/zzz/dir/test_dir.py": "def test_it(): pass",
+ }
+ )
+
+ full = [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ ]
+ result = pytester.runpytest("--collect-only")
+ result.stdout.fnmatch_lines(full, consecutive=True)
+ result = pytester.runpytest("top", "--collect-only")
+ result.stdout.fnmatch_lines(full, consecutive=True)
+ result = pytester.runpytest("top", "top", "--collect-only")
+ result.stdout.fnmatch_lines(full, consecutive=True)
+
+ result = pytester.runpytest(
+ "top/aaa", "top/aaa/pkg", "--collect-only", "--keep-duplicates"
+ )
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ ],
+ consecutive=True,
+ )
+
+ result = pytester.runpytest(
+ "top/aaa/pkg", "top/aaa", "--collect-only", "--keep-duplicates"
+ )
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ ],
+ consecutive=True,
+ )
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/fixtures.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/fixtures.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0f2981e1baf9c9c93504db955e9540d35815228
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/fixtures.py
@@ -0,0 +1,5653 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from itertools import zip_longest
+import os
+from pathlib import Path
+import sys
+import textwrap
+
+from _pytest.compat import getfuncargnames
+from _pytest.config import ExitCode
+from _pytest.fixtures import deduplicate_names
+from _pytest.fixtures import TopRequest
+from _pytest.monkeypatch import MonkeyPatch
+from _pytest.pytester import get_public_names
+from _pytest.pytester import Pytester
+from _pytest.python import Function
+import pytest
+
+
+def test_getfuncargnames_functions():
+ """Test getfuncargnames for normal functions"""
+
+ def f():
+ raise NotImplementedError()
+
+ assert not getfuncargnames(f)
+
+ def g(arg):
+ raise NotImplementedError()
+
+ assert getfuncargnames(g) == ("arg",)
+
+ def h(arg1, arg2="hello"):
+ raise NotImplementedError()
+
+ assert getfuncargnames(h) == ("arg1",)
+
+ def j(arg1, arg2, arg3="hello"):
+ raise NotImplementedError()
+
+ assert getfuncargnames(j) == ("arg1", "arg2")
+
+
+def test_getfuncargnames_methods():
+ """Test getfuncargnames for normal methods"""
+
+ class A:
+ def f(self, arg1, arg2="hello"):
+ raise NotImplementedError()
+
+ def g(self, /, arg1, arg2="hello"):
+ raise NotImplementedError()
+
+ def h(self, *, arg1, arg2="hello"):
+ raise NotImplementedError()
+
+ def j(self, arg1, *, arg2, arg3="hello"):
+ raise NotImplementedError()
+
+ def k(self, /, arg1, *, arg2, arg3="hello"):
+ raise NotImplementedError()
+
+ assert getfuncargnames(A().f) == ("arg1",)
+ assert getfuncargnames(A().g) == ("arg1",)
+ assert getfuncargnames(A().h) == ("arg1",)
+ assert getfuncargnames(A().j) == ("arg1", "arg2")
+ assert getfuncargnames(A().k) == ("arg1", "arg2")
+
+
+def test_getfuncargnames_staticmethod():
+ """Test getfuncargnames for staticmethods"""
+
+ class A:
+ @staticmethod
+ def static(arg1, arg2, x=1):
+ raise NotImplementedError()
+
+ assert getfuncargnames(A.static, cls=A) == ("arg1", "arg2")
+
+
+def test_getfuncargnames_staticmethod_inherited() -> None:
+ """Test getfuncargnames for inherited staticmethods (#8061)"""
+
+ class A:
+ @staticmethod
+ def static(arg1, arg2, x=1):
+ raise NotImplementedError()
+
+ class B(A):
+ pass
+
+ assert getfuncargnames(B.static, cls=B) == ("arg1", "arg2")
+
+
+@pytest.mark.skipif(
+ sys.version_info >= (3, 13),
+ reason="""\
+In python 3.13, this will raise FutureWarning:
+functools.partial will be a method descriptor in future Python versions;
+wrap it in staticmethod() if you want to preserve the old behavior
+
+But the wrapped 'functools.partial' is tested by 'test_getfuncargnames_staticmethod_partial' below.
+""",
+)
+def test_getfuncargnames_partial():
+ """Check getfuncargnames for methods defined with functools.partial (#5701)"""
+ import functools
+
+ def check(arg1, arg2, i):
+ raise NotImplementedError()
+
+ class T:
+ test_ok = functools.partial(check, i=2)
+
+ values = getfuncargnames(T().test_ok, name="test_ok")
+ assert values == ("arg1", "arg2")
+
+
+def test_getfuncargnames_staticmethod_partial():
+ """Check getfuncargnames for staticmethods defined with functools.partial (#5701)"""
+ import functools
+
+ def check(arg1, arg2, i):
+ raise NotImplementedError()
+
+ class T:
+ test_ok = staticmethod(functools.partial(check, i=2))
+
+ values = getfuncargnames(T().test_ok, name="test_ok")
+ assert values == ("arg1", "arg2")
+
+
+@pytest.mark.pytester_example_path("fixtures/fill_fixtures")
+class TestFillFixtures:
+ def test_funcarg_lookupfails(self, pytester: Pytester) -> None:
+ pytester.copy_example()
+ result = pytester.runpytest() # "--collect-only")
+ assert result.ret != 0
+ result.stdout.fnmatch_lines(
+ """
+ *def test_func(some)*
+ *fixture*some*not found*
+ *xyzsomething*
+ """
+ )
+
+ def test_detect_recursive_dependency_error(self, pytester: Pytester) -> None:
+ pytester.copy_example()
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ ["*recursive dependency involving fixture 'fix1' detected*"]
+ )
+
+ def test_funcarg_basic(self, pytester: Pytester) -> None:
+ pytester.copy_example()
+ item = pytester.getitem(Path("test_funcarg_basic.py"))
+ assert isinstance(item, Function)
+ # Execute's item's setup, which fills fixtures.
+ item.session._setupstate.setup(item)
+ del item.funcargs["request"]
+ assert len(get_public_names(item.funcargs)) == 2
+ assert item.funcargs["some"] == "test_func"
+ assert item.funcargs["other"] == 42
+
+ def test_funcarg_lookup_modulelevel(self, pytester: Pytester) -> None:
+ pytester.copy_example()
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_funcarg_lookup_classlevel(self, pytester: Pytester) -> None:
+ p = pytester.copy_example()
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_conftest_funcargs_only_available_in_subdir(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.copy_example()
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=2)
+
+ def test_extend_fixture_module_class(self, pytester: Pytester) -> None:
+ testfile = pytester.copy_example()
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+ result = pytester.runpytest(testfile)
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_extend_fixture_conftest_module(self, pytester: Pytester) -> None:
+ p = pytester.copy_example()
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+ result = pytester.runpytest(str(next(Path(str(p)).rglob("test_*.py"))))
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_extend_fixture_conftest_conftest(self, pytester: Pytester) -> None:
+ p = pytester.copy_example()
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+ result = pytester.runpytest(str(next(Path(str(p)).rglob("test_*.py"))))
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_extend_fixture_conftest_plugin(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ testplugin="""
+ import pytest
+
+ @pytest.fixture
+ def foo():
+ return 7
+ """
+ )
+ pytester.syspathinsert()
+ pytester.makeconftest(
+ """
+ import pytest
+
+ pytest_plugins = 'testplugin'
+
+ @pytest.fixture
+ def foo(foo):
+ return foo + 7
+ """
+ )
+ pytester.makepyfile(
+ """
+ def test_foo(foo):
+ assert foo == 14
+ """
+ )
+ result = pytester.runpytest("-s")
+ assert result.ret == 0
+
+ def test_extend_fixture_plugin_plugin(self, pytester: Pytester) -> None:
+ # Two plugins should extend each order in loading order
+ pytester.makepyfile(
+ testplugin0="""
+ import pytest
+
+ @pytest.fixture
+ def foo():
+ return 7
+ """
+ )
+ pytester.makepyfile(
+ testplugin1="""
+ import pytest
+
+ @pytest.fixture
+ def foo(foo):
+ return foo + 7
+ """
+ )
+ pytester.syspathinsert()
+ pytester.makepyfile(
+ """
+ pytest_plugins = ['testplugin0', 'testplugin1']
+
+ def test_foo(foo):
+ assert foo == 14
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_override_parametrized_fixture_conftest_module(
+ self, pytester: Pytester
+ ) -> None:
+ """Test override of the parametrized fixture with non-parametrized one on the test module level."""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(params=[1, 2, 3])
+ def spam(request):
+ return request.param
+ """
+ )
+ testfile = pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def spam():
+ return 'spam'
+
+ def test_spam(spam):
+ assert spam == 'spam'
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+ result = pytester.runpytest(testfile)
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_override_parametrized_fixture_conftest_conftest(
+ self, pytester: Pytester
+ ) -> None:
+ """Test override of the parametrized fixture with non-parametrized one on the conftest level."""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(params=[1, 2, 3])
+ def spam(request):
+ return request.param
+ """
+ )
+ subdir = pytester.mkpydir("subdir")
+ subdir.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+
+ @pytest.fixture
+ def spam():
+ return 'spam'
+ """
+ ),
+ encoding="utf-8",
+ )
+ testfile = subdir.joinpath("test_spam.py")
+ testfile.write_text(
+ textwrap.dedent(
+ """\
+ def test_spam(spam):
+ assert spam == "spam"
+ """
+ ),
+ encoding="utf-8",
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+ result = pytester.runpytest(testfile)
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_override_non_parametrized_fixture_conftest_module(
+ self, pytester: Pytester
+ ) -> None:
+ """Test override of the non-parametrized fixture with parametrized one on the test module level."""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def spam():
+ return 'spam'
+ """
+ )
+ testfile = pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=[1, 2, 3])
+ def spam(request):
+ return request.param
+
+ params = {'spam': 1}
+
+ def test_spam(spam):
+ assert spam == params['spam']
+ params['spam'] += 1
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*3 passed*"])
+ result = pytester.runpytest(testfile)
+ result.stdout.fnmatch_lines(["*3 passed*"])
+
+ def test_override_non_parametrized_fixture_conftest_conftest(
+ self, pytester: Pytester
+ ) -> None:
+ """Test override of the non-parametrized fixture with parametrized one on the conftest level."""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def spam():
+ return 'spam'
+ """
+ )
+ subdir = pytester.mkpydir("subdir")
+ subdir.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+
+ @pytest.fixture(params=[1, 2, 3])
+ def spam(request):
+ return request.param
+ """
+ ),
+ encoding="utf-8",
+ )
+ testfile = subdir.joinpath("test_spam.py")
+ testfile.write_text(
+ textwrap.dedent(
+ """\
+ params = {'spam': 1}
+
+ def test_spam(spam):
+ assert spam == params['spam']
+ params['spam'] += 1
+ """
+ ),
+ encoding="utf-8",
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*3 passed*"])
+ result = pytester.runpytest(testfile)
+ result.stdout.fnmatch_lines(["*3 passed*"])
+
+ def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(
+ self, pytester: Pytester
+ ) -> None:
+ """Test override of the autouse fixture with parametrized one on the conftest level.
+ This test covers the issue explained in issue 1601
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(autouse=True)
+ def spam():
+ return 'spam'
+ """
+ )
+ subdir = pytester.mkpydir("subdir")
+ subdir.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+
+ @pytest.fixture(params=[1, 2, 3])
+ def spam(request):
+ return request.param
+ """
+ ),
+ encoding="utf-8",
+ )
+ testfile = subdir.joinpath("test_spam.py")
+ testfile.write_text(
+ textwrap.dedent(
+ """\
+ params = {'spam': 1}
+
+ def test_spam(spam):
+ assert spam == params['spam']
+ params['spam'] += 1
+ """
+ ),
+ encoding="utf-8",
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*3 passed*"])
+ result = pytester.runpytest(testfile)
+ result.stdout.fnmatch_lines(["*3 passed*"])
+
+ def test_override_fixture_reusing_super_fixture_parametrization(
+ self, pytester: Pytester
+ ) -> None:
+ """Override a fixture at a lower level, reusing the higher-level fixture that
+ is parametrized (#1953).
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(params=[1, 2])
+ def foo(request):
+ return request.param
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def foo(foo):
+ return foo * 2
+
+ def test_spam(foo):
+ assert foo in (2, 4)
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*2 passed*"])
+
+ def test_override_parametrize_fixture_and_indirect(
+ self, pytester: Pytester
+ ) -> None:
+ """Override a fixture at a lower level, reusing the higher-level fixture that
+ is parametrized, while also using indirect parametrization.
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(params=[1, 2])
+ def foo(request):
+ return request.param
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def foo(foo):
+ return foo * 2
+
+ @pytest.fixture
+ def bar(request):
+ return request.param * 100
+
+ @pytest.mark.parametrize("bar", [42], indirect=True)
+ def test_spam(bar, foo):
+ assert bar == 4200
+ assert foo in (2, 4)
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*2 passed*"])
+
+ def test_override_top_level_fixture_reusing_super_fixture_parametrization(
+ self, pytester: Pytester
+ ) -> None:
+ """Same as the above test, but with another level of overwriting."""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(params=['unused', 'unused'])
+ def foo(request):
+ return request.param
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=[1, 2])
+ def foo(request):
+ return request.param
+
+ class Test:
+
+ @pytest.fixture
+ def foo(self, foo):
+ return foo * 2
+
+ def test_spam(self, foo):
+ assert foo in (2, 4)
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*2 passed*"])
+
+ def test_override_parametrized_fixture_with_new_parametrized_fixture(
+ self, pytester: Pytester
+ ) -> None:
+ """Overriding a parametrized fixture, while also parametrizing the new fixture and
+ simultaneously requesting the overwritten fixture as parameter, yields the same value
+ as ``request.param``.
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(params=['ignored', 'ignored'])
+ def foo(request):
+ return request.param
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=[10, 20])
+ def foo(foo, request):
+ assert request.param == foo
+ return foo * 2
+
+ def test_spam(foo):
+ assert foo in (20, 40)
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*2 passed*"])
+
+ @pytest.mark.xfail(reason="not handled currently")
+ def test_override_parametrized_fixture_via_transitive_fixture(
+ self, pytester: Pytester
+ ) -> None:
+ """Test that overriding a parametrized fixture works even the super
+ fixture is requested only transitively.
+
+ Regression test for #7737.
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=[1, 2])
+ def foo(request):
+ return request.param
+
+ @pytest.fixture
+ def bar(foo):
+ return foo
+
+ class TestIt:
+ @pytest.fixture
+ def foo(self, bar):
+ return bar * 2
+
+ def test_it(self, foo):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.OK
+ result.assert_outcomes(passed=2)
+
+ def test_autouse_fixture_plugin(self, pytester: Pytester) -> None:
+ # A fixture from a plugin has no baseid set, which screwed up
+ # the autouse fixture handling.
+ pytester.makepyfile(
+ testplugin="""
+ import pytest
+
+ @pytest.fixture(autouse=True)
+ def foo(request):
+ request.function.foo = 7
+ """
+ )
+ pytester.syspathinsert()
+ pytester.makepyfile(
+ """
+ pytest_plugins = 'testplugin'
+
+ def test_foo(request):
+ assert request.function.foo == 7
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_funcarg_lookup_error(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def a_fixture(): pass
+
+ @pytest.fixture
+ def b_fixture(): pass
+
+ @pytest.fixture
+ def c_fixture(): pass
+
+ @pytest.fixture
+ def d_fixture(): pass
+ """
+ )
+ pytester.makepyfile(
+ """
+ def test_lookup_error(unknown):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*ERROR at setup of test_lookup_error*",
+ " def test_lookup_error(unknown):*",
+ "E fixture 'unknown' not found",
+ "> available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*",
+ # sorted
+ "> use 'py*test --fixtures *' for help on them.",
+ "*1 error*",
+ ]
+ )
+ result.stdout.no_fnmatch_line("*INTERNAL*")
+
+ def test_fixture_excinfo_leak(self, pytester: Pytester) -> None:
+ # on python2 sys.excinfo would leak into fixture executions
+ pytester.makepyfile(
+ """
+ import sys
+ import traceback
+ import pytest
+
+ @pytest.fixture
+ def leak():
+ if sys.exc_info()[0]: # python3 bug :)
+ traceback.print_exc()
+ #fails
+ assert sys.exc_info() == (None, None, None)
+
+ def test_leak(leak):
+ if sys.exc_info()[0]: # python3 bug :)
+ traceback.print_exc()
+ assert sys.exc_info() == (None, None, None)
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+
+class TestRequestBasic:
+ def test_request_attributes(self, pytester: Pytester) -> None:
+ item = pytester.getitem(
+ """
+ import pytest
+
+ @pytest.fixture
+ def something(request): pass
+ def test_func(something): pass
+ """
+ )
+ assert isinstance(item, Function)
+ req = TopRequest(item, _ispytest=True)
+ assert req.function == item.obj
+ assert req.keywords == item.keywords
+ assert hasattr(req.module, "test_func")
+ assert req.cls is None
+ assert req.function.__name__ == "test_func"
+ assert req.config == item.config
+ assert repr(req).find(req.function.__name__) != -1
+
+ def test_request_attributes_method(self, pytester: Pytester) -> None:
+ (item,) = pytester.getitems(
+ """
+ import pytest
+ class TestB(object):
+
+ @pytest.fixture
+ def something(self, request):
+ return 1
+ def test_func(self, something):
+ pass
+ """
+ )
+ assert isinstance(item, Function)
+ req = item._request
+ assert req.cls.__name__ == "TestB"
+ assert req.instance.__class__ == req.cls
+
+ def test_request_contains_funcarg_arg2fixturedefs(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ import pytest
+ @pytest.fixture
+ def something(request):
+ pass
+ class TestClass(object):
+ def test_method(self, something):
+ pass
+ """
+ )
+ (item1,) = pytester.genitems([modcol])
+ assert isinstance(item1, Function)
+ assert item1.name == "test_method"
+ arg2fixturedefs = TopRequest(item1, _ispytest=True)._arg2fixturedefs
+ assert len(arg2fixturedefs) == 1
+ assert arg2fixturedefs["something"][0].argname == "something"
+
+ @pytest.mark.skipif(
+ hasattr(sys, "pypy_version_info"),
+ reason="this method of test doesn't work on pypy",
+ )
+ def test_request_garbage(self, pytester: Pytester) -> None:
+ try:
+ import xdist # noqa: F401
+ except ImportError:
+ pass
+ else:
+ pytest.xfail("this test is flaky when executed with xdist")
+ pytester.makepyfile(
+ """
+ import sys
+ import pytest
+ from _pytest.fixtures import RequestFixtureDef
+ import gc
+
+ @pytest.fixture(autouse=True)
+ def something(request):
+ original = gc.get_debug()
+ gc.set_debug(gc.DEBUG_SAVEALL)
+ gc.collect()
+
+ yield
+
+ try:
+ gc.collect()
+ leaked = [x for _ in gc.garbage if isinstance(_, RequestFixtureDef)]
+ assert leaked == []
+ finally:
+ gc.set_debug(original)
+
+ def test_func():
+ pass
+ """
+ )
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(["* 1 passed in *"])
+
+ def test_getfixturevalue_recursive(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def something(request):
+ return 1
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def something(request):
+ return request.getfixturevalue("something") + 1
+ def test_func(something):
+ assert something == 2
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_getfixturevalue_teardown(self, pytester: Pytester) -> None:
+ """
+ Issue #1895
+
+ `test_inner` requests `inner` fixture, which in turn requests `resource`
+ using `getfixturevalue`. `test_func` then requests `resource`.
+
+ `resource` is teardown before `inner` because the fixture mechanism won't consider
+ `inner` dependent on `resource` when it is used via `getfixturevalue`: `test_func`
+ will then cause the `resource`'s finalizer to be called first because of this.
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope='session')
+ def resource():
+ r = ['value']
+ yield r
+ r.pop()
+
+ @pytest.fixture(scope='session')
+ def inner(request):
+ resource = request.getfixturevalue('resource')
+ assert resource == ['value']
+ yield
+ assert resource == ['value']
+
+ def test_inner(inner):
+ pass
+
+ def test_func(resource):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 2 passed in *"])
+
+ def test_getfixturevalue_teardown_previously_requested_does_not_warn(
+ self, pytester: Pytester
+ ) -> None:
+ """Test that requesting a fixture during teardown that was previously
+ requested is OK (#12882).
+
+ Note: this is still kinda dubious so don't let this test lock you in to
+ allowing this behavior forever...
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def fix(request, tmp_path):
+ yield
+ assert request.getfixturevalue("tmp_path") == tmp_path
+
+ def test_it(fix):
+ pass
+ """
+ )
+ result = pytester.runpytest("-Werror")
+ result.assert_outcomes(passed=1)
+
+ def test_getfixturevalue_teardown_new_fixture_deprecated(
+ self, pytester: Pytester
+ ) -> None:
+ """Test that requesting a fixture during teardown that was not
+ previously requested raises a deprecation warning (#12882).
+
+ Note: this is a case that previously worked but will become a hard
+ error after the deprecation is completed.
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope="session")
+ def resource():
+ return "value"
+
+ @pytest.fixture
+ def fix(request):
+ yield
+ with pytest.warns(
+ pytest.PytestRemovedIn10Warning,
+ match=r'Calling request\\.getfixturevalue\\("resource"\\) during teardown is deprecated',
+ ):
+ assert request.getfixturevalue("resource") == "value"
+
+ def test_it(fix):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+
+ def test_getfixturevalue_teardown_new_inactive_fixture_errors(
+ self, pytester: Pytester
+ ) -> None:
+ """Test that requesting a fixture during teardown that was not
+ previously requested raises an error (#12882)."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def fix(request):
+ yield
+ request.getfixturevalue("tmp_path")
+
+ def test_it(fix):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1, errors=1)
+ result.stdout.fnmatch_lines(
+ [
+ (
+ '*The fixture value for "tmp_path" is not available during '
+ "teardown because it was not previously requested.*"
+ ),
+ ]
+ )
+
+ def test_getfixturevalue_teardown_new_inactive_fixture_errors_top_request(
+ self, pytester: Pytester
+ ) -> None:
+ """Test that requesting a fixture during teardown that was not
+ previously requested raises an error (tricky case) (#12882)."""
+ pytester.makepyfile(
+ """
+ def test_it(request):
+ request.addfinalizer(lambda: request.getfixturevalue("tmp_path"))
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1, errors=1)
+ result.stdout.fnmatch_lines(
+ [
+ (
+ '*The fixture value for "tmp_path" is not available during '
+ "teardown because it was not previously requested.*"
+ ),
+ ]
+ )
+
+ def test_getfixturevalue(self, pytester: Pytester) -> None:
+ item = pytester.getitem(
+ """
+ import pytest
+
+ @pytest.fixture
+ def something(request):
+ return 1
+
+ values = [2]
+ @pytest.fixture
+ def other(request):
+ return values.pop()
+
+ def test_func(something): pass
+ """
+ )
+ assert isinstance(item, Function)
+ req = item._request
+
+ # Execute item's setup.
+ item.session._setupstate.setup(item)
+
+ with pytest.raises(pytest.FixtureLookupError):
+ req.getfixturevalue("notexists")
+ val = req.getfixturevalue("something")
+ assert val == 1
+ val = req.getfixturevalue("something")
+ assert val == 1
+ val2 = req.getfixturevalue("other")
+ assert val2 == 2
+ val2 = req.getfixturevalue("other") # see about caching
+ assert val2 == 2
+ assert item.funcargs["something"] == 1
+ assert len(get_public_names(item.funcargs)) == 2
+ assert "request" in item.funcargs
+
+ def test_request_addfinalizer(self, pytester: Pytester) -> None:
+ item = pytester.getitem(
+ """
+ import pytest
+ teardownlist = []
+ @pytest.fixture
+ def something(request):
+ request.addfinalizer(lambda: teardownlist.append(1))
+ def test_func(something): pass
+ """
+ )
+ assert isinstance(item, Function)
+ item.session._setupstate.setup(item)
+ item._request._fillfixtures()
+ # successively check finalization calls
+ parent = item.getparent(pytest.Module)
+ assert parent is not None
+ teardownlist = parent.obj.teardownlist
+ ss = item.session._setupstate
+ assert not teardownlist
+ ss.teardown_exact(None)
+ print(ss.stack)
+ assert teardownlist == [1]
+
+ def test_request_addfinalizer_failing_setup(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = [1]
+ @pytest.fixture
+ def myfix(request):
+ request.addfinalizer(values.pop)
+ assert 0
+ def test_fix(myfix):
+ pass
+ def test_finalizer_ran():
+ assert not values
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(failed=1, passed=1)
+
+ def test_request_addfinalizer_failing_setup_module(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = [1, 2]
+ @pytest.fixture(scope="module")
+ def myfix(request):
+ request.addfinalizer(values.pop)
+ request.addfinalizer(values.pop)
+ assert 0
+ def test_fix(myfix):
+ pass
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ mod = reprec.getcalls("pytest_runtest_setup")[0].item.module
+ assert not mod.values
+
+ def test_request_addfinalizer_partial_setup_failure(
+ self, pytester: Pytester
+ ) -> None:
+ p = pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture
+ def something(request):
+ request.addfinalizer(lambda: values.append(None))
+ def test_func(something, missingarg):
+ pass
+ def test_second():
+ assert len(values) == 1
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(
+ ["*1 error*"] # XXX the whole module collection fails
+ )
+
+ def test_request_subrequest_addfinalizer_exceptions(
+ self, pytester: Pytester
+ ) -> None:
+ """
+ Ensure exceptions raised during teardown by finalizers are suppressed
+ until all finalizers are called, then re-raised together in an
+ exception group (#2440)
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ def _excepts(where):
+ raise Exception('Error in %s fixture' % where)
+ @pytest.fixture
+ def subrequest(request):
+ return request
+ @pytest.fixture
+ def something(subrequest):
+ subrequest.addfinalizer(lambda: values.append(1))
+ subrequest.addfinalizer(lambda: values.append(2))
+ subrequest.addfinalizer(lambda: _excepts('something'))
+ @pytest.fixture
+ def excepts(subrequest):
+ subrequest.addfinalizer(lambda: _excepts('excepts'))
+ subrequest.addfinalizer(lambda: values.append(3))
+ def test_first(something, excepts):
+ pass
+ def test_second():
+ assert values == [3, 2, 1]
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=2, errors=1)
+ result.stdout.fnmatch_lines(
+ [
+ ' | *ExceptionGroup: errors while tearing down fixture "subrequest" of (2 sub-exceptions)', # noqa: E501
+ " +-+---------------- 1 ----------------",
+ " | Exception: Error in something fixture",
+ " +---------------- 2 ----------------",
+ " | Exception: Error in excepts fixture",
+ " +------------------------------------",
+ ],
+ )
+
+ def test_request_getmodulepath(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol("def test_somefunc(): pass")
+ (item,) = pytester.genitems([modcol])
+ assert isinstance(item, Function)
+ req = TopRequest(item, _ispytest=True)
+ assert req.path == modcol.path
+
+ def test_request_fixturenames(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ from _pytest.pytester import get_public_names
+ @pytest.fixture()
+ def arg1():
+ pass
+ @pytest.fixture()
+ def farg(arg1):
+ pass
+ @pytest.fixture(autouse=True)
+ def sarg(tmp_path):
+ pass
+ def test_function(request, farg):
+ assert set(get_public_names(request.fixturenames)) == \
+ set(["sarg", "arg1", "request", "farg",
+ "tmp_path", "tmp_path_factory"])
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_request_fixturenames_dynamic_fixture(self, pytester: Pytester) -> None:
+ """Regression test for #3057"""
+ pytester.copy_example("fixtures/test_getfixturevalue_dynamic.py")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_setupdecorator_and_xunit(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(scope='module', autouse=True)
+ def setup_module():
+ values.append("module")
+ @pytest.fixture(autouse=True)
+ def setup_function():
+ values.append("function")
+
+ def test_func():
+ pass
+
+ class TestClass(object):
+ @pytest.fixture(scope="class", autouse=True)
+ def setup_class(self):
+ values.append("class")
+ @pytest.fixture(autouse=True)
+ def setup_method(self):
+ values.append("method")
+ def test_method(self):
+ pass
+ def test_all():
+ assert values == ["module", "function", "class",
+ "function", "method", "function"]
+ """
+ )
+ reprec = pytester.inline_run("-v")
+ reprec.assertoutcome(passed=3)
+
+ def test_fixtures_sub_subdir_normalize_sep(self, pytester: Pytester) -> None:
+ # this tests that normalization of nodeids takes place
+ b = pytester.path.joinpath("tests", "unit")
+ b.mkdir(parents=True)
+ b.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ @pytest.fixture
+ def arg1():
+ pass
+ """
+ ),
+ encoding="utf-8",
+ )
+ p = b.joinpath("test_module.py")
+ p.write_text("def test_func(arg1): pass", encoding="utf-8")
+ result = pytester.runpytest(p, "--fixtures")
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(
+ """
+ *fixtures defined*conftest*
+ *arg1*
+ """
+ )
+
+ def test_show_fixtures_color_yes(self, pytester: Pytester) -> None:
+ pytester.makepyfile("def test_this(): assert 1")
+ result = pytester.runpytest("--color=yes", "--fixtures")
+ assert "\x1b[32mtmp_path" in result.stdout.str()
+
+ def test_newstyle_with_request(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture()
+ def arg(request):
+ pass
+ def test_1(arg):
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_setupcontext_no_param(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(params=[1,2])
+ def arg(request):
+ return request.param
+
+ @pytest.fixture(autouse=True)
+ def mysetup(request, arg):
+ assert not hasattr(request, "param")
+ def test_1(arg):
+ assert arg in (1,2)
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+
+class TestRequestSessionScoped:
+ @pytest.fixture(scope="session")
+ def session_request(self, request):
+ return request
+
+ @pytest.mark.parametrize("name", ["path", "module"])
+ def test_session_scoped_unavailable_attributes(self, session_request, name):
+ with pytest.raises(
+ AttributeError,
+ match=f"{name} not available in session-scoped context",
+ ):
+ getattr(session_request, name)
+
+
+class TestRequestMarking:
+ def test_applymarker(self, pytester: Pytester) -> None:
+ item1, _item2 = pytester.getitems(
+ """
+ import pytest
+
+ @pytest.fixture
+ def something(request):
+ pass
+ class TestClass(object):
+ def test_func1(self, something):
+ pass
+ def test_func2(self, something):
+ pass
+ """
+ )
+ assert isinstance(item1, Function)
+ req1 = TopRequest(item1, _ispytest=True)
+ assert "xfail" not in item1.keywords
+ req1.applymarker(pytest.mark.xfail)
+ assert "xfail" in item1.keywords
+ assert "skipif" not in item1.keywords
+ req1.applymarker(pytest.mark.skipif)
+ assert "skipif" in item1.keywords
+ with pytest.raises(ValueError):
+ req1.applymarker(42) # type: ignore[arg-type]
+
+ def test_accesskeywords(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture()
+ def keywords(request):
+ return request.keywords
+ @pytest.mark.XYZ
+ def test_function(keywords):
+ assert keywords["XYZ"]
+ assert "abc" not in keywords
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_accessmarker_dynamic(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ @pytest.fixture()
+ def keywords(request):
+ return request.keywords
+
+ @pytest.fixture(scope="class", autouse=True)
+ def marking(request):
+ request.applymarker(pytest.mark.XYZ("hello"))
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+ def test_fun1(keywords):
+ assert keywords["XYZ"] is not None
+ assert "abc" not in keywords
+ def test_fun2(keywords):
+ assert keywords["XYZ"] is not None
+ assert "abc" not in keywords
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+
+class TestFixtureUsages:
+ def test_noargfixturedec(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture
+ def arg1():
+ return 1
+
+ def test_func(arg1):
+ assert arg1 == 1
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_receives_funcargs(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture()
+ def arg1():
+ return 1
+
+ @pytest.fixture()
+ def arg2(arg1):
+ return arg1 + 1
+
+ def test_add(arg2):
+ assert arg2 == 2
+ def test_all(arg1, arg2):
+ assert arg1 == 1
+ assert arg2 == 2
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_receives_funcargs_scope_mismatch(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="function")
+ def arg1():
+ return 1
+
+ @pytest.fixture(scope="module")
+ def arg2(arg1):
+ return arg1 + 1
+
+ def test_add(arg2):
+ assert arg2 == 2
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*ScopeMismatch*Requesting fixture stack*",
+ "test_receives_funcargs_scope_mismatch.py:6: def arg2(arg1)",
+ "Requested fixture:",
+ "test_receives_funcargs_scope_mismatch.py:2: def arg1()",
+ "*1 error*",
+ ]
+ )
+
+ def test_receives_funcargs_scope_mismatch_issue660(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="function")
+ def arg1():
+ return 1
+
+ @pytest.fixture(scope="module")
+ def arg2(arg1):
+ return arg1 + 1
+
+ def test_add(arg1, arg2):
+ assert arg2 == 2
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*ScopeMismatch*Requesting fixture stack*",
+ "* def arg2(arg1)",
+ "Requested fixture:",
+ "* def arg1()",
+ "*1 error*",
+ ],
+ )
+
+ def test_invalid_scope(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="functions")
+ def badscope():
+ pass
+
+ def test_nothing(badscope):
+ pass
+ """
+ )
+ result = pytester.runpytest_inprocess()
+ result.stdout.fnmatch_lines(
+ "*Fixture 'badscope' from test_invalid_scope.py got an unexpected scope value 'functions'"
+ )
+
+ @pytest.mark.parametrize("scope", ["function", "session"])
+ def test_parameters_without_eq_semantics(self, scope, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ f"""
+ class NoEq1: # fails on `a == b` statement
+ def __eq__(self, _):
+ raise RuntimeError
+
+ class NoEq2: # fails on `if a == b:` statement
+ def __eq__(self, _):
+ class NoBool:
+ def __bool__(self):
+ raise RuntimeError
+ return NoBool()
+
+ import pytest
+ @pytest.fixture(params=[NoEq1(), NoEq2()], scope={scope!r})
+ def no_eq(request):
+ return request.param
+
+ def test1(no_eq):
+ pass
+
+ def test2(no_eq):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*4 passed*"])
+
+ def test_funcarg_parametrized_and_used_twice(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(params=[1,2])
+ def arg1(request):
+ values.append(1)
+ return request.param
+
+ @pytest.fixture()
+ def arg2(arg1):
+ return arg1 + 1
+
+ def test_add(arg1, arg2):
+ assert arg2 == arg1 + 1
+ assert len(values) == arg1
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*2 passed*"])
+
+ def test_factory_uses_unknown_funcarg_as_dependency_error(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture()
+ def fail(missing):
+ return
+
+ @pytest.fixture()
+ def call_fail(fail):
+ return
+
+ def test_missing(call_fail):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ """
+ *pytest.fixture()*
+ *def call_fail(fail)*
+ *pytest.fixture()*
+ *def fail*
+ *fixture*'missing'*not found*
+ """
+ )
+
+ def test_factory_setup_as_classes_fails(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ class arg1(object):
+ def __init__(self, request):
+ self.x = 1
+ arg1 = pytest.fixture()(arg1)
+
+ """
+ )
+ reprec = pytester.inline_run()
+ values = reprec.getfailedcollections()
+ assert len(values) == 1
+
+ def test_usefixtures_marker(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ values = []
+
+ @pytest.fixture(scope="class")
+ def myfix(request):
+ request.cls.hello = "world"
+ values.append(1)
+
+ class TestClass(object):
+ def test_one(self):
+ assert self.hello == "world"
+ assert len(values) == 1
+ def test_two(self):
+ assert self.hello == "world"
+ assert len(values) == 1
+ pytest.mark.usefixtures("myfix")(TestClass)
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_empty_usefixtures_marker(self, pytester: Pytester) -> None:
+ """Empty usefixtures() marker issues a warning (#12439)."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.usefixtures()
+ def test_one():
+ assert 1 == 1
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ "*PytestWarning: usefixtures() in test_empty_usefixtures_marker.py::test_one"
+ " without arguments has no effect"
+ )
+
+ def test_usefixtures_ini(self, pytester: Pytester) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ usefixtures = myfix
+ """
+ )
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(scope="class")
+ def myfix(request):
+ request.cls.hello = "world"
+
+ """
+ )
+ pytester.makepyfile(
+ """
+ class TestClass(object):
+ def test_one(self):
+ assert self.hello == "world"
+ def test_two(self):
+ assert self.hello == "world"
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_usefixtures_seen_in_showmarkers(self, pytester: Pytester) -> None:
+ result = pytester.runpytest("--markers")
+ result.stdout.fnmatch_lines(
+ """
+ *usefixtures(fixturename1*mark tests*fixtures*
+ """
+ )
+
+ def test_request_instance_issue203(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ class TestClass(object):
+ @pytest.fixture
+ def setup1(self, request):
+ assert self == request.instance
+ self.arg1 = 1
+ def test_hello(self, setup1):
+ assert self.arg1 == 1
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_fixture_parametrized_with_iterator(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ values = []
+ def f():
+ yield 1
+ yield 2
+ dec = pytest.fixture(scope="module", params=f())
+
+ @dec
+ def arg(request):
+ return request.param
+ @dec
+ def arg2(request):
+ return request.param
+
+ def test_1(arg):
+ values.append(arg)
+ def test_2(arg2):
+ values.append(arg2*10)
+ """
+ )
+ reprec = pytester.inline_run("-v")
+ reprec.assertoutcome(passed=4)
+ values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
+ assert values == [1, 2, 10, 20]
+
+ def test_setup_functions_as_fixtures(self, pytester: Pytester) -> None:
+ """Ensure setup_* methods obey fixture scope rules (#517, #3094)."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ DB_INITIALIZED = None
+
+ @pytest.fixture(scope="session", autouse=True)
+ def db():
+ global DB_INITIALIZED
+ DB_INITIALIZED = True
+ yield
+ DB_INITIALIZED = False
+
+ def setup_module():
+ assert DB_INITIALIZED
+
+ def teardown_module():
+ assert DB_INITIALIZED
+
+ class TestClass(object):
+
+ def setup_method(self, method):
+ assert DB_INITIALIZED
+
+ def teardown_method(self, method):
+ assert DB_INITIALIZED
+
+ def test_printer_1(self):
+ pass
+
+ def test_printer_2(self):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 2 passed in *"])
+
+ def test_parameterized_fixture_caching(self, pytester: Pytester) -> None:
+ """Regression test for #12600."""
+ pytester.makepyfile(
+ """
+ import pytest
+ from itertools import count
+
+ CACHE_MISSES = count(0)
+
+ def pytest_generate_tests(metafunc):
+ if "my_fixture" in metafunc.fixturenames:
+ # Use unique objects for parametrization (as opposed to small strings
+ # and small integers which are singletons).
+ metafunc.parametrize("my_fixture", [[1], [2]], indirect=True)
+
+ @pytest.fixture(scope='session')
+ def my_fixture(request):
+ next(CACHE_MISSES)
+
+ def test1(my_fixture):
+ pass
+
+ def test2(my_fixture):
+ pass
+
+ def teardown_module():
+ assert next(CACHE_MISSES) == 2
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.no_fnmatch_line("* ERROR at teardown *")
+
+ def test_unwrapping_pytest_fixture(self, pytester: Pytester) -> None:
+ """Ensure the unwrap method on `FixtureFunctionDefinition` correctly wraps and unwraps methods and functions"""
+ pytester.makepyfile(
+ """
+ import pytest
+ import inspect
+
+ class FixtureFunctionDefTestClass:
+ def __init__(self) -> None:
+ self.i = 10
+
+ @pytest.fixture
+ def fixture_function_def_test_method(self):
+ return self.i
+
+
+ @pytest.fixture
+ def fixture_function_def_test_func():
+ return 9
+
+
+ def test_get_wrapped_func_returns_method():
+ obj = FixtureFunctionDefTestClass()
+ wrapped_function_result = (
+ obj.fixture_function_def_test_method._get_wrapped_function()
+ )
+ assert inspect.ismethod(wrapped_function_result)
+ assert wrapped_function_result() == 10
+
+
+ def test_get_wrapped_func_returns_function():
+ assert fixture_function_def_test_func._get_wrapped_function()() == 9
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=2)
+
+ def test_fixture_wrapped_looks_liked_wrapped_function(
+ self, pytester: Pytester
+ ) -> None:
+ """Ensure that `FixtureFunctionDefinition` behaves like the function it wrapped."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def fixture_function_def_test_func():
+ return 9
+ fixture_function_def_test_func.__doc__ = "documentation"
+
+ def test_fixture_has_same_doc():
+ assert fixture_function_def_test_func.__doc__ == "documentation"
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+
+
+class TestFixtureManagerParseFactories:
+ @pytest.fixture
+ def pytester(self, pytester: Pytester) -> Pytester:
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def hello(request):
+ return "conftest"
+
+ @pytest.fixture
+ def fm(request):
+ return request._fixturemanager
+
+ @pytest.fixture
+ def item(request):
+ return request._pyfuncitem
+ """
+ )
+ return pytester
+
+ def test_parsefactories_evil_objects_issue214(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ class A(object):
+ def __call__(self):
+ pass
+ def __getattr__(self, name):
+ raise RuntimeError()
+ a = A()
+ def test_hello():
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1, failed=0)
+
+ def test_parsefactories_conftest(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_hello(item, fm):
+ for name in ("fm", "hello", "item"):
+ faclist = fm.getfixturedefs(name, item)
+ assert len(faclist) == 1
+ fac = faclist[0]
+ assert fac.func.__name__ == name
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(passed=1)
+
+ def test_parsefactories_conftest_and_module_and_class(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """\
+ import pytest
+
+ @pytest.fixture
+ def hello(request):
+ return "module"
+ class TestClass(object):
+ @pytest.fixture
+ def hello(self, request):
+ return "class"
+ def test_hello(self, item, fm):
+ faclist = fm.getfixturedefs("hello", item)
+ print(faclist)
+ assert len(faclist) == 3
+
+ assert faclist[0].func(item._request) == "conftest"
+ assert faclist[1].func(item._request) == "module"
+ assert faclist[2].func(item._request) == "class"
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(passed=1)
+
+ def test_parsefactories_relative_node_ids(
+ self, pytester: Pytester, monkeypatch: MonkeyPatch
+ ) -> None:
+ # example mostly taken from:
+ # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html
+ runner = pytester.mkdir("runner")
+ package = pytester.mkdir("package")
+ package.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ @pytest.fixture
+ def one():
+ return 1
+ """
+ ),
+ encoding="utf-8",
+ )
+ package.joinpath("test_x.py").write_text(
+ textwrap.dedent(
+ """\
+ def test_x(one):
+ assert one == 1
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub = package.joinpath("sub")
+ sub.mkdir()
+ sub.joinpath("__init__.py").touch()
+ sub.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ @pytest.fixture
+ def one():
+ return 2
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub.joinpath("test_y.py").write_text(
+ textwrap.dedent(
+ """\
+ def test_x(one):
+ assert one == 2
+ """
+ ),
+ encoding="utf-8",
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+ with monkeypatch.context() as mp:
+ mp.chdir(runner)
+ reprec = pytester.inline_run("..")
+ reprec.assertoutcome(passed=2)
+
+ def test_package_xunit_fixture(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ __init__="""\
+ values = []
+ """
+ )
+ package = pytester.mkdir("package")
+ package.joinpath("__init__.py").write_text(
+ textwrap.dedent(
+ """\
+ from .. import values
+ def setup_module():
+ values.append("package")
+ def teardown_module():
+ values[:] = []
+ """
+ ),
+ encoding="utf-8",
+ )
+ package.joinpath("test_x.py").write_text(
+ textwrap.dedent(
+ """\
+ from .. import values
+ def test_x():
+ assert values == ["package"]
+ """
+ ),
+ encoding="utf-8",
+ )
+ package = pytester.mkdir("package2")
+ package.joinpath("__init__.py").write_text(
+ textwrap.dedent(
+ """\
+ from .. import values
+ def setup_module():
+ values.append("package2")
+ def teardown_module():
+ values[:] = []
+ """
+ ),
+ encoding="utf-8",
+ )
+ package.joinpath("test_x.py").write_text(
+ textwrap.dedent(
+ """\
+ from .. import values
+ def test_x():
+ assert values == ["package2"]
+ """
+ ),
+ encoding="utf-8",
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_package_fixture_complex(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ __init__="""\
+ values = []
+ """
+ )
+ pytester.syspathinsert(pytester.path.name)
+ package = pytester.mkdir("package")
+ package.joinpath("__init__.py").write_text("", encoding="utf-8")
+ package.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ from .. import values
+ @pytest.fixture(scope="package")
+ def one():
+ values.append("package")
+ yield values
+ values.pop()
+ @pytest.fixture(scope="package", autouse=True)
+ def two():
+ values.append("package-auto")
+ yield values
+ values.pop()
+ """
+ ),
+ encoding="utf-8",
+ )
+ package.joinpath("test_x.py").write_text(
+ textwrap.dedent(
+ """\
+ from .. import values
+ def test_package_autouse():
+ assert values == ["package-auto"]
+ def test_package(one):
+ assert values == ["package-auto", "package"]
+ """
+ ),
+ encoding="utf-8",
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_collect_custom_items(self, pytester: Pytester) -> None:
+ pytester.copy_example("fixtures/custom_item")
+ result = pytester.runpytest("foo")
+ result.stdout.fnmatch_lines(["*passed*"])
+
+
+class TestAutouseDiscovery:
+ @pytest.fixture
+ def pytester(self, pytester: Pytester) -> Pytester:
+ pytester.makeconftest(
+ """
+ import pytest
+ @pytest.fixture(autouse=True)
+ def perfunction(request, tmp_path):
+ pass
+
+ @pytest.fixture()
+ def arg1(tmp_path):
+ pass
+ @pytest.fixture(autouse=True)
+ def perfunction2(arg1):
+ pass
+
+ @pytest.fixture
+ def fm(request):
+ return request._fixturemanager
+
+ @pytest.fixture
+ def item(request):
+ return request._pyfuncitem
+ """
+ )
+ return pytester
+
+ def test_parsefactories_conftest(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ from _pytest.pytester import get_public_names
+ def test_check_setup(item, fm):
+ autousenames = list(fm._getautousenames(item))
+ assert len(get_public_names(autousenames)) == 2
+ assert "perfunction2" in autousenames
+ assert "perfunction" in autousenames
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(passed=1)
+
+ def test_two_classes_separated_autouse(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ class TestA(object):
+ values = []
+ @pytest.fixture(autouse=True)
+ def setup1(self):
+ self.values.append(1)
+ def test_setup1(self):
+ assert self.values == [1]
+ class TestB(object):
+ values = []
+ @pytest.fixture(autouse=True)
+ def setup2(self):
+ self.values.append(1)
+ def test_setup2(self):
+ assert self.values == [1]
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_setup_at_classlevel(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ class TestClass(object):
+ @pytest.fixture(autouse=True)
+ def permethod(self, request):
+ request.instance.funcname = request.function.__name__
+ def test_method1(self):
+ assert self.funcname == "test_method1"
+ def test_method2(self):
+ assert self.funcname == "test_method2"
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(passed=2)
+
+ @pytest.mark.xfail(reason="'enabled' feature not implemented")
+ def test_setup_enabled_functionnode(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ def enabled(parentnode, markers):
+ return "needsdb" in markers
+
+ @pytest.fixture(params=[1,2])
+ def db(request):
+ return request.param
+
+ @pytest.fixture(enabled=enabled, autouse=True)
+ def createdb(db):
+ pass
+
+ def test_func1(request):
+ assert "db" not in request.fixturenames
+
+ @pytest.mark.needsdb
+ def test_func2(request):
+ assert "db" in request.fixturenames
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(passed=2)
+
+ def test_callables_nocode(self, pytester: Pytester) -> None:
+ """An imported mock.call would break setup/factory discovery due to
+ it being callable and __code__ not being a code object."""
+ pytester.makepyfile(
+ """
+ class _call(tuple):
+ def __call__(self, *k, **kw):
+ pass
+ def __getattr__(self, k):
+ return self
+
+ call = _call()
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(failed=0, passed=0)
+
+ def test_autouse_in_conftests(self, pytester: Pytester) -> None:
+ a = pytester.mkdir("a")
+ b = pytester.mkdir("a1")
+ conftest = pytester.makeconftest(
+ """
+ import pytest
+ @pytest.fixture(autouse=True)
+ def hello():
+ xxx
+ """
+ )
+ conftest.rename(a.joinpath(conftest.name))
+ a.joinpath("test_something.py").write_text(
+ "def test_func(): pass", encoding="utf-8"
+ )
+ b.joinpath("test_otherthing.py").write_text(
+ "def test_func(): pass", encoding="utf-8"
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ """
+ *1 passed*1 error*
+ """
+ )
+
+ def test_autouse_in_module_and_two_classes(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(autouse=True)
+ def append1():
+ values.append("module")
+ def test_x():
+ assert values == ["module"]
+
+ class TestA(object):
+ @pytest.fixture(autouse=True)
+ def append2(self):
+ values.append("A")
+ def test_hello(self):
+ assert values == ["module", "module", "A"], values
+ class TestA2(object):
+ def test_world(self):
+ assert values == ["module", "module", "A", "module"], values
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=3)
+
+
+class TestAutouseManagement:
+ def test_autouse_conftest_mid_directory(self, pytester: Pytester) -> None:
+ pkgdir = pytester.mkpydir("xyz123")
+ pkgdir.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ @pytest.fixture(autouse=True)
+ def app():
+ import sys
+ sys._myapp = "hello"
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub = pkgdir.joinpath("tests")
+ sub.mkdir()
+ t = sub.joinpath("test_app.py")
+ t.touch()
+ t.write_text(
+ textwrap.dedent(
+ """\
+ import sys
+ def test_app():
+ assert sys._myapp == "hello"
+ """
+ ),
+ encoding="utf-8",
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(passed=1)
+
+ def test_funcarg_and_setup(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(scope="module")
+ def arg():
+ values.append(1)
+ return 0
+ @pytest.fixture(scope="module", autouse=True)
+ def something(arg):
+ values.append(2)
+
+ def test_hello(arg):
+ assert len(values) == 2
+ assert values == [1,2]
+ assert arg == 0
+
+ def test_hello2(arg):
+ assert len(values) == 2
+ assert values == [1,2]
+ assert arg == 0
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_uses_parametrized_resource(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(params=[1,2])
+ def arg(request):
+ return request.param
+
+ @pytest.fixture(autouse=True)
+ def something(arg):
+ values.append(arg)
+
+ def test_hello():
+ if len(values) == 1:
+ assert values == [1]
+ elif len(values) == 2:
+ assert values == [1, 2]
+ else:
+ 0/0
+
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(passed=2)
+
+ def test_session_parametrized_function(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ values = []
+
+ @pytest.fixture(scope="session", params=[1,2])
+ def arg(request):
+ return request.param
+
+ @pytest.fixture(scope="function", autouse=True)
+ def append(request, arg):
+ if request.function.__name__ == "test_some":
+ values.append(arg)
+
+ def test_some():
+ pass
+
+ def test_result(arg):
+ assert len(values) == arg
+ assert values[:arg] == [1,2][:arg]
+ """
+ )
+ reprec = pytester.inline_run("-v", "-s")
+ reprec.assertoutcome(passed=4)
+
+ def test_class_function_parametrization_finalization(
+ self, pytester: Pytester
+ ) -> None:
+ p = pytester.makeconftest(
+ """
+ import pytest
+ import pprint
+
+ values = []
+
+ @pytest.fixture(scope="function", params=[1,2])
+ def farg(request):
+ return request.param
+
+ @pytest.fixture(scope="class", params=list("ab"))
+ def carg(request):
+ return request.param
+
+ @pytest.fixture(scope="function", autouse=True)
+ def append(request, farg, carg):
+ def fin():
+ values.append("fin_%s%s" % (carg, farg))
+ request.addfinalizer(fin)
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ class TestClass(object):
+ def test_1(self):
+ pass
+ class TestClass2(object):
+ def test_2(self):
+ pass
+ """
+ )
+ reprec = pytester.inline_run("-v", "-s", "--confcutdir", pytester.path)
+ reprec.assertoutcome(passed=8)
+ config = reprec.getcalls("pytest_unconfigure")[0].config
+ values = config.pluginmanager._getconftestmodules(p)[0].values
+ assert values == ["fin_a1", "fin_a2", "fin_b1", "fin_b2"] * 2
+
+ def test_scope_ordering(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(scope="function", autouse=True)
+ def fappend2():
+ values.append(2)
+ @pytest.fixture(scope="class", autouse=True)
+ def classappend3():
+ values.append(3)
+ @pytest.fixture(scope="module", autouse=True)
+ def mappend():
+ values.append(1)
+
+ class TestHallo(object):
+ def test_method(self):
+ assert values == [1,3,2]
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_parametrization_setup_teardown_ordering(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ def pytest_generate_tests(metafunc):
+ if metafunc.cls is None:
+ assert metafunc.function is test_finish
+ if metafunc.cls is not None:
+ metafunc.parametrize("item", [1,2], scope="class")
+ class TestClass(object):
+ @pytest.fixture(scope="class", autouse=True)
+ def addteardown(self, item, request):
+ values.append("setup-%d" % item)
+ request.addfinalizer(lambda: values.append("teardown-%d" % item))
+ def test_step1(self, item):
+ values.append("step1-%d" % item)
+ def test_step2(self, item):
+ values.append("step2-%d" % item)
+
+ def test_finish():
+ print(values)
+ assert values == ["setup-1", "step1-1", "step2-1", "teardown-1",
+ "setup-2", "step1-2", "step2-2", "teardown-2",]
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(passed=5)
+
+ def test_ordering_autouse_before_explicit(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ values = []
+ @pytest.fixture(autouse=True)
+ def fix1():
+ values.append(1)
+ @pytest.fixture()
+ def arg1():
+ values.append(2)
+ def test_hello(arg1):
+ assert values == [1,2]
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ @pytest.mark.parametrize("param1", ["", "params=[1]"], ids=["p00", "p01"])
+ @pytest.mark.parametrize("param2", ["", "params=[1]"], ids=["p10", "p11"])
+ def test_ordering_dependencies_torndown_first(
+ self, pytester: Pytester, param1, param2
+ ) -> None:
+ """#226"""
+ pytester.makepyfile(
+ f"""
+ import pytest
+ values = []
+ @pytest.fixture({param1})
+ def arg1(request):
+ request.addfinalizer(lambda: values.append("fin1"))
+ values.append("new1")
+ @pytest.fixture({param2})
+ def arg2(request, arg1):
+ request.addfinalizer(lambda: values.append("fin2"))
+ values.append("new2")
+
+ def test_arg(arg2):
+ pass
+ def test_check():
+ assert values == ["new1", "new2", "fin2", "fin1"]
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ reprec.assertoutcome(passed=2)
+
+ def test_reordering_catastrophic_performance(self, pytester: Pytester) -> None:
+ """Check that a certain high-scope parametrization pattern doesn't cause
+ a catasrophic slowdown.
+
+ Regression test for #12355.
+ """
+ pytester.makepyfile("""
+ import pytest
+
+ params = tuple("abcdefghijklmnopqrstuvwxyz")
+ @pytest.mark.parametrize(params, [range(len(params))] * 3, scope="module")
+ def test_parametrize(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z):
+ pass
+ """)
+
+ result = pytester.runpytest()
+
+ result.assert_outcomes(passed=3)
+
+
+class TestFixtureMarker:
+ def test_parametrize(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(params=["a", "b", "c"])
+ def arg(request):
+ return request.param
+ values = []
+ def test_param(arg):
+ values.append(arg)
+ def test_result():
+ assert values == list("abc")
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=4)
+
+ def test_multiple_parametrization_issue_736(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=[1,2,3])
+ def foo(request):
+ return request.param
+
+ @pytest.mark.parametrize('foobar', [4,5,6])
+ def test_issue(foo, foobar):
+ assert foo in [1,2,3]
+ assert foobar in [4,5,6]
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=9)
+
+ @pytest.mark.parametrize(
+ "param_args",
+ ["'fixt, val'", "'fixt,val'", "['fixt', 'val']", "('fixt', 'val')"],
+ )
+ def test_override_parametrized_fixture_issue_979(
+ self, pytester: Pytester, param_args
+ ) -> None:
+ """Make sure a parametrized argument can override a parametrized fixture.
+
+ This was a regression introduced in the fix for #736.
+ """
+ pytester.makepyfile(
+ f"""
+ import pytest
+
+ @pytest.fixture(params=[1, 2])
+ def fixt(request):
+ return request.param
+
+ @pytest.mark.parametrize({param_args}, [(3, 'x'), (4, 'x')])
+ def test_foo(fixt, val):
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_scope_session(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(scope="module")
+ def arg():
+ values.append(1)
+ return 1
+
+ def test_1(arg):
+ assert arg == 1
+ def test_2(arg):
+ assert arg == 1
+ assert len(values) == 1
+ class TestClass(object):
+ def test3(self, arg):
+ assert arg == 1
+ assert len(values) == 1
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=3)
+
+ def test_scope_session_exc(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(scope="session")
+ def fix():
+ values.append(1)
+ pytest.skip('skipping')
+
+ def test_1(fix):
+ pass
+ def test_2(fix):
+ pass
+ def test_last():
+ assert values == [1]
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(skipped=2, passed=1)
+
+ def test_scope_session_exc_two_fix(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ m = []
+ @pytest.fixture(scope="session")
+ def a():
+ values.append(1)
+ pytest.skip('skipping')
+ @pytest.fixture(scope="session")
+ def b(a):
+ m.append(1)
+
+ def test_1(b):
+ pass
+ def test_2(b):
+ pass
+ def test_last():
+ assert values == [1]
+ assert m == []
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(skipped=2, passed=1)
+
+ def test_scope_exc(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ test_foo="""
+ def test_foo(fix):
+ pass
+ """,
+ test_bar="""
+ def test_bar(fix):
+ pass
+ """,
+ conftest="""
+ import pytest
+ reqs = []
+ @pytest.fixture(scope="session")
+ def fix(request):
+ reqs.append(1)
+ pytest.skip()
+ @pytest.fixture
+ def req_list():
+ return reqs
+ """,
+ test_real="""
+ def test_last(req_list):
+ assert req_list == [1]
+ """,
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(skipped=2, passed=1)
+
+ def test_scope_module_uses_session(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(scope="module")
+ def arg():
+ values.append(1)
+ return 1
+
+ def test_1(arg):
+ assert arg == 1
+ def test_2(arg):
+ assert arg == 1
+ assert len(values) == 1
+ class TestClass(object):
+ def test3(self, arg):
+ assert arg == 1
+ assert len(values) == 1
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=3)
+
+ def test_scope_module_and_finalizer(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ finalized_list = []
+ created_list = []
+ @pytest.fixture(scope="module")
+ def arg(request):
+ created_list.append(1)
+ assert request.scope == "module"
+ request.addfinalizer(lambda: finalized_list.append(1))
+ @pytest.fixture
+ def created(request):
+ return len(created_list)
+ @pytest.fixture
+ def finalized(request):
+ return len(finalized_list)
+ """
+ )
+ pytester.makepyfile(
+ test_mod1="""
+ def test_1(arg, created, finalized):
+ assert created == 1
+ assert finalized == 0
+ def test_2(arg, created, finalized):
+ assert created == 1
+ assert finalized == 0""",
+ test_mod2="""
+ def test_3(arg, created, finalized):
+ assert created == 2
+ assert finalized == 1""",
+ test_mode3="""
+ def test_4(arg, created, finalized):
+ assert created == 3
+ assert finalized == 2
+ """,
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=4)
+
+ def test_scope_mismatch_various(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ finalized = []
+ created = []
+ @pytest.fixture(scope="function")
+ def arg(request):
+ pass
+ """
+ )
+ pytester.makepyfile(
+ test_mod1="""
+ import pytest
+ @pytest.fixture(scope="session")
+ def arg(request):
+ request.getfixturevalue("arg")
+ def test_1(arg):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret != 0
+ result.stdout.fnmatch_lines(
+ ["*ScopeMismatch*You tried*function*session*request*"]
+ )
+
+ def test_scope_mismatch_already_computed_dynamic(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ test_it="""
+ import pytest
+
+ @pytest.fixture(scope="function")
+ def fixfunc(): pass
+
+ @pytest.fixture(scope="module")
+ def fixmod(fixfunc): pass
+
+ def test_it(request, fixfunc):
+ request.getfixturevalue("fixmod")
+ """,
+ )
+
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.TESTS_FAILED
+ result.stdout.fnmatch_lines(
+ [
+ "*ScopeMismatch*Requesting fixture stack*",
+ "test_it.py:6: def fixmod(fixfunc)",
+ "Requested fixture:",
+ "test_it.py:3: def fixfunc()",
+ ]
+ )
+
+ def test_dynamic_scope(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+
+
+ def pytest_addoption(parser):
+ parser.addoption("--extend-scope", action="store_true", default=False)
+
+
+ def dynamic_scope(fixture_name, config):
+ if config.getoption("--extend-scope"):
+ return "session"
+ return "function"
+
+
+ @pytest.fixture(scope=dynamic_scope)
+ def dynamic_fixture(calls=[]):
+ calls.append("call")
+ return len(calls)
+
+ """
+ )
+
+ pytester.makepyfile(
+ """
+ def test_first(dynamic_fixture):
+ assert dynamic_fixture == 1
+
+
+ def test_second(dynamic_fixture):
+ assert dynamic_fixture == 2
+
+ """
+ )
+
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ reprec = pytester.inline_run("--extend-scope")
+ reprec.assertoutcome(passed=1, failed=1)
+
+ def test_dynamic_scope_bad_return(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ def dynamic_scope(**_):
+ return "wrong-scope"
+
+ @pytest.fixture(scope=dynamic_scope)
+ def fixture():
+ pass
+
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ "Fixture 'fixture' from test_dynamic_scope_bad_return.py "
+ "got an unexpected scope value 'wrong-scope'"
+ )
+
+ def test_register_only_with_mark(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ @pytest.fixture()
+ def arg():
+ return 1
+ """
+ )
+ pytester.makepyfile(
+ test_mod1="""
+ import pytest
+ @pytest.fixture()
+ def arg(arg):
+ return arg + 1
+ def test_1(arg):
+ assert arg == 2
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_parametrize_and_scope(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="module", params=["a", "b", "c"])
+ def arg(request):
+ return request.param
+ values = []
+ def test_param(arg):
+ values.append(arg)
+ """
+ )
+ reprec = pytester.inline_run("-v")
+ reprec.assertoutcome(passed=3)
+ values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
+ assert len(values) == 3
+ assert "a" in values
+ assert "b" in values
+ assert "c" in values
+
+ def test_scope_mismatch(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ @pytest.fixture(scope="function")
+ def arg(request):
+ pass
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="session")
+ def arg(arg):
+ pass
+ def test_mismatch(arg):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*ScopeMismatch*", "*1 error*"])
+
+ def test_parametrize_separated_order(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope="module", params=[1, 2])
+ def arg(request):
+ return request.param
+
+ values = []
+ def test_1(arg):
+ values.append(arg)
+ def test_2(arg):
+ values.append(arg)
+ """
+ )
+ reprec = pytester.inline_run("-v")
+ reprec.assertoutcome(passed=4)
+ values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
+ assert values == [1, 1, 2, 2]
+
+ def test_module_parametrized_ordering(self, pytester: Pytester) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ console_output_style=classic
+ """
+ )
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(scope="session", params="s1 s2".split())
+ def sarg():
+ pass
+ @pytest.fixture(scope="module", params="m1 m2".split())
+ def marg():
+ pass
+ """
+ )
+ pytester.makepyfile(
+ test_mod1="""
+ def test_func(sarg):
+ pass
+ def test_func1(marg):
+ pass
+ """,
+ test_mod2="""
+ def test_func2(sarg):
+ pass
+ def test_func3(sarg, marg):
+ pass
+ def test_func3b(sarg, marg):
+ pass
+ def test_func4(marg):
+ pass
+ """,
+ )
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines(
+ """
+ test_mod1.py::test_func[s1] PASSED
+ test_mod2.py::test_func2[s1] PASSED
+ test_mod2.py::test_func3[s1-m1] PASSED
+ test_mod2.py::test_func3b[s1-m1] PASSED
+ test_mod2.py::test_func3[s1-m2] PASSED
+ test_mod2.py::test_func3b[s1-m2] PASSED
+ test_mod1.py::test_func[s2] PASSED
+ test_mod2.py::test_func2[s2] PASSED
+ test_mod2.py::test_func3[s2-m1] PASSED
+ test_mod2.py::test_func3b[s2-m1] PASSED
+ test_mod2.py::test_func4[m1] PASSED
+ test_mod2.py::test_func3[s2-m2] PASSED
+ test_mod2.py::test_func3b[s2-m2] PASSED
+ test_mod2.py::test_func4[m2] PASSED
+ test_mod1.py::test_func1[m1] PASSED
+ test_mod1.py::test_func1[m2] PASSED
+ """
+ )
+
+ def test_dynamic_parametrized_ordering(self, pytester: Pytester) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ console_output_style=classic
+ """
+ )
+ pytester.makeconftest(
+ """
+ import pytest
+
+ def pytest_configure(config):
+ class DynamicFixturePlugin(object):
+ @pytest.fixture(scope='session', params=['flavor1', 'flavor2'])
+ def flavor(self, request):
+ return request.param
+ config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture')
+
+ @pytest.fixture(scope='session', params=['vxlan', 'vlan'])
+ def encap(request):
+ return request.param
+
+ @pytest.fixture(scope='session', autouse='True')
+ def reprovision(request, flavor, encap):
+ pass
+ """
+ )
+ pytester.makepyfile(
+ """
+ def test(reprovision):
+ pass
+ def test2(reprovision):
+ pass
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines(
+ """
+ test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED
+ test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED
+ test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED
+ test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED
+ test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED
+ test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED
+ test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED
+ test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED
+ """
+ )
+
+ def test_class_ordering(self, pytester: Pytester) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ console_output_style=classic
+ """
+ )
+ pytester.makeconftest(
+ """
+ import pytest
+
+ values = []
+
+ @pytest.fixture(scope="function", params=[1,2])
+ def farg(request):
+ return request.param
+
+ @pytest.fixture(scope="class", params=list("ab"))
+ def carg(request):
+ return request.param
+
+ @pytest.fixture(scope="function", autouse=True)
+ def append(request, farg, carg):
+ def fin():
+ values.append("fin_%s%s" % (carg, farg))
+ request.addfinalizer(fin)
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ class TestClass2(object):
+ def test_1(self):
+ pass
+ def test_2(self):
+ pass
+ class TestClass(object):
+ def test_3(self):
+ pass
+ """
+ )
+ result = pytester.runpytest("-vs")
+ result.stdout.re_match_lines(
+ r"""
+ test_class_ordering.py::TestClass2::test_1\[a-1\] PASSED
+ test_class_ordering.py::TestClass2::test_1\[a-2\] PASSED
+ test_class_ordering.py::TestClass2::test_2\[a-1\] PASSED
+ test_class_ordering.py::TestClass2::test_2\[a-2\] PASSED
+ test_class_ordering.py::TestClass2::test_1\[b-1\] PASSED
+ test_class_ordering.py::TestClass2::test_1\[b-2\] PASSED
+ test_class_ordering.py::TestClass2::test_2\[b-1\] PASSED
+ test_class_ordering.py::TestClass2::test_2\[b-2\] PASSED
+ test_class_ordering.py::TestClass::test_3\[a-1\] PASSED
+ test_class_ordering.py::TestClass::test_3\[a-2\] PASSED
+ test_class_ordering.py::TestClass::test_3\[b-1\] PASSED
+ test_class_ordering.py::TestClass::test_3\[b-2\] PASSED
+ """
+ )
+
+ def test_parametrize_separated_order_higher_scope_first(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope="function", params=[1, 2])
+ def arg(request):
+ param = request.param
+ request.addfinalizer(lambda: values.append("fin:%s" % param))
+ values.append("create:%s" % param)
+ return request.param
+
+ @pytest.fixture(scope="module", params=["mod1", "mod2"])
+ def modarg(request):
+ param = request.param
+ request.addfinalizer(lambda: values.append("fin:%s" % param))
+ values.append("create:%s" % param)
+ return request.param
+
+ values = []
+ def test_1(arg):
+ values.append("test1")
+ def test_2(modarg):
+ values.append("test2")
+ def test_3(arg, modarg):
+ values.append("test3")
+ def test_4(modarg, arg):
+ values.append("test4")
+ """
+ )
+ reprec = pytester.inline_run("-v")
+ reprec.assertoutcome(passed=12)
+ values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
+ expected = [
+ "create:1",
+ "test1",
+ "fin:1",
+ "create:2",
+ "test1",
+ "fin:2",
+ "create:mod1",
+ "test2",
+ "create:1",
+ "test3",
+ "fin:1",
+ "create:2",
+ "test3",
+ "fin:2",
+ "create:1",
+ "test4",
+ "fin:1",
+ "create:2",
+ "test4",
+ "fin:2",
+ "fin:mod1",
+ "create:mod2",
+ "test2",
+ "create:1",
+ "test3",
+ "fin:1",
+ "create:2",
+ "test3",
+ "fin:2",
+ "create:1",
+ "test4",
+ "fin:1",
+ "create:2",
+ "test4",
+ "fin:2",
+ "fin:mod2",
+ ]
+ import pprint
+
+ pprint.pprint(list(zip_longest(values, expected)))
+ assert values == expected
+
+ def test_parametrized_fixture_teardown_order(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(params=[1,2], scope="class")
+ def param1(request):
+ return request.param
+
+ values = []
+
+ class TestClass(object):
+ @classmethod
+ @pytest.fixture(scope="class", autouse=True)
+ def setup1(self, request, param1):
+ values.append(1)
+ request.addfinalizer(self.teardown1)
+ @classmethod
+ def teardown1(self):
+ assert values.pop() == 1
+ @pytest.fixture(scope="class", autouse=True)
+ def setup2(self, request, param1):
+ values.append(2)
+ request.addfinalizer(self.teardown2)
+ @classmethod
+ def teardown2(self):
+ assert values.pop() == 2
+ def test(self):
+ pass
+
+ def test_finish():
+ assert not values
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines(
+ """
+ *3 passed*
+ """
+ )
+ assert result.ret == 0
+
+ def test_fixture_finalizer(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ import sys
+
+ @pytest.fixture
+ def browser(request):
+
+ def finalize():
+ sys.stdout.write_text('Finalized', encoding='utf-8')
+ request.addfinalizer(finalize)
+ return {}
+ """
+ )
+ b = pytester.mkdir("subdir")
+ b.joinpath("test_overridden_fixture_finalizer.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ @pytest.fixture
+ def browser(browser):
+ browser['visited'] = True
+ return browser
+
+ def test_browser(browser):
+ assert browser['visited'] is True
+ """
+ ),
+ encoding="utf-8",
+ )
+ reprec = pytester.runpytest("-s")
+ for test in ["test_browser"]:
+ reprec.stdout.fnmatch_lines(["*Finalized*"])
+
+ def test_class_scope_with_normal_tests(self, pytester: Pytester) -> None:
+ testpath = pytester.makepyfile(
+ """
+ import pytest
+
+ class Box(object):
+ value = 0
+
+ @pytest.fixture(scope='class')
+ def a(request):
+ Box.value += 1
+ return Box.value
+
+ def test_a(a):
+ assert a == 1
+
+ class Test1(object):
+ def test_b(self, a):
+ assert a == 2
+
+ class Test2(object):
+ def test_c(self, a):
+ assert a == 3"""
+ )
+ reprec = pytester.inline_run(testpath)
+ for test in ["test_a", "test_b", "test_c"]:
+ assert reprec.matchreport(test).passed
+
+ def test_request_is_clean(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(params=[1, 2])
+ def fix(request):
+ request.addfinalizer(lambda: values.append(request.param))
+ def test_fix(fix):
+ pass
+ """
+ )
+ reprec = pytester.inline_run("-s")
+ values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
+ assert values == [1, 2]
+
+ def test_parametrize_separated_lifecycle(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ values = []
+ @pytest.fixture(scope="module", params=[1, 2])
+ def arg(request):
+ x = request.param
+ request.addfinalizer(lambda: values.append("fin%s" % x))
+ return request.param
+ def test_1(arg):
+ values.append(arg)
+ def test_2(arg):
+ values.append(arg)
+ """
+ )
+ reprec = pytester.inline_run("-vs")
+ reprec.assertoutcome(passed=4)
+ values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
+ import pprint
+
+ pprint.pprint(values)
+ # assert len(values) == 6
+ assert values[0] == values[1] == 1
+ assert values[2] == "fin1"
+ assert values[3] == values[4] == 2
+ assert values[5] == "fin2"
+
+ def test_parametrize_function_scoped_finalizers_called(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope="function", params=[1, 2])
+ def arg(request):
+ x = request.param
+ request.addfinalizer(lambda: values.append("fin%s" % x))
+ return request.param
+
+ values = []
+ def test_1(arg):
+ values.append(arg)
+ def test_2(arg):
+ values.append(arg)
+ def test_3():
+ assert len(values) == 8
+ assert values == [1, "fin1", 2, "fin2", 1, "fin1", 2, "fin2"]
+ """
+ )
+ reprec = pytester.inline_run("-v")
+ reprec.assertoutcome(passed=5)
+
+ @pytest.mark.parametrize("scope", ["session", "function", "module"])
+ def test_finalizer_order_on_parametrization(
+ self, scope, pytester: Pytester
+ ) -> None:
+ """#246"""
+ pytester.makepyfile(
+ f"""
+ import pytest
+ values = []
+
+ @pytest.fixture(scope={scope!r}, params=["1"])
+ def fix1(request):
+ return request.param
+
+ @pytest.fixture(scope={scope!r})
+ def fix2(request, base):
+ def cleanup_fix2():
+ assert not values, "base should not have been finalized"
+ request.addfinalizer(cleanup_fix2)
+
+ @pytest.fixture(scope={scope!r})
+ def base(request, fix1):
+ def cleanup_base():
+ values.append("fin_base")
+ print("finalizing base")
+ request.addfinalizer(cleanup_base)
+
+ def test_begin():
+ pass
+ def test_baz(base, fix2):
+ pass
+ def test_other():
+ pass
+ """
+ )
+ reprec = pytester.inline_run("-lvs")
+ reprec.assertoutcome(passed=3)
+
+ def test_class_scope_parametrization_ordering(self, pytester: Pytester) -> None:
+ """#396"""
+ pytester.makepyfile(
+ """
+ import pytest
+ values = []
+ @pytest.fixture(params=["John", "Doe"], scope="class")
+ def human(request):
+ request.addfinalizer(lambda: values.append("fin %s" % request.param))
+ return request.param
+
+ class TestGreetings(object):
+ def test_hello(self, human):
+ values.append("test_hello")
+
+ class TestMetrics(object):
+ def test_name(self, human):
+ values.append("test_name")
+
+ def test_population(self, human):
+ values.append("test_population")
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=6)
+ values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
+ assert values == [
+ "test_hello",
+ "fin John",
+ "test_hello",
+ "fin Doe",
+ "test_name",
+ "test_population",
+ "fin John",
+ "test_name",
+ "test_population",
+ "fin Doe",
+ ]
+
+ def test_parametrize_setup_function(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope="module", params=[1, 2])
+ def arg(request):
+ return request.param
+
+ @pytest.fixture(scope="module", autouse=True)
+ def mysetup(request, arg):
+ request.addfinalizer(lambda: values.append("fin%s" % arg))
+ values.append("setup%s" % arg)
+
+ values = []
+ def test_1(arg):
+ values.append(arg)
+ def test_2(arg):
+ values.append(arg)
+ def test_3():
+ import pprint
+ pprint.pprint(values)
+ if arg == 1:
+ assert values == ["setup1", 1, 1, ]
+ elif arg == 2:
+ assert values == ["setup1", 1, 1, "fin1",
+ "setup2", 2, 2, ]
+
+ """
+ )
+ reprec = pytester.inline_run("-v")
+ reprec.assertoutcome(passed=6)
+
+ def test_fixture_marked_function_not_collected_as_test(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture
+ def test_app():
+ return 1
+
+ def test_something(test_app):
+ assert test_app == 1
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_params_and_ids(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=[object(), object()],
+ ids=['alpha', 'beta'])
+ def fix(request):
+ return request.param
+
+ def test_foo(fix):
+ assert 1
+ """
+ )
+ res = pytester.runpytest("-v")
+ res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
+
+ def test_params_and_ids_yieldfixture(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=[object(), object()], ids=['alpha', 'beta'])
+ def fix(request):
+ yield request.param
+
+ def test_foo(fix):
+ assert 1
+ """
+ )
+ res = pytester.runpytest("-v")
+ res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
+
+ def test_deterministic_fixture_collection(
+ self, pytester: Pytester, monkeypatch
+ ) -> None:
+ """#920"""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope="module",
+ params=["A",
+ "B",
+ "C"])
+ def A(request):
+ return request.param
+
+ @pytest.fixture(scope="module",
+ params=["DDDDDDDDD", "EEEEEEEEEEEE", "FFFFFFFFFFF", "banansda"])
+ def B(request, A):
+ return request.param
+
+ def test_foo(B):
+ # Something funky is going on here.
+ # Despite specified seeds, on what is collected,
+ # sometimes we get unexpected passes. hashing B seems
+ # to help?
+ assert hash(B) or True
+ """
+ )
+ monkeypatch.setenv("PYTHONHASHSEED", "1")
+ out1 = pytester.runpytest_subprocess("-v")
+ monkeypatch.setenv("PYTHONHASHSEED", "2")
+ out2 = pytester.runpytest_subprocess("-v")
+ output1 = [
+ line
+ for line in out1.outlines
+ if line.startswith("test_deterministic_fixture_collection.py::test_foo")
+ ]
+ output2 = [
+ line
+ for line in out2.outlines
+ if line.startswith("test_deterministic_fixture_collection.py::test_foo")
+ ]
+ assert len(output1) == 12
+ assert output1 == output2
+
+
+class TestRequestScopeAccess:
+ pytestmark = pytest.mark.parametrize(
+ ("scope", "ok", "error"),
+ [
+ ["session", "", "path class function module"],
+ ["module", "module path", "cls function"],
+ ["class", "module path cls", "function"],
+ ["function", "module path cls function", ""],
+ ],
+ )
+
+ def test_setup(self, pytester: Pytester, scope, ok, error) -> None:
+ pytester.makepyfile(
+ f"""
+ import pytest
+ @pytest.fixture(scope={scope!r}, autouse=True)
+ def myscoped(request):
+ for x in {ok.split()}:
+ assert hasattr(request, x)
+ for x in {error.split()}:
+ with pytest.raises(AttributeError):
+ getattr(request, x)
+ assert request.session
+ assert request.config
+ def test_func():
+ pass
+ """
+ )
+ reprec = pytester.inline_run("-l")
+ reprec.assertoutcome(passed=1)
+
+ def test_funcarg(self, pytester: Pytester, scope, ok, error) -> None:
+ pytester.makepyfile(
+ f"""
+ import pytest
+ @pytest.fixture(scope={scope!r})
+ def arg(request):
+ for x in {ok.split()!r}:
+ assert hasattr(request, x)
+ for x in {error.split()!r}:
+ with pytest.raises(AttributeError):
+ getattr(request, x)
+ assert request.session
+ assert request.config
+ def test_func(arg):
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+
+class TestErrors:
+ def test_subfactory_missing_funcarg(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture()
+ def gen(qwe123):
+ return 1
+ def test_something(gen):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret != 0
+ result.stdout.fnmatch_lines(
+ ["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"]
+ )
+
+ def test_issue498_fixture_finalizer_failing(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture
+ def fix1(request):
+ def f():
+ raise KeyError
+ request.addfinalizer(f)
+ return object()
+
+ values = []
+ def test_1(fix1):
+ values.append(fix1)
+ def test_2(fix1):
+ values.append(fix1)
+ def test_3():
+ assert values[0] != values[1]
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ """
+ *ERROR*teardown*test_1*
+ *KeyError*
+ *ERROR*teardown*test_2*
+ *KeyError*
+ *3 pass*2 errors*
+ """
+ )
+
+ def test_setupfunc_missing_funcarg(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(autouse=True)
+ def gen(qwe123):
+ return 1
+ def test_something():
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret != 0
+ result.stdout.fnmatch_lines(
+ ["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"]
+ )
+
+ def test_cached_exception_doesnt_get_longer(self, pytester: Pytester) -> None:
+ """Regression test for #12204."""
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="session")
+ def bad(): 1 / 0
+
+ def test_1(bad): pass
+ def test_2(bad): pass
+ def test_3(bad): pass
+ """
+ )
+
+ result = pytester.runpytest_inprocess("--tb=native")
+ assert result.ret == ExitCode.TESTS_FAILED
+ failures = result.reprec.getfailures() # type: ignore[attr-defined]
+ assert len(failures) == 3
+ lines1 = failures[1].longrepr.reprtraceback.reprentries[0].lines
+ lines2 = failures[2].longrepr.reprtraceback.reprentries[0].lines
+ assert len(lines1) == len(lines2)
+
+
+class TestShowFixtures:
+ def test_funcarg_compat(self, pytester: Pytester) -> None:
+ config = pytester.parseconfigure("--funcargs")
+ assert config.option.showfixtures
+
+ def test_show_help(self, pytester: Pytester) -> None:
+ result = pytester.runpytest("--fixtures", "--help")
+ assert not result.ret
+
+ def test_show_fixtures(self, pytester: Pytester) -> None:
+ result = pytester.runpytest("--fixtures")
+ result.stdout.fnmatch_lines(
+ [
+ "tmp_path_factory [[]session scope[]] -- .../_pytest/tmpdir.py:*",
+ "*for the test session*",
+ "tmp_path -- .../_pytest/tmpdir.py:*",
+ "*temporary directory*",
+ ]
+ )
+
+ def test_show_fixtures_verbose(self, pytester: Pytester) -> None:
+ result = pytester.runpytest("--fixtures", "-v")
+ result.stdout.fnmatch_lines(
+ [
+ "tmp_path_factory [[]session scope[]] -- .../_pytest/tmpdir.py:*",
+ "*for the test session*",
+ "tmp_path -- .../_pytest/tmpdir.py:*",
+ "*temporary directory*",
+ ]
+ )
+
+ def test_show_fixtures_testmodule(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ '''
+ import pytest
+ @pytest.fixture
+ def _arg0():
+ """ hidden """
+ @pytest.fixture
+ def arg1():
+ """ hello world """
+ '''
+ )
+ result = pytester.runpytest("--fixtures", p)
+ result.stdout.fnmatch_lines(
+ """
+ *tmp_path -- *
+ *fixtures defined from*
+ *arg1 -- test_show_fixtures_testmodule.py:6*
+ *hello world*
+ """
+ )
+ result.stdout.no_fnmatch_line("*arg0*")
+
+ @pytest.mark.parametrize("testmod", [True, False])
+ def test_show_fixtures_conftest(self, pytester: Pytester, testmod) -> None:
+ pytester.makeconftest(
+ '''
+ import pytest
+ @pytest.fixture
+ def arg1():
+ """ hello world """
+ '''
+ )
+ if testmod:
+ pytester.makepyfile(
+ """
+ def test_hello():
+ pass
+ """
+ )
+ result = pytester.runpytest("--fixtures")
+ result.stdout.fnmatch_lines(
+ """
+ *tmp_path*
+ *fixtures defined from*conftest*
+ *arg1*
+ *hello world*
+ """
+ )
+
+ def test_show_fixtures_trimmed_doc(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ textwrap.dedent(
+ '''\
+ import pytest
+ @pytest.fixture
+ def arg1():
+ """
+ line1
+ line2
+
+ """
+ @pytest.fixture
+ def arg2():
+ """
+ line1
+ line2
+
+ """
+ '''
+ )
+ )
+ result = pytester.runpytest("--fixtures", p)
+ result.stdout.fnmatch_lines(
+ textwrap.dedent(
+ """\
+ * fixtures defined from test_show_fixtures_trimmed_doc *
+ arg2 -- test_show_fixtures_trimmed_doc.py:10
+ line1
+ line2
+ arg1 -- test_show_fixtures_trimmed_doc.py:3
+ line1
+ line2
+ """
+ )
+ )
+
+ def test_show_fixtures_indented_doc(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ textwrap.dedent(
+ '''\
+ import pytest
+ @pytest.fixture
+ def fixture1():
+ """
+ line1
+ indented line
+ """
+ '''
+ )
+ )
+ result = pytester.runpytest("--fixtures", p)
+ result.stdout.fnmatch_lines(
+ textwrap.dedent(
+ """\
+ * fixtures defined from test_show_fixtures_indented_doc *
+ fixture1 -- test_show_fixtures_indented_doc.py:3
+ line1
+ indented line
+ """
+ )
+ )
+
+ def test_show_fixtures_indented_doc_first_line_unindented(
+ self, pytester: Pytester
+ ) -> None:
+ p = pytester.makepyfile(
+ textwrap.dedent(
+ '''\
+ import pytest
+ @pytest.fixture
+ def fixture1():
+ """line1
+ line2
+ indented line
+ """
+ '''
+ )
+ )
+ result = pytester.runpytest("--fixtures", p)
+ result.stdout.fnmatch_lines(
+ textwrap.dedent(
+ """\
+ * fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *
+ fixture1 -- test_show_fixtures_indented_doc_first_line_unindented.py:3
+ line1
+ line2
+ indented line
+ """
+ )
+ )
+
+ def test_show_fixtures_indented_in_class(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ textwrap.dedent(
+ '''\
+ import pytest
+ class TestClass(object):
+ @pytest.fixture
+ def fixture1(self):
+ """line1
+ line2
+ indented line
+ """
+ '''
+ )
+ )
+ result = pytester.runpytest("--fixtures", p)
+ result.stdout.fnmatch_lines(
+ textwrap.dedent(
+ """\
+ * fixtures defined from test_show_fixtures_indented_in_class *
+ fixture1 -- test_show_fixtures_indented_in_class.py:4
+ line1
+ line2
+ indented line
+ """
+ )
+ )
+
+ def test_show_fixtures_different_files(self, pytester: Pytester) -> None:
+ """`--fixtures` only shows fixtures from first file (#833)."""
+ pytester.makepyfile(
+ test_a='''
+ import pytest
+
+ @pytest.fixture
+ def fix_a():
+ """Fixture A"""
+ pass
+
+ def test_a(fix_a):
+ pass
+ '''
+ )
+ pytester.makepyfile(
+ test_b='''
+ import pytest
+
+ @pytest.fixture
+ def fix_b():
+ """Fixture B"""
+ pass
+
+ def test_b(fix_b):
+ pass
+ '''
+ )
+ result = pytester.runpytest("--fixtures")
+ result.stdout.fnmatch_lines(
+ """
+ * fixtures defined from test_a *
+ fix_a -- test_a.py:4
+ Fixture A
+
+ * fixtures defined from test_b *
+ fix_b -- test_b.py:4
+ Fixture B
+ """
+ )
+
+ def test_show_fixtures_with_same_name(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ '''
+ import pytest
+ @pytest.fixture
+ def arg1():
+ """Hello World in conftest.py"""
+ return "Hello World"
+ '''
+ )
+ pytester.makepyfile(
+ """
+ def test_foo(arg1):
+ assert arg1 == "Hello World"
+ """
+ )
+ pytester.makepyfile(
+ '''
+ import pytest
+ @pytest.fixture
+ def arg1():
+ """Hi from test module"""
+ return "Hi"
+ def test_bar(arg1):
+ assert arg1 == "Hi"
+ '''
+ )
+ result = pytester.runpytest("--fixtures")
+ result.stdout.fnmatch_lines(
+ """
+ * fixtures defined from conftest *
+ arg1 -- conftest.py:3
+ Hello World in conftest.py
+
+ * fixtures defined from test_show_fixtures_with_same_name *
+ arg1 -- test_show_fixtures_with_same_name.py:3
+ Hi from test module
+ """
+ )
+
+ def test_fixture_disallow_twice(self):
+ """Test that applying @pytest.fixture twice generates an error (#2334)."""
+ with pytest.raises(ValueError):
+
+ @pytest.fixture
+ @pytest.fixture
+ def foo():
+ raise NotImplementedError()
+
+
+class TestContextManagerFixtureFuncs:
+ def test_simple(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture
+ def arg1():
+ print("setup")
+ yield 1
+ print("teardown")
+ def test_1(arg1):
+ print("test1", arg1)
+ def test_2(arg1):
+ print("test2", arg1)
+ assert 0
+ """
+ )
+ result = pytester.runpytest("-s")
+ result.stdout.fnmatch_lines(
+ """
+ *setup*
+ *test1 1*
+ *teardown*
+ *setup*
+ *test2 1*
+ *teardown*
+ """
+ )
+
+ def test_scoped(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="module")
+ def arg1():
+ print("setup")
+ yield 1
+ print("teardown")
+ def test_1(arg1):
+ print("test1", arg1)
+ def test_2(arg1):
+ print("test2", arg1)
+ """
+ )
+ result = pytester.runpytest("-s")
+ result.stdout.fnmatch_lines(
+ """
+ *setup*
+ *test1 1*
+ *test2 1*
+ *teardown*
+ """
+ )
+
+ def test_setup_exception(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="module")
+ def arg1():
+ pytest.fail("setup")
+ yield 1
+ def test_1(arg1):
+ pass
+ """
+ )
+ result = pytester.runpytest("-s")
+ result.stdout.fnmatch_lines(
+ """
+ *pytest.fail*setup*
+ *1 error*
+ """
+ )
+
+ def test_teardown_exception(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="module")
+ def arg1():
+ yield 1
+ pytest.fail("teardown")
+ def test_1(arg1):
+ pass
+ """
+ )
+ result = pytester.runpytest("-s")
+ result.stdout.fnmatch_lines(
+ """
+ *pytest.fail*teardown*
+ *1 passed*1 error*
+ """
+ )
+
+ def test_yields_more_than_one(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(scope="module")
+ def arg1():
+ yield 1
+ yield 2
+ def test_1(arg1):
+ pass
+ """
+ )
+ result = pytester.runpytest("-s")
+ result.stdout.fnmatch_lines(
+ """
+ *fixture function*
+ *test_yields*:2*
+ """
+ )
+
+ def test_custom_name(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(name='meow')
+ def arg1():
+ return 'mew'
+ def test_1(meow):
+ print(meow)
+ """
+ )
+ result = pytester.runpytest("-s")
+ result.stdout.fnmatch_lines(["*mew*"])
+
+
+class TestParameterizedSubRequest:
+ def test_call_from_fixture(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ test_call_from_fixture="""
+ import pytest
+
+ @pytest.fixture(params=[0, 1, 2])
+ def fix_with_param(request):
+ return request.param
+
+ @pytest.fixture
+ def get_named_fixture(request):
+ return request.getfixturevalue('fix_with_param')
+
+ def test_foo(request, get_named_fixture):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "The requested fixture has no parameter defined for test:",
+ " test_call_from_fixture.py::test_foo",
+ "Requested fixture 'fix_with_param' defined in:",
+ "test_call_from_fixture.py:4",
+ "Requested here:",
+ "test_call_from_fixture.py:9",
+ "*1 error in*",
+ ]
+ )
+
+ def test_call_from_test(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ test_call_from_test="""
+ import pytest
+
+ @pytest.fixture(params=[0, 1, 2])
+ def fix_with_param(request):
+ return request.param
+
+ def test_foo(request):
+ request.getfixturevalue('fix_with_param')
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "The requested fixture has no parameter defined for test:",
+ " test_call_from_test.py::test_foo",
+ "Requested fixture 'fix_with_param' defined in:",
+ "test_call_from_test.py:4",
+ "Requested here:",
+ "test_call_from_test.py:8",
+ "*1 failed*",
+ ]
+ )
+
+ def test_external_fixture(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(params=[0, 1, 2])
+ def fix_with_param(request):
+ return request.param
+ """
+ )
+
+ pytester.makepyfile(
+ test_external_fixture="""
+ def test_foo(request):
+ request.getfixturevalue('fix_with_param')
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "The requested fixture has no parameter defined for test:",
+ " test_external_fixture.py::test_foo",
+ "",
+ "Requested fixture 'fix_with_param' defined in:",
+ "conftest.py:4",
+ "Requested here:",
+ "test_external_fixture.py:2",
+ "*1 failed*",
+ ]
+ )
+
+ def test_non_relative_path(self, pytester: Pytester) -> None:
+ tests_dir = pytester.mkdir("tests")
+ fixdir = pytester.mkdir("fixtures")
+ fixfile = fixdir.joinpath("fix.py")
+ fixfile.write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+
+ @pytest.fixture(params=[0, 1, 2])
+ def fix_with_param(request):
+ return request.param
+ """
+ ),
+ encoding="utf-8",
+ )
+
+ testfile = tests_dir.joinpath("test_foos.py")
+ testfile.write_text(
+ textwrap.dedent(
+ """\
+ from fix import fix_with_param
+
+ def test_foo(request):
+ request.getfixturevalue('fix_with_param')
+ """
+ ),
+ encoding="utf-8",
+ )
+
+ os.chdir(tests_dir)
+ pytester.syspathinsert(fixdir)
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "The requested fixture has no parameter defined for test:",
+ " test_foos.py::test_foo",
+ "",
+ "Requested fixture 'fix_with_param' defined in:",
+ f"{fixfile}:4",
+ "Requested here:",
+ "test_foos.py:4",
+ "*1 failed*",
+ ]
+ )
+
+ # With non-overlapping rootdir, passing tests_dir.
+ rootdir = pytester.mkdir("rootdir")
+ os.chdir(rootdir)
+ result = pytester.runpytest("--rootdir", rootdir, tests_dir)
+ result.stdout.fnmatch_lines(
+ [
+ "The requested fixture has no parameter defined for test:",
+ " test_foos.py::test_foo",
+ "",
+ "Requested fixture 'fix_with_param' defined in:",
+ f"{fixfile}:4",
+ "Requested here:",
+ f"{testfile}:4",
+ "*1 failed*",
+ ]
+ )
+
+
+def test_pytest_fixture_setup_and_post_finalizer_hook(pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ def pytest_fixture_setup(fixturedef, request):
+ print('ROOT setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
+ def pytest_fixture_post_finalizer(fixturedef, request):
+ print('ROOT finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
+ """
+ )
+ pytester.makepyfile(
+ **{
+ "tests/conftest.py": """
+ def pytest_fixture_setup(fixturedef, request):
+ print('TESTS setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
+ def pytest_fixture_post_finalizer(fixturedef, request):
+ print('TESTS finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
+ """,
+ "tests/test_hooks.py": """
+ import pytest
+
+ @pytest.fixture()
+ def my_fixture():
+ return 'some'
+
+ def test_func(my_fixture):
+ print('TEST test_func')
+ assert my_fixture == 'some'
+ """,
+ }
+ )
+ result = pytester.runpytest("-s")
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(
+ [
+ "*TESTS setup hook called for my_fixture from test_func*",
+ "*ROOT setup hook called for my_fixture from test_func*",
+ "*TEST test_func*",
+ "*TESTS finalizer hook called for my_fixture from test_func*",
+ "*ROOT finalizer hook called for my_fixture from test_func*",
+ ]
+ )
+
+
+def test_fixture_post_finalizer_called_once(pytester: Pytester) -> None:
+ """Test that pytest_fixture_post_finalizer is called only once per fixture teardown.
+
+ When a fixture depends on multiple parametrized fixtures and all their parameters
+ change at the same time, the dependent fixture should be torn down only once,
+ and pytest_fixture_post_finalizer should be called only once for it.
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+
+ finalizer_calls = []
+
+ def pytest_fixture_post_finalizer(fixturedef, request):
+ finalizer_calls.append(fixturedef.argname)
+
+ @pytest.fixture(autouse=True)
+ def check_finalizer_calls(request):
+ yield
+ # After each test, verify no duplicate finalizer calls.
+ if finalizer_calls:
+ assert len(finalizer_calls) == len(set(finalizer_calls)), (
+ f"Duplicate finalizer calls detected: {finalizer_calls}"
+ )
+ finalizer_calls.clear()
+ """
+ )
+ pytester.makepyfile(
+ test_fixtures="""
+ import pytest
+
+ @pytest.fixture(scope="session")
+ def foo(request):
+ return request.param
+
+ @pytest.fixture(scope="session")
+ def bar(request):
+ return request.param
+
+ @pytest.fixture(scope="session")
+ def baz(foo, bar):
+ return f"{foo}-{bar}"
+
+ @pytest.mark.parametrize("foo,bar", [(1, 1)], indirect=True)
+ def test_first(foo, bar, baz):
+ assert foo == 1
+ assert bar == 1
+ assert baz == "1-1"
+
+ @pytest.mark.parametrize("foo,bar", [(2, 2)], indirect=True)
+ def test_second(foo, bar, baz):
+ assert foo == 2
+ assert bar == 2
+ assert baz == "2-2"
+ """
+ )
+ result = pytester.runpytest("-v")
+ # The test passes, which means no duplicate finalizer calls were detected
+ # by the check_finalizer_calls autouse fixture.
+ result.assert_outcomes(passed=2)
+
+
+def test_fixture_post_finalizer_hook_exception(pytester: Pytester) -> None:
+ """Test that exceptions in pytest_fixture_post_finalizer hook are caught.
+
+ Also verifies that the fixture cache is properly reset even when the
+ post_finalizer hook raises an exception, so the fixture can be rebuilt
+ in subsequent tests.
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+
+ def pytest_fixture_post_finalizer(fixturedef, request):
+ if "test_first" in request.node.nodeid:
+ raise RuntimeError("Error in post finalizer hook")
+
+ @pytest.fixture
+ def my_fixture(request):
+ yield request.node.nodeid
+ """
+ )
+ pytester.makepyfile(
+ test_fixtures="""
+ def test_first(my_fixture):
+ assert "test_first" in my_fixture
+
+ def test_second(my_fixture):
+ assert "test_second" in my_fixture
+ """
+ )
+ result = pytester.runpytest("-v", "--setup-show")
+ result.assert_outcomes(passed=2, errors=1)
+ result.stdout.fnmatch_lines(
+ [
+ "*test_first*PASSED",
+ "*test_first*ERROR",
+ "*RuntimeError: Error in post finalizer hook*",
+ ]
+ )
+ # Verify fixture is setup twice (rebuilt for test_second despite error).
+ result.stdout.fnmatch_lines(
+ [
+ "test_fixtures.py::test_first ",
+ " SETUP F my_fixture",
+ " test_fixtures.py::test_first (fixtures used: my_fixture, request)PASSED",
+ "test_fixtures.py::test_first ERROR",
+ "test_fixtures.py::test_second ",
+ " SETUP F my_fixture",
+ " test_fixtures.py::test_second (fixtures used: my_fixture, request)PASSED",
+ " TEARDOWN F my_fixture",
+ ],
+ consecutive=True,
+ )
+
+
+class TestScopeOrdering:
+ """Class of tests that ensure fixtures are ordered based on their scopes (#2405)"""
+
+ @pytest.mark.parametrize("variant", ["mark", "autouse"])
+ def test_func_closure_module_auto(
+ self, pytester: Pytester, variant, monkeypatch
+ ) -> None:
+ """Semantically identical to the example posted in #2405 when ``use_mark=True``"""
+ monkeypatch.setenv("FIXTURE_ACTIVATION_VARIANT", variant)
+ pytester.makepyfile(
+ """
+ import warnings
+ import os
+ import pytest
+ VAR = 'FIXTURE_ACTIVATION_VARIANT'
+ VALID_VARS = ('autouse', 'mark')
+
+ VARIANT = os.environ.get(VAR)
+ if VARIANT is None or VARIANT not in VALID_VARS:
+ warnings.warn("{!r} is not in {}, assuming autouse".format(VARIANT, VALID_VARS) )
+ variant = 'mark'
+
+ @pytest.fixture(scope='module', autouse=VARIANT == 'autouse')
+ def m1(): pass
+
+ if VARIANT=='mark':
+ pytestmark = pytest.mark.usefixtures('m1')
+
+ @pytest.fixture(scope='function', autouse=True)
+ def f1(): pass
+
+ def test_func(m1):
+ pass
+ """
+ )
+ items, _ = pytester.inline_genitems()
+ assert isinstance(items[0], Function)
+ request = TopRequest(items[0], _ispytest=True)
+ assert request.fixturenames == "m1 f1".split()
+
+ def test_func_closure_with_native_fixtures(
+ self, pytester: Pytester, monkeypatch: MonkeyPatch
+ ) -> None:
+ """Sanity check that verifies the order returned by the closures and the actual fixture execution order:
+ The execution order may differ because of fixture inter-dependencies.
+ """
+ monkeypatch.setattr(pytest, "FIXTURE_ORDER", [], raising=False)
+ pytester.makepyfile(
+ """
+ import pytest
+
+ FIXTURE_ORDER = pytest.FIXTURE_ORDER
+
+ @pytest.fixture(scope="session")
+ def s1():
+ FIXTURE_ORDER.append('s1')
+
+ @pytest.fixture(scope="package")
+ def p1():
+ FIXTURE_ORDER.append('p1')
+
+ @pytest.fixture(scope="module")
+ def m1():
+ FIXTURE_ORDER.append('m1')
+
+ @pytest.fixture(scope='session')
+ def my_tmp_path_factory():
+ FIXTURE_ORDER.append('my_tmp_path_factory')
+
+ @pytest.fixture
+ def my_tmp_path(my_tmp_path_factory):
+ FIXTURE_ORDER.append('my_tmp_path')
+
+ @pytest.fixture
+ def f1(my_tmp_path):
+ FIXTURE_ORDER.append('f1')
+
+ @pytest.fixture
+ def f2():
+ FIXTURE_ORDER.append('f2')
+
+ def test_foo(f1, p1, m1, f2, s1): pass
+ """
+ )
+ items, _ = pytester.inline_genitems()
+ assert isinstance(items[0], Function)
+ request = TopRequest(items[0], _ispytest=True)
+ # order of fixtures based on their scope and position in the parameter list
+ assert (
+ request.fixturenames
+ == "s1 my_tmp_path_factory p1 m1 f1 f2 my_tmp_path".split()
+ )
+ pytester.runpytest()
+ # actual fixture execution differs: dependent fixtures must be created first ("my_tmp_path")
+ FIXTURE_ORDER = pytest.FIXTURE_ORDER # type: ignore[attr-defined]
+ assert FIXTURE_ORDER == "s1 my_tmp_path_factory p1 m1 my_tmp_path f1 f2".split()
+
+ def test_func_closure_module(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope='module')
+ def m1(): pass
+
+ @pytest.fixture(scope='function')
+ def f1(): pass
+
+ def test_func(f1, m1):
+ pass
+ """
+ )
+ items, _ = pytester.inline_genitems()
+ assert isinstance(items[0], Function)
+ request = TopRequest(items[0], _ispytest=True)
+ assert request.fixturenames == "m1 f1".split()
+
+ def test_func_closure_scopes_reordered(self, pytester: Pytester) -> None:
+ """Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although
+ fixtures of same scope keep the declared order
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope='session')
+ def s1(): pass
+
+ @pytest.fixture(scope='module')
+ def m1(): pass
+
+ @pytest.fixture(scope='function')
+ def f1(): pass
+
+ @pytest.fixture(scope='function')
+ def f2(): pass
+
+ class Test:
+
+ @pytest.fixture(scope='class')
+ def c1(cls): pass
+
+ def test_func(self, f2, f1, c1, m1, s1):
+ pass
+ """
+ )
+ items, _ = pytester.inline_genitems()
+ assert isinstance(items[0], Function)
+ request = TopRequest(items[0], _ispytest=True)
+ assert request.fixturenames == "s1 m1 c1 f2 f1".split()
+
+ def test_func_closure_same_scope_closer_root_first(
+ self, pytester: Pytester
+ ) -> None:
+ """Auto-use fixtures of same scope are ordered by closer-to-root first"""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(scope='module', autouse=True)
+ def m_conf(): pass
+ """
+ )
+ pytester.makepyfile(
+ **{
+ "sub/conftest.py": """
+ import pytest
+
+ @pytest.fixture(scope='package', autouse=True)
+ def p_sub(): pass
+
+ @pytest.fixture(scope='module', autouse=True)
+ def m_sub(): pass
+ """,
+ "sub/__init__.py": "",
+ "sub/test_func.py": """
+ import pytest
+
+ @pytest.fixture(scope='module', autouse=True)
+ def m_test(): pass
+
+ @pytest.fixture(scope='function')
+ def f1(): pass
+
+ def test_func(m_test, f1):
+ pass
+ """,
+ }
+ )
+ items, _ = pytester.inline_genitems()
+ assert isinstance(items[0], Function)
+ request = TopRequest(items[0], _ispytest=True)
+ assert request.fixturenames == "p_sub m_conf m_sub m_test f1".split()
+
+ def test_func_closure_all_scopes_complex(self, pytester: Pytester) -> None:
+ """Complex test involving all scopes and mixing autouse with normal fixtures"""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(scope='session')
+ def s1(): pass
+
+ @pytest.fixture(scope='package', autouse=True)
+ def p1(): pass
+ """
+ )
+ pytester.makepyfile(**{"__init__.py": ""})
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope='module', autouse=True)
+ def m1(): pass
+
+ @pytest.fixture(scope='module')
+ def m2(s1): pass
+
+ @pytest.fixture(scope='function')
+ def f1(): pass
+
+ @pytest.fixture(scope='function')
+ def f2(): pass
+
+ class Test:
+
+ @pytest.fixture(scope='class', autouse=True)
+ def c1(self):
+ pass
+
+ def test_func(self, f2, f1, m2):
+ pass
+ """
+ )
+ items, _ = pytester.inline_genitems()
+ assert isinstance(items[0], Function)
+ request = TopRequest(items[0], _ispytest=True)
+ assert request.fixturenames == "s1 p1 m1 m2 c1 f2 f1".split()
+
+ def test_parametrized_package_scope_reordering(self, pytester: Pytester) -> None:
+ """A parameterized package-scoped fixture correctly reorders items to
+ minimize setups & teardowns.
+
+ Regression test for #12328.
+ """
+ pytester.makepyfile(
+ __init__="",
+ conftest="""
+ import pytest
+ @pytest.fixture(scope="package", params=["a", "b"])
+ def fix(request):
+ return request.param
+ """,
+ test_1="def test1(fix): pass",
+ test_2="def test2(fix): pass",
+ )
+
+ result = pytester.runpytest("--setup-plan")
+ assert result.ret == ExitCode.OK
+ result.stdout.fnmatch_lines(
+ [
+ " SETUP P fix['a']",
+ " test_1.py::test1[a] (fixtures used: fix, request)",
+ " test_2.py::test2[a] (fixtures used: fix, request)",
+ " TEARDOWN P fix['a']",
+ " SETUP P fix['b']",
+ " test_1.py::test1[b] (fixtures used: fix, request)",
+ " test_2.py::test2[b] (fixtures used: fix, request)",
+ " TEARDOWN P fix['b']",
+ ],
+ )
+
+ def test_multiple_packages(self, pytester: Pytester) -> None:
+ """Complex test involving multiple package fixtures. Make sure teardowns
+ are executed in order.
+ .
+ └── root
+ ├── __init__.py
+ ├── sub1
+ │ ├── __init__.py
+ │ ├── conftest.py
+ │ └── test_1.py
+ └── sub2
+ ├── __init__.py
+ ├── conftest.py
+ └── test_2.py
+ """
+ root = pytester.mkdir("root")
+ root.joinpath("__init__.py").write_text("values = []", encoding="utf-8")
+ sub1 = root.joinpath("sub1")
+ sub1.mkdir()
+ sub1.joinpath("__init__.py").touch()
+ sub1.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ from .. import values
+ @pytest.fixture(scope="package")
+ def fix():
+ values.append("pre-sub1")
+ yield values
+ assert values.pop() == "pre-sub1"
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub1.joinpath("test_1.py").write_text(
+ textwrap.dedent(
+ """\
+ from .. import values
+ def test_1(fix):
+ assert values == ["pre-sub1"]
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub2 = root.joinpath("sub2")
+ sub2.mkdir()
+ sub2.joinpath("__init__.py").touch()
+ sub2.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ from .. import values
+ @pytest.fixture(scope="package")
+ def fix():
+ values.append("pre-sub2")
+ yield values
+ assert values.pop() == "pre-sub2"
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub2.joinpath("test_2.py").write_text(
+ textwrap.dedent(
+ """\
+ from .. import values
+ def test_2(fix):
+ assert values == ["pre-sub2"]
+ """
+ ),
+ encoding="utf-8",
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_class_fixture_self_instance(self, pytester: Pytester) -> None:
+ """Check that plugin classes which implement fixtures receive the plugin instance
+ as self (see #2270).
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+
+ def pytest_configure(config):
+ config.pluginmanager.register(MyPlugin())
+
+ class MyPlugin():
+ def __init__(self):
+ self.arg = 1
+
+ @pytest.fixture(scope='function')
+ def myfix(self):
+ assert isinstance(self, MyPlugin)
+ return self.arg
+ """
+ )
+
+ pytester.makepyfile(
+ """
+ class TestClass(object):
+ def test_1(self, myfix):
+ assert myfix == 1
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+
+def test_call_fixture_function_error():
+ """Check if an error is raised if a fixture function is called directly (#4545)"""
+
+ @pytest.fixture
+ def fix():
+ raise NotImplementedError()
+
+ with pytest.raises(pytest.fail.Exception):
+ assert fix() == 1
+
+
+def test_fixture_double_decorator(pytester: Pytester) -> None:
+ """Check if an error is raised when using @pytest.fixture twice."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ @pytest.fixture
+ def fixt():
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(errors=1)
+ result.stdout.fnmatch_lines(
+ [
+ "E * ValueError: @pytest.fixture is being applied more than once to the same function 'fixt'"
+ ]
+ )
+
+
+def test_fixture_class(pytester: Pytester) -> None:
+ """Check if an error is raised when using @pytest.fixture on a class."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ class A:
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(errors=1)
+
+
+def test_fixture_param_shadowing(pytester: Pytester) -> None:
+ """Parametrized arguments would be shadowed if a fixture with the same name also exists (#5036)"""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=['a', 'b'])
+ def argroot(request):
+ return request.param
+
+ @pytest.fixture
+ def arg(argroot):
+ return argroot
+
+ # This should only be parametrized directly
+ @pytest.mark.parametrize("arg", [1])
+ def test_direct(arg):
+ assert arg == 1
+
+ # This should be parametrized based on the fixtures
+ def test_normal_fixture(arg):
+ assert isinstance(arg, str)
+
+ # Indirect should still work:
+
+ @pytest.fixture
+ def arg2(request):
+ return 2*request.param
+
+ @pytest.mark.parametrize("arg2", [1], indirect=True)
+ def test_indirect(arg2):
+ assert arg2 == 2
+ """
+ )
+ # Only one test should have run
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=4)
+ result.stdout.fnmatch_lines(["*::test_direct[[]1[]]*"])
+ result.stdout.fnmatch_lines(["*::test_normal_fixture[[]a[]]*"])
+ result.stdout.fnmatch_lines(["*::test_normal_fixture[[]b[]]*"])
+ result.stdout.fnmatch_lines(["*::test_indirect[[]1[]]*"])
+
+
+def test_fixture_named_request(pytester: Pytester) -> None:
+ pytester.copy_example("fixtures/test_fixture_named_request.py")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*'request' is a reserved word for fixtures, use another name:",
+ " *test_fixture_named_request.py:8",
+ ]
+ )
+
+
+def test_indirect_fixture_does_not_break_scope(pytester: Pytester) -> None:
+ """Ensure that fixture scope is respected when using indirect fixtures (#570)"""
+ pytester.makepyfile(
+ """
+ import pytest
+ instantiated = []
+
+ @pytest.fixture(scope="session")
+ def fixture_1(request):
+ instantiated.append(("fixture_1", request.param))
+
+
+ @pytest.fixture(scope="session")
+ def fixture_2(request):
+ instantiated.append(("fixture_2", request.param))
+
+
+ scenarios = [
+ ("A", "a1"),
+ ("A", "a2"),
+ ("B", "b1"),
+ ("B", "b2"),
+ ("C", "c1"),
+ ("C", "c2"),
+ ]
+
+ @pytest.mark.parametrize(
+ "fixture_1,fixture_2", scenarios, indirect=["fixture_1", "fixture_2"]
+ )
+ def test_create_fixtures(fixture_1, fixture_2):
+ pass
+
+
+ def test_check_fixture_instantiations():
+ assert instantiated == [
+ ('fixture_1', 'A'),
+ ('fixture_2', 'a1'),
+ ('fixture_2', 'a2'),
+ ('fixture_1', 'B'),
+ ('fixture_2', 'b1'),
+ ('fixture_2', 'b2'),
+ ('fixture_1', 'C'),
+ ('fixture_2', 'c1'),
+ ('fixture_2', 'c2'),
+ ]
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=7)
+
+
+def test_fixture_parametrization_nparray(pytester: Pytester) -> None:
+ pytest.importorskip("numpy")
+
+ pytester.makepyfile(
+ """
+ from numpy import linspace
+ from pytest import fixture
+
+ @fixture(params=linspace(1, 10, 10))
+ def value(request):
+ return request.param
+
+ def test_bug(value):
+ assert value == value
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=10)
+
+
+def test_fixture_arg_ordering(pytester: Pytester) -> None:
+ """
+ This test describes how fixtures in the same scope but without explicit dependencies
+ between them are created. While users should make dependencies explicit, often
+ they rely on this order, so this test exists to catch regressions in this regard.
+ See #6540 and #6492.
+ """
+ p1 = pytester.makepyfile(
+ """
+ import pytest
+
+ suffixes = []
+
+ @pytest.fixture
+ def fix_1(): suffixes.append("fix_1")
+ @pytest.fixture
+ def fix_2(): suffixes.append("fix_2")
+ @pytest.fixture
+ def fix_3(): suffixes.append("fix_3")
+ @pytest.fixture
+ def fix_4(): suffixes.append("fix_4")
+ @pytest.fixture
+ def fix_5(): suffixes.append("fix_5")
+
+ @pytest.fixture
+ def fix_combined(fix_1, fix_2, fix_3, fix_4, fix_5): pass
+
+ def test_suffix(fix_combined):
+ assert suffixes == ["fix_1", "fix_2", "fix_3", "fix_4", "fix_5"]
+ """
+ )
+ result = pytester.runpytest("-vv", str(p1))
+ assert result.ret == 0
+
+
+def test_yield_fixture_with_no_value(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.fixture(name='custom')
+ def empty_yield():
+ if False:
+ yield
+
+ def test_fixt(custom):
+ pass
+ """
+ )
+ expected = "E ValueError: custom did not yield a value"
+ result = pytester.runpytest()
+ result.assert_outcomes(errors=1)
+ result.stdout.fnmatch_lines([expected])
+ assert result.ret == ExitCode.TESTS_FAILED
+
+
+def test_deduplicate_names() -> None:
+ items = deduplicate_names("abacd")
+ assert items == ("a", "b", "c", "d")
+ items = deduplicate_names((*items, "g", "f", "g", "e", "b"))
+ assert items == ("a", "b", "c", "d", "g", "f", "e")
+
+
+def test_staticmethod_classmethod_fixture_instance(pytester: Pytester) -> None:
+ """Ensure that static and class methods get and have access to a fresh
+ instance.
+
+ This also ensures `setup_method` works well with static and class methods.
+
+ Regression test for #12065.
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ class Test:
+ ran_setup_method = False
+ ran_fixture = False
+
+ def setup_method(self):
+ assert not self.ran_setup_method
+ self.ran_setup_method = True
+
+ @pytest.fixture(autouse=True)
+ def fixture(self):
+ assert not self.ran_fixture
+ self.ran_fixture = True
+
+ def test_method(self):
+ assert self.ran_setup_method
+ assert self.ran_fixture
+
+ @staticmethod
+ def test_1(request):
+ assert request.instance.ran_setup_method
+ assert request.instance.ran_fixture
+
+ @classmethod
+ def test_2(cls, request):
+ assert request.instance.ran_setup_method
+ assert request.instance.ran_fixture
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.OK
+ result.assert_outcomes(passed=3)
+
+
+def test_scoped_fixture_caching(pytester: Pytester) -> None:
+ """Make sure setup and finalization is only run once when using scoped fixture
+ multiple times."""
+ pytester.makepyfile(
+ """
+ from __future__ import annotations
+
+ from typing import Generator
+
+ import pytest
+ executed: list[str] = []
+ @pytest.fixture(scope="class")
+ def fixture_1() -> Generator[None, None, None]:
+ executed.append("fix setup")
+ yield
+ executed.append("fix teardown")
+
+
+ class TestFixtureCaching:
+ def test_1(self, fixture_1: None) -> None:
+ assert executed == ["fix setup"]
+
+ def test_2(self, fixture_1: None) -> None:
+ assert executed == ["fix setup"]
+
+
+ def test_expected_setup_and_teardown() -> None:
+ assert executed == ["fix setup", "fix teardown"]
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+
+def test_scoped_fixture_caching_exception(pytester: Pytester) -> None:
+ """Make sure setup & finalization is only run once for scoped fixture, with a cached exception."""
+ pytester.makepyfile(
+ """
+ from __future__ import annotations
+
+ import pytest
+ executed_crash: list[str] = []
+
+
+ @pytest.fixture(scope="class")
+ def fixture_crash(request: pytest.FixtureRequest) -> None:
+ executed_crash.append("fix_crash setup")
+
+ def my_finalizer() -> None:
+ executed_crash.append("fix_crash teardown")
+
+ request.addfinalizer(my_finalizer)
+
+ raise Exception("foo")
+
+
+ class TestFixtureCachingException:
+ @pytest.mark.xfail
+ def test_crash_1(self, fixture_crash: None) -> None:
+ ...
+
+ @pytest.mark.xfail
+ def test_crash_2(self, fixture_crash: None) -> None:
+ ...
+
+
+ def test_crash_expected_setup_and_teardown() -> None:
+ assert executed_crash == ["fix_crash setup", "fix_crash teardown"]
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+
+def test_scoped_fixture_teardown_order(pytester: Pytester) -> None:
+ """
+ Make sure teardowns happen in reverse order of setup with scoped fixtures, when
+ a later test only depends on a subset of scoped fixtures.
+
+ Regression test for https://github.com/pytest-dev/pytest/issues/1489
+ """
+ pytester.makepyfile(
+ """
+ from typing import Generator
+
+ import pytest
+
+
+ last_executed = ""
+
+
+ @pytest.fixture(scope="module")
+ def fixture_1() -> Generator[None, None, None]:
+ global last_executed
+ assert last_executed == ""
+ last_executed = "fixture_1_setup"
+ yield
+ assert last_executed == "fixture_2_teardown"
+ last_executed = "fixture_1_teardown"
+
+
+ @pytest.fixture(scope="module")
+ def fixture_2() -> Generator[None, None, None]:
+ global last_executed
+ assert last_executed == "fixture_1_setup"
+ last_executed = "fixture_2_setup"
+ yield
+ assert last_executed == "run_test"
+ last_executed = "fixture_2_teardown"
+
+
+ def test_fixture_teardown_order(fixture_1: None, fixture_2: None) -> None:
+ global last_executed
+ assert last_executed == "fixture_2_setup"
+ last_executed = "run_test"
+
+
+ def test_2(fixture_1: None) -> None:
+ # This would previously queue an additional teardown of fixture_1,
+ # despite fixture_1's value being cached, which caused fixture_1 to be
+ # torn down before fixture_2 - violating the rule that teardowns should
+ # happen in reverse order of setup.
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+
+def test_subfixture_teardown_order(pytester: Pytester) -> None:
+ """
+ Make sure fixtures don't re-register their finalization in parent fixtures multiple
+ times, causing ordering failure in their teardowns.
+
+ Regression test for #12135
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ execution_order = []
+
+ @pytest.fixture(scope="class")
+ def fixture_1():
+ ...
+
+ @pytest.fixture(scope="class")
+ def fixture_2(fixture_1):
+ execution_order.append("setup 2")
+ yield
+ execution_order.append("teardown 2")
+
+ @pytest.fixture(scope="class")
+ def fixture_3(fixture_1):
+ execution_order.append("setup 3")
+ yield
+ execution_order.append("teardown 3")
+
+ class TestFoo:
+ def test_initialize_fixtures(self, fixture_2, fixture_3):
+ ...
+
+ # This would previously reschedule fixture_2's finalizer in the parent fixture,
+ # causing it to be torn down before fixture 3.
+ def test_reschedule_fixture_2(self, fixture_2):
+ ...
+
+ # Force finalization directly on fixture_1
+ # Otherwise the cleanup would sequence 3&2 before 1 as normal.
+ @pytest.mark.parametrize("fixture_1", [None], indirect=["fixture_1"])
+ def test_finalize_fixture_1(self, fixture_1):
+ ...
+
+ def test_result():
+ assert execution_order == ["setup 2", "setup 3", "teardown 3", "teardown 2"]
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+
+def test_parametrized_fixture_scope_allowed(pytester: Pytester) -> None:
+ """
+ Make sure scope from parametrize does not affect fixture's ability to be
+ depended upon.
+
+ Regression test for #13248
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope="session")
+ def my_fixture(request):
+ return getattr(request, "param", None)
+
+ @pytest.fixture(scope="session")
+ def another_fixture(my_fixture):
+ return my_fixture
+
+ @pytest.mark.parametrize("my_fixture", ["a value"], indirect=True, scope="function")
+ def test_foo(another_fixture):
+ assert another_fixture == "a value"
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+
+
+def test_collect_positional_only(pytester: Pytester) -> None:
+ """Support the collection of tests with positional-only arguments (#13376)."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ class Test:
+ @pytest.fixture
+ def fix(self):
+ return 1
+
+ def test_method(self, /, fix):
+ assert fix == 1
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+
+
+def test_parametrization_dependency_pruning(pytester: Pytester) -> None:
+ """Test that when a fixture is dynamically shadowed by parameterization, it
+ is properly pruned and not executed."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+
+ # This fixture should never run because shadowed_fixture is parametrized.
+ @pytest.fixture
+ def boom():
+ raise RuntimeError("BOOM!")
+
+
+ # This fixture is shadowed by metafunc.parametrize in pytest_generate_tests.
+ @pytest.fixture
+ def shadowed_fixture(boom):
+ return "fixture_value"
+
+
+ # Dynamically parametrize shadowed_fixture, replacing the fixture with direct values.
+ def pytest_generate_tests(metafunc):
+ if "shadowed_fixture" in metafunc.fixturenames:
+ metafunc.parametrize("shadowed_fixture", ["param1", "param2"])
+
+
+ # This test should receive shadowed_fixture as a parametrized value, and
+ # boom should not explode.
+ def test_shadowed(shadowed_fixture):
+ assert shadowed_fixture in ["param1", "param2"]
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=2)
+
+
+def test_fixture_closure_with_overrides(pytester: Pytester) -> None:
+ """Test that an item's static fixture closure properly includes transitive
+ dependencies through overridden fixtures (#13773)."""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def db(): pass
+
+ @pytest.fixture
+ def app(db): pass
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ # Overrides conftest-level `app` and requests it.
+ @pytest.fixture
+ def app(app): pass
+
+ class TestClass:
+ # Overrides module-level `app` and requests it.
+ @pytest.fixture
+ def app(self, app): pass
+
+ def test_something(self, request, app):
+ # Both dynamic and static fixture closures should include 'db'.
+ assert 'db' in request.fixturenames
+ assert 'db' in request.node.fixturenames
+ # No dynamic dependencies, should be equal.
+ assert set(request.fixturenames) == set(request.node.fixturenames)
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=1)
+
+
+def test_fixture_closure_with_overrides_and_intermediary(pytester: Pytester) -> None:
+ """Test that an item's static fixture closure properly includes transitive
+ dependencies through overridden fixtures (#13773).
+
+ A more complicated case than test_fixture_closure_with_overrides, adds an
+ intermediary so the override chain is not direct.
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def db(): pass
+
+ @pytest.fixture
+ def app(db): pass
+
+ @pytest.fixture
+ def intermediate(app): pass
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ # Overrides conftest-level `app` and requests it.
+ @pytest.fixture
+ def app(intermediate): pass
+
+ class TestClass:
+ # Overrides module-level `app` and requests it.
+ @pytest.fixture
+ def app(self, app): pass
+
+ def test_something(self, request, app):
+ # Both dynamic and static fixture closures should include 'db'.
+ assert 'db' in request.fixturenames
+ assert 'db' in request.node.fixturenames
+ # No dynamic dependencies, should be equal.
+ assert set(request.fixturenames) == set(request.node.fixturenames)
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=1)
+
+
+def test_fixture_closure_with_broken_override_chain(pytester: Pytester) -> None:
+ """Test that an item's static fixture closure properly includes transitive
+ dependencies through overridden fixtures (#13773).
+
+ A more complicated case than test_fixture_closure_with_overrides, one of the
+ fixtures in the chain doesn't call its super, so it shouldn't be included.
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def db(): pass
+
+ @pytest.fixture
+ def app(db): pass
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ # Overrides conftest-level `app` and *doesn't* request it.
+ @pytest.fixture
+ def app(): pass
+
+ class TestClass:
+ # Overrides module-level `app` and requests it.
+ @pytest.fixture
+ def app(self, app): pass
+
+ def test_something(self, request, app):
+ # Both dynamic and static fixture closures should include 'db'.
+ assert 'db' not in request.fixturenames
+ assert 'db' not in request.node.fixturenames
+ # No dynamic dependencies, should be equal.
+ assert set(request.fixturenames) == set(request.node.fixturenames)
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=1)
+
+
+def test_fixture_closure_handles_circular_dependencies(pytester: Pytester) -> None:
+ """Test that getfixtureclosure properly handles circular dependencies.
+
+ The test will error in the runtest phase due to the fixture loop,
+ but the closure computation still completes.
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ # Direct circular dependency.
+ @pytest.fixture
+ def fix_a(fix_b): pass
+
+ @pytest.fixture
+ def fix_b(fix_a): pass
+
+ # Indirect circular dependency through multiple fixtures.
+ @pytest.fixture
+ def fix_x(fix_y): pass
+
+ @pytest.fixture
+ def fix_y(fix_z): pass
+
+ @pytest.fixture
+ def fix_z(fix_x): pass
+
+ def test_circular_deps(fix_a, fix_x):
+ pass
+ """
+ )
+ items, _hookrec = pytester.inline_genitems()
+ assert isinstance(items[0], Function)
+ assert items[0].fixturenames == ["fix_a", "fix_x", "fix_b", "fix_y", "fix_z"]
+
+
+def test_fixture_closure_handles_diamond_dependencies(pytester: Pytester) -> None:
+ """Test that getfixtureclosure properly handles diamond dependencies."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def db(): pass
+
+ @pytest.fixture
+ def user(db): pass
+
+ @pytest.fixture
+ def session(db): pass
+
+ @pytest.fixture
+ def app(user, session): pass
+
+ def test_diamond_deps(request, app):
+ assert request.node.fixturenames == ["request", "app", "user", "db", "session"]
+ assert request.fixturenames == ["request", "app", "user", "db", "session"]
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=1)
+
+
+def test_fixture_closure_with_complex_override_and_shared_deps(
+ pytester: Pytester,
+) -> None:
+ """Test that shared dependencies in override chains are processed only once."""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture
+ def db(): pass
+
+ @pytest.fixture
+ def cache(): pass
+
+ @pytest.fixture
+ def settings(): pass
+
+ @pytest.fixture
+ def app(db, cache, settings): pass
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ # Override app, but also directly use cache and settings.
+ # This creates multiple paths to the same fixtures.
+ @pytest.fixture
+ def app(app, cache, settings): pass
+
+ class TestClass:
+ # Another override that uses both app and cache.
+ @pytest.fixture
+ def app(self, app, cache): pass
+
+ def test_shared_deps(self, request, app):
+ assert request.node.fixturenames == ["request", "app", "db", "cache", "settings"]
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=1)
+
+
+def test_fixture_closure_with_parametrize_ignore(pytester: Pytester) -> None:
+ """Test that getfixtureclosure properly handles parametrization argnames
+ which override a fixture."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def fix1(fix2): pass
+
+ @pytest.fixture
+ def fix2(fix3): pass
+
+ @pytest.fixture
+ def fix3(): pass
+
+ @pytest.mark.parametrize('fix2', ['2'])
+ def test_it(request, fix1):
+ assert request.node.fixturenames == ["request", "fix1", "fix2"]
+ assert request.fixturenames == ["request", "fix1", "fix2"]
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=1)
+
+
+def test_overridden_fixture_depends_on_parametrized(pytester: Pytester) -> None:
+ """#11075"""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(params=["foo"])
+ def fixture_foo(request):
+ yield request.param
+
+ @pytest.fixture
+ def fixture_bar(fixture_foo):
+ yield fixture_foo
+
+ class TestFoobar:
+ @pytest.fixture
+ def fixture_bar(self, fixture_bar):
+ yield fixture_bar
+
+ def test_foobar(self, fixture_bar):
+ assert fixture_bar == "foo"
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=1)
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/integration.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8f8d0ffae9cee12dac13b046442421bcd1d9f12
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/integration.py
@@ -0,0 +1,465 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from _pytest._code import getfslineno
+from _pytest.fixtures import getfixturemarker
+from _pytest.pytester import Pytester
+from _pytest.python import Function
+import pytest
+
+
+def test_wrapped_getfslineno() -> None:
+ def func():
+ pass
+
+ def wrap(f):
+ func.__wrapped__ = f # type: ignore
+ func.patchings = ["qwe"] # type: ignore
+ return func
+
+ @wrap
+ def wrapped_func(x, y, z):
+ pass
+
+ _fs, lineno = getfslineno(wrapped_func)
+ _fs2, lineno2 = getfslineno(wrap)
+ assert lineno > lineno2, "getfslineno does not unwrap correctly"
+
+
+class TestMockDecoration:
+ def test_wrapped_getfuncargnames(self) -> None:
+ from _pytest.compat import getfuncargnames
+
+ def wrap(f):
+ def func():
+ pass
+
+ func.__wrapped__ = f # type: ignore
+ return func
+
+ @wrap
+ def f(x):
+ pass
+
+ values = getfuncargnames(f)
+ assert values == ("x",)
+
+ def test_getfuncargnames_patching(self):
+ from unittest.mock import patch
+
+ from _pytest.compat import getfuncargnames
+
+ class T:
+ def original(self, x, y, z):
+ pass
+
+ @patch.object(T, "original")
+ def f(x, y, z):
+ pass
+
+ values = getfuncargnames(f)
+ assert values == ("y", "z")
+
+ def test_unittest_mock(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import unittest.mock
+ class T(unittest.TestCase):
+ @unittest.mock.patch("os.path.abspath")
+ def test_hello(self, abspath):
+ import os
+ os.path.abspath("hello")
+ abspath.assert_any_call("hello")
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_unittest_mock_and_fixture(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import os.path
+ import unittest.mock
+ import pytest
+
+ @pytest.fixture
+ def inject_me():
+ pass
+
+ @unittest.mock.patch.object(os.path, "abspath",
+ new=unittest.mock.MagicMock)
+ def test_hello(inject_me):
+ import os
+ os.path.abspath("hello")
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_unittest_mock_and_pypi_mock(self, pytester: Pytester) -> None:
+ pytest.importorskip("mock", "1.0.1")
+ pytester.makepyfile(
+ """
+ import mock
+ import unittest.mock
+ class TestBoth(object):
+ @unittest.mock.patch("os.path.abspath")
+ def test_hello(self, abspath):
+ import os
+ os.path.abspath("hello")
+ abspath.assert_any_call("hello")
+
+ @mock.patch("os.path.abspath")
+ def test_hello_mock(self, abspath):
+ import os
+ os.path.abspath("hello")
+ abspath.assert_any_call("hello")
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ def test_mock_sentinel_check_against_numpy_like(self, pytester: Pytester) -> None:
+ """Ensure our function that detects mock arguments compares against sentinels using
+ identity to circumvent objects which can't be compared with equality against others
+ in a truth context, like with numpy arrays (#5606).
+ """
+ pytester.makepyfile(
+ dummy="""
+ class NumpyLike:
+ def __init__(self, value):
+ self.value = value
+ def __eq__(self, other):
+ raise ValueError("like numpy, cannot compare against others for truth")
+ FOO = NumpyLike(10)
+ """
+ )
+ pytester.makepyfile(
+ """
+ from unittest.mock import patch
+ import dummy
+ class Test(object):
+ @patch("dummy.FOO", new=dummy.NumpyLike(50))
+ def test_hello(self):
+ assert dummy.FOO.value == 50
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+ def test_mock(self, pytester: Pytester) -> None:
+ pytest.importorskip("mock", "1.0.1")
+ pytester.makepyfile(
+ """
+ import os
+ import unittest
+ import mock
+
+ class T(unittest.TestCase):
+ @mock.patch("os.path.abspath")
+ def test_hello(self, abspath):
+ os.path.abspath("hello")
+ abspath.assert_any_call("hello")
+ def mock_basename(path):
+ return "mock_basename"
+ @mock.patch("os.path.abspath")
+ @mock.patch("os.path.normpath")
+ @mock.patch("os.path.basename", new=mock_basename)
+ def test_something(normpath, abspath, tmp_path):
+ abspath.return_value = "this"
+ os.path.normpath(os.path.abspath("hello"))
+ normpath.assert_any_call("this")
+ assert os.path.basename("123") == "mock_basename"
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+ calls = reprec.getcalls("pytest_runtest_logreport")
+ funcnames = [
+ call.report.location[2] for call in calls if call.report.when == "call"
+ ]
+ assert funcnames == ["T.test_hello", "test_something"]
+
+ def test_mock_sorting(self, pytester: Pytester) -> None:
+ pytest.importorskip("mock", "1.0.1")
+ pytester.makepyfile(
+ """
+ import os
+ import mock
+
+ @mock.patch("os.path.abspath")
+ def test_one(abspath):
+ pass
+ @mock.patch("os.path.abspath")
+ def test_two(abspath):
+ pass
+ @mock.patch("os.path.abspath")
+ def test_three(abspath):
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ calls = reprec.getreports("pytest_runtest_logreport")
+ calls = [x for x in calls if x.when == "call"]
+ names = [x.nodeid.split("::")[-1] for x in calls]
+ assert names == ["test_one", "test_two", "test_three"]
+
+ def test_mock_double_patch_issue473(self, pytester: Pytester) -> None:
+ pytest.importorskip("mock", "1.0.1")
+ pytester.makepyfile(
+ """
+ from mock import patch
+ from pytest import mark
+
+ @patch('os.getcwd')
+ @patch('os.path')
+ @mark.slow
+ class TestSimple(object):
+ def test_simple_thing(self, mock_path, mock_getcwd):
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+
+class TestReRunTests:
+ def test_rerun(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ from _pytest.runner import runtestprotocol
+ def pytest_runtest_protocol(item, nextitem):
+ runtestprotocol(item, log=False, nextitem=nextitem)
+ runtestprotocol(item, log=True, nextitem=nextitem)
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+ count = 0
+ req = None
+ @pytest.fixture
+ def fix(request):
+ global count, req
+ assert request != req
+ req = request
+ print("fix count %s" % count)
+ count += 1
+ def test_fix(fix):
+ pass
+ """
+ )
+ result = pytester.runpytest("-s")
+ result.stdout.fnmatch_lines(
+ """
+ *fix count 0*
+ *fix count 1*
+ """
+ )
+ result.stdout.fnmatch_lines(
+ """
+ *2 passed*
+ """
+ )
+
+
+def test_pytestconfig_is_session_scoped() -> None:
+ from _pytest.fixtures import pytestconfig
+
+ marker = getfixturemarker(pytestconfig)
+ assert marker is not None
+ assert marker.scope == "session"
+
+
+class TestNoselikeTestAttribute:
+ def test_module_with_global_test(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ __test__ = False
+ def test_hello():
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ assert not reprec.getfailedcollections()
+ calls = reprec.getreports("pytest_runtest_logreport")
+ assert not calls
+
+ def test_class_and_method(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ __test__ = True
+ def test_func():
+ pass
+ test_func.__test__ = False
+
+ class TestSome(object):
+ __test__ = False
+ def test_method(self):
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ assert not reprec.getfailedcollections()
+ calls = reprec.getreports("pytest_runtest_logreport")
+ assert not calls
+
+ def test_unittest_class(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import unittest
+ class TC(unittest.TestCase):
+ def test_1(self):
+ pass
+ class TC2(unittest.TestCase):
+ __test__ = False
+ def test_2(self):
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ assert not reprec.getfailedcollections()
+ call = reprec.getcalls("pytest_collection_modifyitems")[0]
+ assert len(call.items) == 1
+ assert call.items[0].cls.__name__ == "TC"
+
+ def test_class_with_nasty_getattr(self, pytester: Pytester) -> None:
+ """Make sure we handle classes with a custom nasty __getattr__ right.
+
+ With a custom __getattr__ which e.g. returns a function (like with a
+ RPC wrapper), we shouldn't assume this meant "__test__ = True".
+ """
+ # https://github.com/pytest-dev/pytest/issues/1204
+ pytester.makepyfile(
+ """
+ class MetaModel(type):
+
+ def __getattr__(cls, key):
+ return lambda: None
+
+
+ BaseModel = MetaModel('Model', (), {})
+
+
+ class Model(BaseModel):
+
+ __metaclass__ = MetaModel
+
+ def test_blah(self):
+ pass
+ """
+ )
+ reprec = pytester.inline_run()
+ assert not reprec.getfailedcollections()
+ call = reprec.getcalls("pytest_collection_modifyitems")[0]
+ assert not call.items
+
+
+class TestParameterize:
+ """#351"""
+
+ def test_idfn_marker(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ def idfn(param):
+ if param == 0:
+ return 'spam'
+ elif param == 1:
+ return 'ham'
+ else:
+ return None
+
+ @pytest.mark.parametrize('a,b', [(0, 2), (1, 2)], ids=idfn)
+ def test_params(a, b):
+ pass
+ """
+ )
+ res = pytester.runpytest("--collect-only")
+ res.stdout.fnmatch_lines(["*spam-2*", "*ham-2*"])
+
+ def test_idfn_fixture(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ def idfn(param):
+ if param == 0:
+ return 'spam'
+ elif param == 1:
+ return 'ham'
+ else:
+ return None
+
+ @pytest.fixture(params=[0, 1], ids=idfn)
+ def a(request):
+ return request.param
+
+ @pytest.fixture(params=[1, 2], ids=idfn)
+ def b(request):
+ return request.param
+
+ def test_params(a, b):
+ pass
+ """
+ )
+ res = pytester.runpytest("--collect-only")
+ res.stdout.fnmatch_lines(["*spam-2*", "*ham-2*"])
+
+ def test_param_rejects_usefixtures(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize("x", [
+ pytest.param(1, marks=[pytest.mark.usefixtures("foo")]),
+ ])
+ def test_foo(x):
+ pass
+ """
+ )
+ res = pytester.runpytest("--collect-only")
+ res.stdout.fnmatch_lines(
+ ["*test_param_rejects_usefixtures.py:4*", "*pytest.param(*"]
+ )
+
+
+def test_function_instance(pytester: Pytester) -> None:
+ items = pytester.getitems(
+ """
+ def test_func(): pass
+
+ class TestIt:
+ def test_method(self): pass
+
+ @classmethod
+ def test_class(cls): pass
+
+ @staticmethod
+ def test_static(): pass
+ """
+ )
+ assert len(items) == 4
+
+ assert isinstance(items[0], Function)
+ assert items[0].name == "test_func"
+ assert items[0].instance is None
+
+ assert isinstance(items[1], Function)
+ assert items[1].name == "test_method"
+ assert items[1].instance is not None
+ assert items[1].instance.__class__.__name__ == "TestIt"
+
+ # Even class and static methods get an instance!
+ # This is the instance used for bound fixture methods, which
+ # class/staticmethod tests are perfectly able to request.
+ assert isinstance(items[2], Function)
+ assert items[2].name == "test_class"
+ assert items[2].instance is not None
+
+ assert isinstance(items[3], Function)
+ assert items[3].name == "test_static"
+ assert items[3].instance is not None
+
+ assert items[1].instance is not items[2].instance is not items[3].instance
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/metafunc.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/metafunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..026589d65f50bb53a83775d8bf636f90f7f17bda
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/metafunc.py
@@ -0,0 +1,2414 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from collections.abc import Iterator
+from collections.abc import Sequence
+import dataclasses
+import itertools
+import re
+import sys
+import textwrap
+from typing import Any
+from typing import cast
+
+import hypothesis
+from hypothesis import strategies
+
+from _pytest import fixtures
+from _pytest import python
+from _pytest.compat import getfuncargnames
+from _pytest.compat import NOTSET
+from _pytest.outcomes import fail
+from _pytest.outcomes import Failed
+from _pytest.pytester import Pytester
+from _pytest.python import Function
+from _pytest.python import IdMaker
+from _pytest.scope import Scope
+import pytest
+
+
+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: dict[str, list[fixtures.FixtureDef[object]]] = {}
+
+ def __init__(self, names):
+ self.names_closure = names
+
+ @dataclasses.dataclass
+ class FixtureManagerMock:
+ config: Any
+
+ @dataclasses.dataclass
+ class SessionMock:
+ _fixturemanager: FixtureManagerMock
+
+ @dataclasses.dataclass
+ class DefinitionMock(python.FunctionDefinition):
+ _nodeid: str
+ obj: object
+
+ names = getfuncargnames(func)
+ fixtureinfo: Any = FuncFixtureInfoMock(names)
+ definition: Any = DefinitionMock._create(obj=func, _nodeid="mock::nodeid")
+ definition._fixtureinfo = fixtureinfo
+ definition.session = SessionMock(FixtureManagerMock({}))
+ 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_single_arg_trailing_comma(self) -> None:
+ """Test that trailing comma in string argnames behaves like tuple argnames.
+
+ Regression test for https://github.com/pytest-dev/pytest/issues/719
+
+ When using a single argument with:
+ - "arg" (string, no comma): argvalues is a list of values
+ - "arg," (string, trailing comma): argvalues is a list of tuples (like tuple form)
+ - ("arg",) (tuple): argvalues is a list of tuples
+ """
+
+ def func(arg):
+ pass # pragma: no cover
+
+ scenarios = [("a",), ("b",)]
+
+ # Tuple form: argvalues are tuples, unpacked to get the value
+ metafunc = self.Metafunc(func)
+ metafunc.parametrize(("arg",), scenarios)
+ assert metafunc._calls[0].params == {"arg": "a"}
+ assert metafunc._calls[1].params == {"arg": "b"}
+
+ # String with trailing comma: should behave like tuple form
+ metafunc = self.Metafunc(func)
+ metafunc.parametrize("arg,", scenarios)
+ assert metafunc._calls[0].params == {"arg": "a"}
+ assert metafunc._calls[1].params == {"arg": "b"}
+
+ # String without comma: argvalues are values directly (tuples are passed as-is)
+ metafunc = self.Metafunc(func)
+ metafunc.parametrize("arg", scenarios)
+ assert metafunc._calls[0].params == {"arg": ("a",)}
+ assert metafunc._calls[1].params == {"arg": ("b",)}
+
+ # String without comma with plain values: values are used directly
+ metafunc = self.Metafunc(func)
+ metafunc.parametrize("arg", ["a", "b"])
+ assert metafunc._calls[0].params == {"arg": "a"}
+ assert metafunc._calls[1].params == {"arg": "b"}
+
+ def test_parametrize_error(self) -> None:
+ def func(x, y):
+ pass
+
+ metafunc = self.Metafunc(func)
+ metafunc.parametrize("x", [1, 2])
+ with pytest.raises(pytest.Collector.CollectError):
+ metafunc.parametrize("x", [5, 6])
+ with pytest.raises(pytest.Collector.CollectError):
+ metafunc.parametrize("x", [5, 6])
+ metafunc.parametrize("y", [1, 2])
+ with pytest.raises(pytest.Collector.CollectError):
+ metafunc.parametrize("y", [5, 6])
+ with pytest.raises(pytest.Collector.CollectError):
+ metafunc.parametrize("y", [5, 6])
+
+ with pytest.raises(TypeError, match=r"^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[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())
+ assert [(x.params, x.id) for x in metafunc._calls] == [
+ ({"x": 1}, "0"),
+ ({"x": 2}, "2"),
+ ]
+ with pytest.raises(
+ fail.Exception,
+ match=(
+ r"In mock::nodeid: ids contains unsupported value Exc\(from_gen\) \(type: \) at index 2. "
+ r"Supported types are: .*"
+ ),
+ ):
+ metafunc.parametrize("x", [1, 2, 3], ids=gen())
+
+ 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
+
+ @dataclasses.dataclass
+ class DummyFixtureDef:
+ _scope: Scope
+
+ fixtures_defs = cast(
+ dict[str, Sequence[fixtures.FixtureDef[object]]],
+ dict(
+ session_fix=[DummyFixtureDef(Scope.Session)],
+ package_fix=[DummyFixtureDef(Scope.Package)],
+ module_fix=[DummyFixtureDef(Scope.Module)],
+ class_fix=[DummyFixtureDef(Scope.Class)],
+ func_fix=[DummyFixtureDef(Scope.Function)],
+ mixed_fix=[DummyFixtureDef(Scope.Module), DummyFixtureDef(Scope.Class)],
+ ),
+ )
+
+ # 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) == Scope.Function
+ assert find_scope(["class_fix"], indirect=True) == Scope.Class
+ assert find_scope(["module_fix"], indirect=True) == Scope.Module
+ assert find_scope(["package_fix"], indirect=True) == Scope.Package
+ assert find_scope(["session_fix"], indirect=True) == Scope.Session
+
+ assert find_scope(["class_fix", "func_fix"], indirect=True) == Scope.Function
+ assert find_scope(["func_fix", "session_fix"], indirect=True) == Scope.Function
+ assert find_scope(["session_fix", "class_fix"], indirect=True) == Scope.Class
+ assert (
+ find_scope(["package_fix", "session_fix"], indirect=True) == Scope.Package
+ )
+ assert find_scope(["module_fix", "session_fix"], indirect=True) == Scope.Module
+
+ # when indirect is False or is not for all scopes, always use function
+ assert (
+ find_scope(["session_fix", "module_fix"], indirect=False) == Scope.Function
+ )
+ assert (
+ find_scope(["session_fix", "module_fix"], indirect=["module_fix"])
+ == Scope.Function
+ )
+ assert (
+ find_scope(
+ ["session_fix", "module_fix"], indirect=["session_fix", "module_fix"]
+ )
+ == Scope.Module
+ )
+ assert find_scope(["mixed_fix"], indirect=True) == Scope.Class
+
+ 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 = IdMaker([], [], None, None, None, None)._idval(value, "a", 6)
+ 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\xe9@blah.com"),
+ (
+ 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 (
+ IdMaker([], [], None, None, None, None)._idval(val, "a", 6) == 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 = IdMaker([], [], None, None, config, None)._idval(val, "a", 6)
+ 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 (
+ IdMaker([], [], None, None, None, None)._idval(val, "a", 6) == 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 (
+ IdMaker([], [], None, None, None, None)._idval(val, "a", 6) == 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 IdMaker([], [], None, None, None, None)._idval(NOTSET, "a", 0) == "a0"
+
+ def test_idmaker_autoname(self) -> None:
+ """#250"""
+ result = IdMaker(
+ ("a", "b"),
+ [pytest.param("string", 1.0), pytest.param("st-ring", 2.0)],
+ None,
+ None,
+ None,
+ None,
+ ).make_unique_parameterset_ids()
+ assert result == ["string-1.0", "st-ring-2.0"]
+
+ result = IdMaker(
+ ("a", "b"),
+ [pytest.param(object(), 1.0), pytest.param(object(), object())],
+ None,
+ None,
+ None,
+ None,
+ ).make_unique_parameterset_ids()
+ assert result == ["a0-1.0", "a1-b1"]
+ # unicode mixing, issue250
+ result = IdMaker(
+ ("a", "b"), [pytest.param({}, b"\xc3\xb4")], None, None, None, None
+ ).make_unique_parameterset_ids()
+ assert result == ["a0-\\xc3\\xb4"]
+
+ def test_idmaker_with_bytes_regex(self) -> None:
+ result = IdMaker(
+ ("a"), [pytest.param(re.compile(b"foo"))], None, None, None, None
+ ).make_unique_parameterset_ids()
+ 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"),
+ pytest.param(1.0j, -2.0j),
+ ],
+ None,
+ None,
+ None,
+ None,
+ ).make_unique_parameterset_ids()
+ 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",
+ "1j-(-0-2j)",
+ ]
+
+ 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),
+ ],
+ None,
+ None,
+ None,
+ None,
+ ).make_unique_parameterset_ids()
+ 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"),
+ ],
+ None,
+ None,
+ None,
+ None,
+ ).make_unique_parameterset_ids()
+ 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)], None, None, None, None
+ ).make_unique_parameterset_ids()
+ assert result == ["Foo.one-Foo.two"]
+
+ def test_idmaker_idfn(self) -> None:
+ """#351"""
+
+ def ids(val: object) -> str | None:
+ 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]),
+ ],
+ ids,
+ None,
+ None,
+ None,
+ ).make_unique_parameterset_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]),
+ ],
+ ids,
+ None,
+ None,
+ None,
+ ).make_unique_parameterset_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")],
+ lambda _: "ação",
+ None,
+ config,
+ None,
+ ).make_unique_parameterset_ids()
+ 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")], None, ["ação"], config, None
+ ).make_unique_parameterset_ids()
+ assert result == [expected]
+
+ def test_idmaker_with_param_id_and_config(self) -> None:
+ """Unit test for expected behavior to create ids with pytest.param(id=...) and
+ disable_test_id_escaping_and_forfeit_all_rights_to_community_support
+ option (#9037).
+ """
+
+ class MockConfig:
+ def __init__(self, config):
+ self.config = config
+
+ 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", id="ação")],
+ None,
+ None,
+ config,
+ None,
+ ).make_unique_parameterset_ids()
+ assert result == [expected]
+
+ def test_idmaker_duplicated_empty_str(self) -> None:
+ """Regression test for empty strings parametrized more than once (#11563)."""
+ result = IdMaker(
+ ("a",), [pytest.param(""), pytest.param("")], None, None, None, None
+ ).make_unique_parameterset_ids()
+ assert result == ["0", "1"]
+
+ 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)],
+ None,
+ ["a", None],
+ None,
+ None,
+ ).make_unique_parameterset_ids()
+ 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")],
+ None,
+ ["a", None],
+ None,
+ None,
+ ).make_unique_parameterset_ids()
+ assert result == ["me", "you"]
+
+ def test_idmaker_with_ids_unique_names(self) -> None:
+ result = IdMaker(
+ ("a"),
+ list(map(pytest.param, [1, 2, 3, 4, 5])),
+ None,
+ ["a", "a", "b", "c", "b"],
+ None,
+ None,
+ ).make_unique_parameterset_ids()
+ 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].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].params == dict(x="a", y="b")
+ # Since `y` is a direct parameter, its DirectParamFixtureDef would
+ # be registered.
+ assert list(metafunc._arg2fixturedefs.keys()) == ["y"]
+
+ 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].params == dict(x="a", y="b")
+ assert list(metafunc._arg2fixturedefs.keys()) == []
+
+ 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].params == dict(x="a", y="b")
+ assert list(metafunc._arg2fixturedefs.keys()) == ["x", "y"]
+
+ def test_parametrize_indirect_wrong_type(self) -> None:
+ def func(x, y):
+ pass
+
+ metafunc = self.Metafunc(func)
+ with pytest.raises(
+ fail.Exception,
+ match="In mock::nodeid: 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 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].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_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].params == dict(x=1, y=2)
+ assert metafunc._calls[0].id == "1-2"
+ assert metafunc._calls[1].params == dict(x=3, y=4)
+ assert metafunc._calls[1].id == "3-4"
+
+ def test_high_scoped_parametrize_reordering(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize("arg2", [3, 4])
+ @pytest.mark.parametrize("arg1", [0, 1, 2], scope='module')
+ def test1(arg1, arg2):
+ pass
+
+ def test2():
+ pass
+
+ @pytest.mark.parametrize("arg1", [0, 1, 2], scope='module')
+ def test3(arg1):
+ pass
+ """
+ )
+ result = pytester.runpytest("--collect-only")
+ result.stdout.re_match_lines(
+ [
+ r" ",
+ r" ",
+ r" ",
+ r" ",
+ r" ",
+ r" ",
+ r" ",
+ r" ",
+ r" ",
+ r" ",
+ ]
+ )
+
+ 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_parametrize_iterator_deprecation(self) -> None:
+ """Test that using iterators for argvalues raises a deprecation warning."""
+
+ def func(x: int) -> None:
+ raise NotImplementedError()
+
+ def data_generator() -> Iterator[int]:
+ yield 1
+ yield 2
+
+ metafunc = self.Metafunc(func)
+
+ with pytest.warns(
+ pytest.PytestRemovedIn10Warning,
+ match=r"Passing a non-Collection iterable to parametrize is deprecated",
+ ):
+ metafunc.parametrize("x", data_generator())
+
+
+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
+
+ def test_function(metafunc, pytestconfig):
+ assert metafunc.config == pytestconfig
+ assert metafunc.module.__name__ == __name__
+ assert metafunc.function == test_function
+ assert metafunc.cls is None
+
+ class TestClass(object):
+ def test_method(self, metafunc, pytestconfig):
+ assert metafunc.config == pytestconfig
+ assert metafunc.module.__name__ == __name__
+ unbound = TestClass.test_method
+ assert metafunc.function == unbound
+ assert metafunc.cls == TestClass
+ """
+ )
+ result = pytester.runpytest(p, "-v")
+ result.assert_outcomes(passed=2)
+
+ def test_two_functions(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def pytest_generate_tests(metafunc):
+ metafunc.parametrize('arg1', [10, 20], ids=['0', '1'])
+
+ def test_func1(arg1):
+ assert arg1 == 10
+
+ def test_func2(arg1):
+ assert arg1 in (10, 20)
+ """
+ )
+ result = pytester.runpytest("-v", p)
+ result.stdout.fnmatch_lines(
+ [
+ "*test_func1*0*PASS*",
+ "*test_func1*1*FAIL*",
+ "*test_func2*PASS*",
+ "*test_func2*PASS*",
+ "*1 failed, 3 passed*",
+ ]
+ )
+
+ def test_noself_in_method(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def pytest_generate_tests(metafunc):
+ assert 'xyz' not in metafunc.fixturenames
+
+ class TestHello(object):
+ def test_hello(xyz):
+ pass
+ """
+ )
+ result = pytester.runpytest(p)
+ result.assert_outcomes(passed=1)
+
+ def test_generate_tests_in_class(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ class TestClass(object):
+ def pytest_generate_tests(self, metafunc):
+ metafunc.parametrize('hello', ['world'], ids=['hellow'])
+
+ def test_myfunc(self, hello):
+ assert hello == "world"
+ """
+ )
+ result = pytester.runpytest("-v", p)
+ result.stdout.fnmatch_lines(["*test_myfunc*hello*PASS*", "*1 passed*"])
+
+ def test_two_functions_not_same_instance(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def pytest_generate_tests(metafunc):
+ metafunc.parametrize('arg1', [10, 20], ids=["0", "1"])
+
+ class TestClass(object):
+ def test_func(self, arg1):
+ assert not hasattr(self, 'x')
+ self.x = 1
+ """
+ )
+ result = pytester.runpytest("-v", p)
+ result.stdout.fnmatch_lines(
+ ["*test_func*0*PASS*", "*test_func*1*PASS*", "*2 pass*"]
+ )
+
+ def test_issue28_setup_method_in_generate_tests(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def pytest_generate_tests(metafunc):
+ metafunc.parametrize('arg1', [1])
+
+ class TestClass(object):
+ def test_method(self, arg1):
+ assert arg1 == self.val
+ def setup_method(self, func):
+ self.val = 1
+ """
+ )
+ result = pytester.runpytest(p)
+ result.assert_outcomes(passed=1)
+
+ def test_parametrize_functional2(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def pytest_generate_tests(metafunc):
+ metafunc.parametrize("arg1", [1,2])
+ metafunc.parametrize("arg2", [4,5])
+ def test_hello(arg1, arg2):
+ assert 0, (arg1, arg2)
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ ["*(1, 4)*", "*(1, 5)*", "*(2, 4)*", "*(2, 5)*", "*4 failed*"]
+ )
+
+ def test_parametrize_single_arg_trailing_comma_functional(
+ self, pytester: Pytester
+ ) -> None:
+ """Test that trailing comma in string argnames behaves like tuple argnames.
+
+ Regression test for https://github.com/pytest-dev/pytest/issues/719
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ scenarios = [('a',), ('b',)]
+
+ @pytest.mark.parametrize(("arg",), scenarios)
+ def test_tuple_form(arg):
+ # Tuple argnames: values are unpacked from tuples
+ assert arg in ('a', 'b')
+ assert isinstance(arg, str)
+
+ @pytest.mark.parametrize("arg,", scenarios)
+ def test_string_trailing_comma(arg):
+ # String with trailing comma: should behave like tuple form
+ assert arg in ('a', 'b')
+ assert isinstance(arg, str)
+
+ @pytest.mark.parametrize("arg", scenarios)
+ def test_string_no_comma(arg):
+ # String without comma: tuples are passed as-is
+ assert arg in (('a',), ('b',))
+ assert isinstance(arg, tuple)
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.assert_outcomes(passed=6)
+
+ def test_parametrize_and_inner_getfixturevalue(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def pytest_generate_tests(metafunc):
+ metafunc.parametrize("arg1", [1], indirect=True)
+ metafunc.parametrize("arg2", [10], indirect=True)
+
+ import pytest
+ @pytest.fixture
+ def arg1(request):
+ x = request.getfixturevalue("arg2")
+ return x + request.param
+
+ @pytest.fixture
+ def arg2(request):
+ return request.param
+
+ def test_func1(arg1, arg2):
+ assert arg1 == 11
+ """
+ )
+ result = pytester.runpytest("-v", p)
+ result.stdout.fnmatch_lines(["*test_func1*1*PASS*", "*1 passed*"])
+
+ def test_parametrize_on_setup_arg(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def pytest_generate_tests(metafunc):
+ assert "arg1" in metafunc.fixturenames
+ metafunc.parametrize("arg1", [1], indirect=True)
+
+ import pytest
+ @pytest.fixture
+ def arg1(request):
+ return request.param
+
+ @pytest.fixture
+ def arg2(request, arg1):
+ return 10 * arg1
+
+ def test_func(arg2):
+ assert arg2 == 10
+ """
+ )
+ result = pytester.runpytest("-v", p)
+ result.stdout.fnmatch_lines(["*test_func*1*PASS*", "*1 passed*"])
+
+ def test_parametrize_with_ids(self, pytester: Pytester) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ console_output_style=classic
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+ def pytest_generate_tests(metafunc):
+ metafunc.parametrize(("a", "b"), [(1,1), (1,2)],
+ ids=["basic", "advanced"])
+
+ def test_function(a, b):
+ assert a == b
+ """
+ )
+ result = pytester.runpytest("-v")
+ assert result.ret == 1
+ result.stdout.fnmatch_lines_random(
+ ["*test_function*basic*PASSED", "*test_function*advanced*FAILED"]
+ )
+
+ def test_parametrize_without_ids(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ def pytest_generate_tests(metafunc):
+ metafunc.parametrize(("a", "b"),
+ [(1,object()), (1.3,object())])
+
+ def test_function(a, b):
+ assert 1
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines(
+ """
+ *test_function*1-b0*
+ *test_function*1.3-b1*
+ """
+ )
+
+ def test_parametrize_with_None_in_ids(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ def pytest_generate_tests(metafunc):
+ metafunc.parametrize(("a", "b"), [(1,1), (1,1), (1,2)],
+ ids=["basic", None, "advanced"])
+
+ def test_function(a, b):
+ assert a == b
+ """
+ )
+ result = pytester.runpytest("-v")
+ assert result.ret == 1
+ result.stdout.fnmatch_lines_random(
+ [
+ "*test_function*basic*PASSED*",
+ "*test_function*1-1*PASSED*",
+ "*test_function*advanced*FAILED*",
+ ]
+ )
+
+ def test_fixture_parametrized_empty_ids(self, pytester: Pytester) -> None:
+ """Fixtures parametrized with empty ids cause an internal error (#1849)."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope="module", ids=[], params=[])
+ def temp(request):
+ return request.param
+
+ def test_temp(temp):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 1 skipped *"])
+
+ def test_parametrized_empty_ids(self, pytester: Pytester) -> None:
+ """Tests parametrized with empty ids cause an internal error (#1849)."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize('temp', [], ids=list())
+ def test_temp(temp):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 1 skipped *"])
+
+ def test_parametrized_ids_invalid_type(self, pytester: Pytester) -> None:
+ """Test error with non-strings/non-ints, without generator (#1857)."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize("x, expected", [(1, 2), (3, 4), (5, 6)], ids=(None, 2, OSError()))
+ def test_ids_numbers(x,expected):
+ assert x * 2 == expected
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "In test_parametrized_ids_invalid_type.py::test_ids_numbers: ids contains unsupported value "
+ "OSError() (type: ) at index 2. "
+ "Supported types are: str, bytes, int, float, complex, bool, enum, regex or anything with a __name__."
+ ]
+ )
+
+ def test_parametrize_with_identical_ids_get_unique_names(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ def pytest_generate_tests(metafunc):
+ metafunc.parametrize(("a", "b"), [(1,1), (1,2)],
+ ids=["a", "a"])
+
+ def test_function(a, b):
+ assert a == b
+ """
+ )
+ result = pytester.runpytest("-v")
+ assert result.ret == 1
+ result.stdout.fnmatch_lines_random(
+ ["*test_function*a0*PASSED*", "*test_function*a1*FAILED*"]
+ )
+
+ @pytest.mark.parametrize(("scope", "length"), [("module", 2), ("function", 4)])
+ def test_parametrize_scope_overrides(
+ self, pytester: Pytester, scope: str, length: int
+ ) -> None:
+ pytester.makepyfile(
+ f"""
+ import pytest
+ values = []
+ def pytest_generate_tests(metafunc):
+ if "arg" in metafunc.fixturenames:
+ metafunc.parametrize("arg", [1,2], indirect=True,
+ scope={scope!r})
+ @pytest.fixture
+ def arg(request):
+ values.append(request.param)
+ return request.param
+ def test_hello(arg):
+ assert arg in (1,2)
+ def test_world(arg):
+ assert arg in (1,2)
+ def test_checklength():
+ assert len(values) == {length}
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=5)
+
+ def test_parametrize_issue323(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope='module', params=range(966))
+ def foo(request):
+ return request.param
+
+ def test_it(foo):
+ pass
+ def test_it2(foo):
+ pass
+ """
+ )
+ reprec = pytester.inline_run("--collect-only")
+ assert not reprec.getcalls("pytest_internalerror")
+
+ def test_usefixtures_seen_in_generate_tests(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ def pytest_generate_tests(metafunc):
+ assert "abc" in metafunc.fixturenames
+ metafunc.parametrize("abc", [1])
+
+ @pytest.mark.usefixtures("abc")
+ def test_function():
+ pass
+ """
+ )
+ reprec = pytester.runpytest()
+ reprec.assert_outcomes(passed=1)
+
+ def test_generate_tests_only_done_in_subdir(self, pytester: Pytester) -> None:
+ sub1 = pytester.mkpydir("sub1")
+ sub2 = pytester.mkpydir("sub2")
+ sub1.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ def pytest_generate_tests(metafunc):
+ assert metafunc.function.__name__ == "test_1"
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub2.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ def pytest_generate_tests(metafunc):
+ assert metafunc.function.__name__ == "test_2"
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub1.joinpath("test_in_sub1.py").write_text(
+ "def test_1(): pass", encoding="utf-8"
+ )
+ sub2.joinpath("test_in_sub2.py").write_text(
+ "def test_2(): pass", encoding="utf-8"
+ )
+ result = pytester.runpytest("--keep-duplicates", "-v", "-s", sub1, sub2, sub1)
+ result.assert_outcomes(passed=3)
+
+ def test_generate_same_function_names_issue403(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ def make_tests():
+ @pytest.mark.parametrize("x", range(2))
+ def test_foo(x):
+ pass
+ return test_foo
+
+ test_x = make_tests()
+ test_y = make_tests()
+ """
+ )
+ reprec = pytester.runpytest()
+ reprec.assert_outcomes(passed=4)
+
+ def test_parametrize_misspelling(self, pytester: Pytester) -> None:
+ """#463"""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrise("x", range(2))
+ def test_foo(x):
+ pass
+ """
+ )
+ result = pytester.runpytest("--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 0 items / 1 error",
+ "",
+ "*= ERRORS =*",
+ "*_ ERROR collecting test_parametrize_misspelling.py _*",
+ "test_parametrize_misspelling.py:3: in ",
+ ' @pytest.mark.parametrise("x", range(2))',
+ "E Failed: Unknown 'parametrise' mark, did you mean 'parametrize'?",
+ "*! Interrupted: 1 error during collection !*",
+ "*= no tests collected, 1 error in *",
+ ]
+ )
+
+ @pytest.mark.parametrize("scope", ["class", "package"])
+ def test_parametrize_missing_scope_doesnt_crash(
+ self, pytester: Pytester, scope: str
+ ) -> None:
+ """Doesn't crash when parametrize(scope=) is used without a
+ corresponding node."""
+ pytester.makepyfile(
+ f"""
+ import pytest
+
+ @pytest.mark.parametrize("x", [0], scope="{scope}")
+ def test_it(x): pass
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_parametrize_module_level_test_with_class_scope(
+ self, pytester: Pytester
+ ) -> None:
+ """
+ Test that a class-scoped parametrization without a corresponding `Class`
+ gets module scope, i.e. we only create a single FixtureDef for it per module.
+ """
+ module = pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize("x", [0, 1], scope="class")
+ def test_1(x):
+ pass
+
+ @pytest.mark.parametrize("x", [1, 2], scope="module")
+ def test_2(x):
+ pass
+ """
+ )
+ test_1_0, _, test_2_0, _ = pytester.genitems((pytester.getmodulecol(module),))
+
+ assert isinstance(test_1_0, Function)
+ assert test_1_0.name == "test_1[0]"
+ test_1_fixture_x = test_1_0._fixtureinfo.name2fixturedefs["x"][-1]
+
+ assert isinstance(test_2_0, Function)
+ assert test_2_0.name == "test_2[1]"
+ test_2_fixture_x = test_2_0._fixtureinfo.name2fixturedefs["x"][-1]
+
+ assert test_1_fixture_x is test_2_fixture_x
+
+ def test_reordering_with_scopeless_and_just_indirect_parametrization(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.fixture(scope="package")
+ def fixture1():
+ pass
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope="module")
+ def fixture0():
+ pass
+
+ @pytest.fixture(scope="module")
+ def fixture1(fixture0):
+ pass
+
+ @pytest.mark.parametrize("fixture1", [0], indirect=True)
+ def test_0(fixture1):
+ pass
+
+ @pytest.fixture(scope="module")
+ def fixture():
+ pass
+
+ @pytest.mark.parametrize("fixture", [0], indirect=True)
+ def test_1(fixture):
+ pass
+
+ def test_2():
+ pass
+
+ class Test:
+ @pytest.fixture(scope="class")
+ def fixture(self, fixture):
+ pass
+
+ @pytest.mark.parametrize("fixture", [0], indirect=True)
+ def test_3(self, fixture):
+ pass
+ """
+ )
+ result = pytester.runpytest("-v")
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(
+ [
+ "*test_0*",
+ "*test_1*",
+ "*test_2*",
+ "*test_3*",
+ ]
+ )
+
+ def test_parametrize_generator_multiple_runs(self, pytester: Pytester) -> None:
+ """Test that generators in parametrize work with multiple pytest.main() (deprecated)."""
+ testfile = pytester.makepyfile(
+ """
+ import pytest
+
+ def data_generator():
+ yield 1
+ yield 2
+
+ @pytest.mark.parametrize("bar", data_generator())
+ def test_foo(bar):
+ pass
+
+ if __name__ == '__main__':
+ args = ["-q", "--collect-only"]
+ pytest.main(args) # First run - should work with warning
+ pytest.main(args) # Second run - should also work with warning
+ """
+ )
+ result = pytester.run(sys.executable, "-Wdefault", testfile)
+ # Should see the deprecation warnings.
+ result.stdout.fnmatch_lines(
+ [
+ "*PytestRemovedIn10Warning: Passing a non-Collection iterable*",
+ "*PytestRemovedIn10Warning: Passing a non-Collection iterable*",
+ ]
+ )
+
+ def test_parametrize_iterator_class_multiple_tests(
+ self, pytester: Pytester
+ ) -> None:
+ """Test that iterators in parametrize on a class get exhausted (deprecated)."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize("n", iter(range(2)))
+ class Test:
+ def test_1(self, n):
+ pass
+
+ def test_2(self, n):
+ pass
+ """
+ )
+ result = pytester.runpytest("-v", "-Wdefault")
+ # Iterator gets exhausted after first test, second test gets no parameters.
+ # This is deprecated.
+ result.assert_outcomes(passed=2, skipped=1)
+ result.stdout.fnmatch_lines(
+ [
+ "*test_parametrize_iterator_class_multiple_tests.py::Test::test_1[[]0] PASSED*",
+ "*test_parametrize_iterator_class_multiple_tests.py::Test::test_1[[]1] PASSED*",
+ "*test_parametrize_iterator_class_multiple_tests.py::Test::test_2[[]NOTSET] SKIPPED*",
+ "*PytestRemovedIn10Warning: Passing a non-Collection iterable*",
+ ]
+ )
+
+
+class TestMetafuncFunctionalAuto:
+ """Tests related to automatically find out the correct scope for
+ parametrized tests (#1832)."""
+
+ def test_parametrize_auto_scope(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope='session', autouse=True)
+ def fixture():
+ return 1
+
+ @pytest.mark.parametrize('animal', ["dog", "cat"])
+ def test_1(animal):
+ assert animal in ('dog', 'cat')
+
+ @pytest.mark.parametrize('animal', ['fish'])
+ def test_2(animal):
+ assert animal == 'fish'
+
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 3 passed *"])
+
+ def test_parametrize_auto_scope_indirect(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope='session')
+ def echo(request):
+ return request.param
+
+ @pytest.mark.parametrize('animal, echo', [("dog", 1), ("cat", 2)], indirect=['echo'])
+ def test_1(animal, echo):
+ assert animal in ('dog', 'cat')
+ assert echo in (1, 2, 3)
+
+ @pytest.mark.parametrize('animal, echo', [('fish', 3)], indirect=['echo'])
+ def test_2(animal, echo):
+ assert animal == 'fish'
+ assert echo in (1, 2, 3)
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 3 passed *"])
+
+ def test_parametrize_auto_scope_override_fixture(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope='session', autouse=True)
+ def animal():
+ return 'fox'
+
+ @pytest.mark.parametrize('animal', ["dog", "cat"])
+ def test_1(animal):
+ assert animal in ('dog', 'cat')
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 2 passed *"])
+
+ def test_parametrize_all_indirects(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture()
+ def animal(request):
+ return request.param
+
+ @pytest.fixture(scope='session')
+ def echo(request):
+ return request.param
+
+ @pytest.mark.parametrize('animal, echo', [("dog", 1), ("cat", 2)], indirect=True)
+ def test_1(animal, echo):
+ assert animal in ('dog', 'cat')
+ assert echo in (1, 2, 3)
+
+ @pytest.mark.parametrize('animal, echo', [("fish", 3)], indirect=True)
+ def test_2(animal, echo):
+ assert animal == 'fish'
+ assert echo in (1, 2, 3)
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 3 passed *"])
+
+ def test_parametrize_some_arguments_auto_scope(
+ self, pytester: Pytester, monkeypatch
+ ) -> None:
+ """Integration test for (#3941)"""
+ class_fix_setup: list[object] = []
+ monkeypatch.setattr(sys, "class_fix_setup", class_fix_setup, raising=False)
+ func_fix_setup: list[object] = []
+ monkeypatch.setattr(sys, "func_fix_setup", func_fix_setup, raising=False)
+
+ pytester.makepyfile(
+ """
+ import pytest
+ import sys
+
+ @pytest.fixture(scope='class', autouse=True)
+ def class_fix(request):
+ sys.class_fix_setup.append(request.param)
+
+ @pytest.fixture(autouse=True)
+ def func_fix():
+ sys.func_fix_setup.append(True)
+
+ @pytest.mark.parametrize('class_fix', [10, 20], indirect=True)
+ class Test:
+ def test_foo(self):
+ pass
+ def test_bar(self):
+ pass
+ """
+ )
+ result = pytester.runpytest_inprocess()
+ result.stdout.fnmatch_lines(["* 4 passed in *"])
+ assert func_fix_setup == [True] * 4
+ assert class_fix_setup == [10, 20]
+
+ def test_parametrize_issue634(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture(scope='module')
+ def foo(request):
+ print('preparing foo-%d' % request.param)
+ return 'foo-%d' % request.param
+
+ def test_one(foo):
+ pass
+
+ def test_two(foo):
+ pass
+
+ test_two.test_with = (2, 3)
+
+ def pytest_generate_tests(metafunc):
+ params = (1, 2, 3, 4)
+ if not 'foo' in metafunc.fixturenames:
+ return
+
+ test_with = getattr(metafunc.function, 'test_with', None)
+ if test_with:
+ params = test_with
+ metafunc.parametrize('foo', params, indirect=True)
+ """
+ )
+ result = pytester.runpytest("-s")
+ output = result.stdout.str()
+ assert output.count("preparing foo-2") == 1
+ assert output.count("preparing foo-3") == 1
+
+
+class TestMarkersWithParametrization:
+ """#308"""
+
+ def test_simple_mark(self, pytester: Pytester) -> None:
+ s = """
+ import pytest
+
+ @pytest.mark.foo
+ @pytest.mark.parametrize(("n", "expected"), [
+ (1, 2),
+ pytest.param(1, 3, marks=pytest.mark.bar),
+ (2, 3),
+ ])
+ def test_increment(n, expected):
+ assert n + 1 == expected
+ """
+ items = pytester.getitems(s)
+ assert len(items) == 3
+ for item in items:
+ assert "foo" in item.keywords
+ assert "bar" not in items[0].keywords
+ assert "bar" in items[1].keywords
+ assert "bar" not in items[2].keywords
+
+ def test_select_based_on_mark(self, pytester: Pytester) -> None:
+ s = """
+ import pytest
+
+ @pytest.mark.parametrize(("n", "expected"), [
+ (1, 2),
+ pytest.param(2, 3, marks=pytest.mark.foo),
+ (3, 4),
+ ])
+ def test_increment(n, expected):
+ assert n + 1 == expected
+ """
+ pytester.makepyfile(s)
+ rec = pytester.inline_run("-m", "foo")
+ passed, skipped, fail = rec.listoutcomes()
+ assert len(passed) == 1
+ assert len(skipped) == 0
+ assert len(fail) == 0
+
+ def test_simple_xfail(self, pytester: Pytester) -> None:
+ s = """
+ import pytest
+
+ @pytest.mark.parametrize(("n", "expected"), [
+ (1, 2),
+ pytest.param(1, 3, marks=pytest.mark.xfail),
+ (2, 3),
+ ])
+ def test_increment(n, expected):
+ assert n + 1 == expected
+ """
+ pytester.makepyfile(s)
+ reprec = pytester.inline_run()
+ # xfail is skip??
+ reprec.assertoutcome(passed=2, skipped=1)
+
+ def test_simple_xfail_single_argname(self, pytester: Pytester) -> None:
+ s = """
+ import pytest
+
+ @pytest.mark.parametrize("n", [
+ 2,
+ pytest.param(3, marks=pytest.mark.xfail),
+ 4,
+ ])
+ def test_isEven(n):
+ assert n % 2 == 0
+ """
+ pytester.makepyfile(s)
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2, skipped=1)
+
+ def test_xfail_with_arg(self, pytester: Pytester) -> None:
+ s = """
+ import pytest
+
+ @pytest.mark.parametrize(("n", "expected"), [
+ (1, 2),
+ pytest.param(1, 3, marks=pytest.mark.xfail("True")),
+ (2, 3),
+ ])
+ def test_increment(n, expected):
+ assert n + 1 == expected
+ """
+ pytester.makepyfile(s)
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2, skipped=1)
+
+ def test_xfail_with_kwarg(self, pytester: Pytester) -> None:
+ s = """
+ import pytest
+
+ @pytest.mark.parametrize(("n", "expected"), [
+ (1, 2),
+ pytest.param(1, 3, marks=pytest.mark.xfail(reason="some bug")),
+ (2, 3),
+ ])
+ def test_increment(n, expected):
+ assert n + 1 == expected
+ """
+ pytester.makepyfile(s)
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2, skipped=1)
+
+ def test_xfail_with_arg_and_kwarg(self, pytester: Pytester) -> None:
+ s = """
+ import pytest
+
+ @pytest.mark.parametrize(("n", "expected"), [
+ (1, 2),
+ pytest.param(1, 3, marks=pytest.mark.xfail("True", reason="some bug")),
+ (2, 3),
+ ])
+ def test_increment(n, expected):
+ assert n + 1 == expected
+ """
+ pytester.makepyfile(s)
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2, skipped=1)
+
+ @pytest.mark.parametrize("strict", [True, False])
+ def test_xfail_passing_is_xpass(self, pytester: Pytester, strict: bool) -> None:
+ s = f"""
+ import pytest
+
+ m = pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict})
+
+ @pytest.mark.parametrize(("n", "expected"), [
+ (1, 2),
+ pytest.param(2, 3, marks=m),
+ (3, 4),
+ ])
+ def test_increment(n, expected):
+ assert n + 1 == expected
+ """
+ pytester.makepyfile(s)
+ reprec = pytester.inline_run()
+ passed, failed = (2, 1) if strict else (3, 0)
+ reprec.assertoutcome(passed=passed, failed=failed)
+
+ def test_parametrize_called_in_generate_tests(self, pytester: Pytester) -> None:
+ s = """
+ import pytest
+
+
+ def pytest_generate_tests(metafunc):
+ passingTestData = [(1, 2),
+ (2, 3)]
+ failingTestData = [(1, 3),
+ (2, 2)]
+
+ testData = passingTestData + [pytest.param(*d, marks=pytest.mark.xfail)
+ for d in failingTestData]
+ metafunc.parametrize(("n", "expected"), testData)
+
+
+ def test_increment(n, expected):
+ assert n + 1 == expected
+ """
+ pytester.makepyfile(s)
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2, skipped=2)
+
+ def test_parametrize_ID_generation_string_int_works(
+ self, pytester: Pytester
+ ) -> None:
+ """#290"""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def myfixture():
+ return 'example'
+ @pytest.mark.parametrize(
+ 'limit', (0, '0'))
+ def test_limit(limit, myfixture):
+ return
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=2)
+
+ @pytest.mark.parametrize("strict", [True, False])
+ def test_parametrize_marked_value(self, pytester: Pytester, strict: bool) -> None:
+ s = f"""
+ import pytest
+
+ @pytest.mark.parametrize(("n", "expected"), [
+ pytest.param(
+ 2,3,
+ marks=pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict}),
+ ),
+ pytest.param(
+ 2,3,
+ marks=[pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict})],
+ ),
+ ])
+ def test_increment(n, expected):
+ assert n + 1 == expected
+ """
+ pytester.makepyfile(s)
+ reprec = pytester.inline_run()
+ passed, failed = (0, 2) if strict else (2, 0)
+ reprec.assertoutcome(passed=passed, failed=failed)
+
+ def test_pytest_make_parametrize_id(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ def pytest_make_parametrize_id(config, val):
+ return str(val * 2)
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize("x", range(2))
+ def test_func(x):
+ pass
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines(["*test_func*0*PASS*", "*test_func*2*PASS*"])
+
+ def test_pytest_make_parametrize_id_with_argname(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ def pytest_make_parametrize_id(config, val, argname):
+ return str(val * 2 if argname == 'x' else val * 10)
+ """
+ )
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize("x", range(2))
+ def test_func_a(x):
+ pass
+
+ @pytest.mark.parametrize("y", [1])
+ def test_func_b(y):
+ pass
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines(
+ ["*test_func_a*0*PASS*", "*test_func_a*2*PASS*", "*test_func_b*10*PASS*"]
+ )
+
+ def test_parametrize_positional_args(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize("a", [1], False)
+ def test_foo(a):
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+
+ def test_parametrize_iterator(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import itertools
+ import pytest
+
+ id_parametrize = pytest.mark.parametrize(
+ ids=("param%d" % i for i in itertools.count())
+ )
+
+ @id_parametrize('y', ['a', 'b'])
+ def test1(y):
+ pass
+
+ @id_parametrize('y', ['a', 'b'])
+ def test2(y):
+ pass
+
+ @pytest.mark.parametrize("a, b", [(1, 2), (3, 4)], ids=itertools.count())
+ def test_converted_to_str(a, b):
+ pass
+ """
+ )
+ result = pytester.runpytest("-vv", "-s")
+ result.stdout.fnmatch_lines(
+ [
+ "test_parametrize_iterator.py::test1[param0] PASSED",
+ "test_parametrize_iterator.py::test1[param1] PASSED",
+ "test_parametrize_iterator.py::test2[param0] PASSED",
+ "test_parametrize_iterator.py::test2[param1] PASSED",
+ "test_parametrize_iterator.py::test_converted_to_str[0] PASSED",
+ "test_parametrize_iterator.py::test_converted_to_str[1] PASSED",
+ "*= 6 passed in *",
+ ]
+ )
+
+
+class TestHiddenParam:
+ """Test that pytest.HIDDEN_PARAM works"""
+
+ def test_parametrize_ids(self, pytester: Pytester) -> None:
+ items = pytester.getitems(
+ """
+ import pytest
+
+ @pytest.mark.parametrize(
+ ("foo", "bar"),
+ [
+ ("a", "x"),
+ ("b", "y"),
+ ("c", "z"),
+ ],
+ ids=["paramset1", pytest.HIDDEN_PARAM, "paramset3"],
+ )
+ def test_func(foo, bar):
+ pass
+ """
+ )
+ names = [item.name for item in items]
+ assert names == [
+ "test_func[paramset1]",
+ "test_func",
+ "test_func[paramset3]",
+ ]
+
+ def test_param_id(self, pytester: Pytester) -> None:
+ items = pytester.getitems(
+ """
+ import pytest
+
+ @pytest.mark.parametrize(
+ ("foo", "bar"),
+ [
+ pytest.param("a", "x", id="paramset1"),
+ pytest.param("b", "y", id=pytest.HIDDEN_PARAM),
+ ("c", "z"),
+ ],
+ )
+ def test_func(foo, bar):
+ pass
+ """
+ )
+ names = [item.name for item in items]
+ assert names == [
+ "test_func[paramset1]",
+ "test_func",
+ "test_func[c-z]",
+ ]
+
+ def test_multiple_hidden_param_is_forbidden(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize(
+ ("foo", "bar"),
+ [
+ ("a", "x"),
+ ("b", "y"),
+ ],
+ ids=[pytest.HIDDEN_PARAM, pytest.HIDDEN_PARAM],
+ )
+ def test_func(foo, bar):
+ pass
+ """
+ )
+ result = pytester.runpytest("--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 0 items / 1 error",
+ "",
+ "*= ERRORS =*",
+ "*_ ERROR collecting test_multiple_hidden_param_is_forbidden.py _*",
+ "E Failed: In test_multiple_hidden_param_is_forbidden.py::test_func: multiple instances of "
+ "HIDDEN_PARAM cannot be used in the same parametrize call, because the tests names need to be unique.",
+ "*! Interrupted: 1 error during collection !*",
+ "*= no tests collected, 1 error in *",
+ ]
+ )
+
+ def test_multiple_hidden_param_is_forbidden_idmaker(self) -> None:
+ id_maker = IdMaker(
+ ("foo", "bar"),
+ [pytest.param("a", "x"), pytest.param("b", "y")],
+ None,
+ [pytest.HIDDEN_PARAM, pytest.HIDDEN_PARAM],
+ None,
+ "some_node_id",
+ )
+ expected = "In some_node_id: multiple instances of HIDDEN_PARAM"
+ with pytest.raises(Failed, match=expected):
+ id_maker.make_unique_parameterset_ids()
+
+ def test_idmaker_error_without_nodeid(self) -> None:
+ id_maker = IdMaker(["a"], [pytest.param("a")], None, [object()], None, None)
+ with pytest.raises(Failed, match="ids contains unsupported value"):
+ id_maker.make_unique_parameterset_ids()
+
+ def test_multiple_parametrize(self, pytester: Pytester) -> None:
+ items = pytester.getitems(
+ """
+ import pytest
+
+ @pytest.mark.parametrize(
+ "bar",
+ ["x", "y"],
+ )
+ @pytest.mark.parametrize(
+ "foo",
+ ["a", "b"],
+ ids=["a", pytest.HIDDEN_PARAM],
+ )
+ def test_func(foo, bar):
+ pass
+ """
+ )
+ names = [item.name for item in items]
+ assert names == [
+ "test_func[a-x]",
+ "test_func[a-y]",
+ "test_func[x]",
+ "test_func[y]",
+ ]
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/raises.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/raises.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ba0c0e1c89a5f25e2863e5c9a57b401a6fdfb6f
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/raises.py
@@ -0,0 +1,446 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import io
+import re
+import sys
+
+from _pytest.outcomes import Failed
+from _pytest.pytester import Pytester
+from _pytest.warning_types import PytestWarning
+import pytest
+
+
+def wrap_escape(s: str) -> str:
+ return "^" + re.escape(s) + "$"
+
+
+class TestRaises:
+ def test_check_callable(self) -> None:
+ with pytest.raises(TypeError, match=r".* must be callable"):
+ pytest.raises(RuntimeError, "int('qwe')") # type: ignore[call-overload]
+
+ def test_raises(self):
+ with pytest.raises(ValueError) as excinfo:
+ int("qwe")
+ assert "invalid literal" in str(excinfo.value)
+
+ def test_raises_function(self):
+ with pytest.raises(ValueError) as excinfo:
+ int("hello")
+ assert "invalid literal" in str(excinfo.value)
+
+ def test_raises_does_not_allow_none(self):
+ with pytest.raises(
+ ValueError,
+ match=wrap_escape("You must specify at least one parameter to match on."),
+ ):
+ # We're testing that this invalid usage gives a helpful error,
+ # so we can ignore Mypy telling us that None is invalid.
+ pytest.raises(expected_exception=None) # type: ignore
+
+ # it's unclear if this message is helpful, and if it is, should it trigger more
+ # liberally? Usually you'd get a TypeError here
+ def test_raises_false_and_arg(self):
+ with pytest.raises(
+ ValueError,
+ match=wrap_escape(
+ "Expected an exception type or a tuple of exception types, but got `False`. "
+ "Raising exceptions is already understood as failing the test, so you don't need "
+ "any special code to say 'this should never raise an exception'."
+ ),
+ ):
+ pytest.raises(False, int) # type: ignore[call-overload]
+
+ def test_raises_does_not_allow_empty_tuple(self):
+ with pytest.raises(
+ ValueError,
+ match=wrap_escape("You must specify at least one parameter to match on."),
+ ):
+ pytest.raises(expected_exception=())
+
+ def test_raises_callable_no_exception(self) -> None:
+ class A:
+ def __call__(self):
+ pass
+
+ try:
+ pytest.raises(ValueError, A())
+ except pytest.fail.Exception:
+ pass
+
+ def test_raises_falsey_type_error(self) -> None:
+ with pytest.raises(TypeError):
+ with pytest.raises(AssertionError, match=0): # type: ignore[call-overload]
+ raise AssertionError("ohai")
+
+ def test_raises_repr_inflight(self):
+ """Ensure repr() on an exception info inside a pytest.raises with block works (#4386)"""
+
+ class E(Exception):
+ pass
+
+ with pytest.raises(E) as excinfo:
+ # this test prints the inflight uninitialized object
+ # using repr and str as well as pprint to demonstrate
+ # it works
+ print(str(excinfo))
+ print(repr(excinfo))
+ import pprint
+
+ pprint.pprint(excinfo)
+ raise E()
+
+ def test_raises_as_contextmanager(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ import _pytest._code
+
+ def test_simple():
+ with pytest.raises(ZeroDivisionError) as excinfo:
+ assert isinstance(excinfo, _pytest._code.ExceptionInfo)
+ 1/0
+ print(excinfo)
+ assert excinfo.type == ZeroDivisionError
+ assert isinstance(excinfo.value, ZeroDivisionError)
+
+ def test_noraise():
+ with pytest.raises(pytest.raises.Exception):
+ with pytest.raises(ValueError):
+ int()
+
+ def test_raise_wrong_exception_passes_by():
+ with pytest.raises(ZeroDivisionError):
+ with pytest.raises(ValueError):
+ 1/0
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*3 passed*"])
+
+ def test_does_not_raise(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ from contextlib import nullcontext as does_not_raise
+ import pytest
+
+ @pytest.mark.parametrize('example_input,expectation', [
+ (3, does_not_raise()),
+ (2, does_not_raise()),
+ (1, does_not_raise()),
+ (0, pytest.raises(ZeroDivisionError)),
+ ])
+ def test_division(example_input, expectation):
+ '''Test how much I know division.'''
+ with expectation:
+ assert (6 / example_input) is not None
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*4 passed*"])
+
+ def test_does_not_raise_does_raise(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ from contextlib import nullcontext as does_not_raise
+ import pytest
+
+ @pytest.mark.parametrize('example_input,expectation', [
+ (0, does_not_raise()),
+ (1, pytest.raises(ZeroDivisionError)),
+ ])
+ def test_division(example_input, expectation):
+ '''Test how much I know division.'''
+ with expectation:
+ assert (6 / example_input) is not None
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*2 failed*"])
+
+ def test_raises_with_invalid_regex(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+
+ def test_invalid_regex():
+ with pytest.raises(ValueError, match="invalid regex character ["):
+ raise ValueError()
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*Invalid regex pattern provided to 'match': unterminated character set at position 24*",
+ ]
+ )
+ result.stdout.no_fnmatch_line("*Traceback*")
+ result.stdout.no_fnmatch_line("*File*")
+ result.stdout.no_fnmatch_line("*line*")
+
+ def test_noclass(self) -> None:
+ with pytest.raises(TypeError):
+ with pytest.raises("wrong"): # type: ignore[call-overload]
+ ... # pragma: no cover
+
+ def test_invalid_arguments_to_raises(self) -> None:
+ with pytest.raises(TypeError, match="unknown"):
+ with pytest.raises(TypeError, unknown="bogus"): # type: ignore[call-overload]
+ raise ValueError()
+
+ def test_tuple(self):
+ with pytest.raises((KeyError, ValueError)):
+ raise KeyError("oops")
+
+ def test_no_raise_message(self) -> None:
+ try:
+ with pytest.raises(ValueError):
+ int("0")
+ except pytest.fail.Exception as e:
+ assert e.msg == f"DID NOT RAISE {ValueError!r}"
+ else:
+ assert False, "Expected pytest.raises.Exception"
+
+ try:
+ with pytest.raises(ValueError):
+ pass
+ except pytest.fail.Exception as e:
+ assert e.msg == f"DID NOT RAISE {ValueError!r}"
+ else:
+ assert False, "Expected pytest.raises.Exception"
+
+ @pytest.mark.parametrize(
+ "method", ["function", "function_match", "with", "with_raisesexc", "with_group"]
+ )
+ def test_raises_cyclic_reference(self, method):
+ """Ensure pytest.raises does not leave a reference cycle (#1965)."""
+ import gc
+
+ class T:
+ def __call__(self):
+ raise ValueError
+
+ t = T()
+ refcount = len(gc.get_referrers(t))
+
+ if method == "function":
+ pytest.raises(ValueError, t)
+ elif method == "function_match":
+ pytest.raises(ValueError, t).match("^$")
+ elif method == "with":
+ with pytest.raises(ValueError):
+ t()
+ elif method == "with_raisesexc":
+ with pytest.RaisesExc(ValueError):
+ t()
+ elif method == "with_group":
+ with pytest.RaisesGroup(ValueError, allow_unwrapped=True):
+ t()
+ else: # pragma: no cover
+ raise AssertionError("bad parametrization")
+
+ # ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()
+ assert sys.exc_info() == (None, None, None)
+
+ assert refcount == len(gc.get_referrers(t))
+
+ def test_raises_match(self) -> None:
+ msg = r"with base \d+"
+ with pytest.raises(ValueError, match=msg):
+ int("asdf")
+
+ msg = "with base 10"
+ with pytest.raises(ValueError, match=msg):
+ int("asdf")
+
+ msg = "with base 16"
+ expr = (
+ "Regex pattern did not match.\n"
+ f" Expected regex: {msg!r}\n"
+ f" Actual message: \"invalid literal for int() with base 10: 'asdf'\""
+ )
+ with pytest.raises(AssertionError, match="^" + re.escape(expr) + "$"):
+ with pytest.raises(ValueError, match=msg):
+ int("asdf", base=10)
+
+ # "match" without context manager.
+ pytest.raises(ValueError, int, "asdf").match("invalid literal")
+ with pytest.raises(AssertionError) as excinfo:
+ pytest.raises(ValueError, int, "asdf").match(msg)
+ assert str(excinfo.value) == expr
+
+ pytest.raises(TypeError, int, match="invalid") # type: ignore[call-overload]
+
+ def tfunc(match):
+ raise ValueError(f"match={match}")
+
+ pytest.raises(ValueError, tfunc, match="asdf").match("match=asdf")
+ pytest.raises(ValueError, tfunc, match="").match("match=")
+
+ # empty string matches everything, which is probably not what the user wants
+ with pytest.warns(
+ PytestWarning,
+ match=wrap_escape(
+ "matching against an empty string will *always* pass. If you want to check for an empty message you "
+ "need to pass '^$'. If you don't want to match you should pass `None` or leave out the parameter."
+ ),
+ ):
+ pytest.raises(match="")
+
+ def test_match_failure_string_quoting(self):
+ with pytest.raises(AssertionError) as excinfo:
+ with pytest.raises(AssertionError, match="'foo"):
+ raise AssertionError("'bar")
+ (msg,) = excinfo.value.args
+ assert (
+ msg
+ == '''Regex pattern did not match.\n Expected regex: "'foo"\n Actual message: "'bar"'''
+ )
+
+ def test_match_failure_exact_string_message(self):
+ message = "Oh here is a message with (42) numbers in parameters"
+ with pytest.raises(AssertionError) as excinfo:
+ with pytest.raises(AssertionError, match=message):
+ raise AssertionError(message)
+ (msg,) = excinfo.value.args
+ assert msg == (
+ "Regex pattern did not match.\n"
+ " Expected regex: 'Oh here is a message with (42) numbers in parameters'\n"
+ " Actual message: 'Oh here is a message with (42) numbers in parameters'\n"
+ " Did you mean to `re.escape()` the regex?"
+ )
+
+ def test_raises_match_wrong_type(self):
+ """Raising an exception with the wrong type and match= given.
+
+ pytest should throw the unexpected exception - the pattern match is not
+ really relevant if we got a different exception.
+ """
+ with pytest.raises(
+ ValueError,
+ match=wrap_escape("invalid literal for int() with base 10: 'asdf'"),
+ ):
+ with pytest.raises(IndexError, match="nomatch"):
+ int("asdf")
+
+ def test_raises_exception_looks_iterable(self):
+ class Meta(type):
+ def __getitem__(self, item):
+ return 1 / 0 # pragma: no cover
+
+ def __len__(self):
+ return 1 # pragma: no cover
+
+ class ClassLooksIterableException(Exception, metaclass=Meta):
+ pass
+
+ with pytest.raises(
+ Failed,
+ match=r"DID NOT RAISE ",
+ ):
+ with pytest.raises(ClassLooksIterableException):
+ ... # pragma: no cover
+
+ def test_raises_with_raising_dunder_class(self) -> None:
+ """Test current behavior with regard to exceptions via __class__ (#4284)."""
+
+ class CrappyClass(Exception):
+ # Type ignored because it's bypassed intentionally.
+ @property # type: ignore
+ def __class__(self):
+ assert False, "via __class__"
+
+ with pytest.raises(AssertionError) as excinfo:
+ with pytest.raises(CrappyClass()): # type: ignore[call-overload]
+ pass
+ assert "via __class__" in excinfo.value.args[0]
+
+ def test_raises_context_manager_with_kwargs(self):
+ with pytest.raises(expected_exception=ValueError):
+ raise ValueError
+ with pytest.raises(
+ TypeError,
+ match=wrap_escape(
+ "Unexpected keyword arguments passed to pytest.raises: foo\n"
+ "Use context-manager form instead?"
+ ),
+ ):
+ with pytest.raises(OSError, foo="bar"): # type: ignore[call-overload]
+ pass
+
+ def test_expected_exception_is_not_a_baseexception(self) -> None:
+ with pytest.raises(
+ TypeError,
+ match=wrap_escape("Expected a BaseException type, but got 'str'"),
+ ):
+ with pytest.raises("hello"): # type: ignore[call-overload]
+ pass # pragma: no cover
+
+ class NotAnException:
+ pass
+
+ with pytest.raises(
+ ValueError,
+ match=wrap_escape(
+ "Expected a BaseException type, but got 'NotAnException'"
+ ),
+ ):
+ with pytest.raises(NotAnException): # type: ignore[type-var]
+ pass # pragma: no cover
+
+ with pytest.raises(
+ TypeError,
+ match=wrap_escape("Expected a BaseException type, but got 'str'"),
+ ):
+ with pytest.raises(("hello", NotAnException)): # type: ignore[arg-type]
+ pass # pragma: no cover
+
+ def test_issue_11872(self) -> None:
+ """Regression test for #11872.
+
+ urllib.error.HTTPError on some Python 3.10/11 minor releases raises
+ KeyError instead of AttributeError on invalid attribute access.
+
+ https://github.com/python/cpython/issues/98778
+ """
+ from email.message import Message
+ from urllib.error import HTTPError
+
+ with pytest.raises(HTTPError, match="Not Found") as exc_info:
+ raise HTTPError(
+ code=404, msg="Not Found", fp=io.BytesIO(), hdrs=Message(), url=""
+ )
+ exc_info.value.close() # avoid a resource warning
+
+ def test_raises_match_compiled_regex(self) -> None:
+ """Test that compiled regex patterns work with pytest.raises."""
+ # Test with a compiled pattern that matches
+ pattern = re.compile(r"with base \d+")
+ with pytest.raises(ValueError, match=pattern):
+ int("asdf")
+
+ # Test with a compiled pattern that doesn't match
+ pattern_nomatch = re.compile(r"with base 16")
+ expr = (
+ "Regex pattern did not match.\n"
+ f" Expected regex: {pattern_nomatch.pattern!r}\n"
+ f" Actual message: \"invalid literal for int() with base 10: 'asdf'\""
+ )
+ with pytest.raises(AssertionError, match="^" + re.escape(expr) + "$"):
+ with pytest.raises(ValueError, match=pattern_nomatch):
+ int("asdf", base=10)
+
+ # Test compiled pattern with flags
+ pattern_with_flags = re.compile(r"INVALID LITERAL", re.IGNORECASE)
+ with pytest.raises(ValueError, match=pattern_with_flags):
+ int("asdf")
+
+ def test_pipe_is_treated_as_regex_metacharacter(self) -> None:
+ """| (pipe) must be recognized as a regex metacharacter."""
+ from _pytest.raises import is_fully_escaped
+ from _pytest.raises import unescape
+
+ assert not is_fully_escaped("foo|bar")
+ assert is_fully_escaped(r"foo\|bar")
+ assert unescape(r"foo\|bar") == "foo|bar"
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/raises_group.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/raises_group.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5e3b5cd2dc24ebc95ce62881dd23ea91280e677
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/raises_group.py
@@ -0,0 +1,1357 @@
+from __future__ import annotations
+
+# several expected multi-line strings contain long lines. We don't wanna break them up
+# as that makes it confusing to see where the line breaks are.
+# ruff: noqa: E501
+from contextlib import AbstractContextManager
+import re
+import sys
+
+from _pytest._code import ExceptionInfo
+from _pytest.outcomes import Failed
+from _pytest.pytester import Pytester
+from _pytest.raises import RaisesExc
+from _pytest.raises import RaisesGroup
+from _pytest.raises import repr_callable
+import pytest
+
+
+if sys.version_info < (3, 11):
+ from exceptiongroup import BaseExceptionGroup
+ from exceptiongroup import ExceptionGroup
+
+
+def wrap_escape(s: str) -> str:
+ return "^" + re.escape(s) + "$"
+
+
+def fails_raises_group(msg: str, add_prefix: bool = True) -> RaisesExc[Failed]:
+ assert msg[-1] != "\n", (
+ "developer error, expected string should not end with newline"
+ )
+ prefix = "Raised exception group did not match: " if add_prefix else ""
+ return pytest.raises(Failed, match=wrap_escape(prefix + msg))
+
+
+def test_raises_group() -> None:
+ with pytest.raises(
+ TypeError,
+ match=wrap_escape("Expected a BaseException type, but got 'int'"),
+ ):
+ RaisesExc(5) # type: ignore[call-overload]
+ with pytest.raises(
+ ValueError,
+ match=wrap_escape("Expected a BaseException type, but got 'int'"),
+ ):
+ RaisesExc(int) # type: ignore[type-var]
+ with pytest.raises(
+ TypeError,
+ match=wrap_escape(
+ "Expected a BaseException type, RaisesExc, or RaisesGroup, but got an exception instance: ValueError",
+ ),
+ ):
+ RaisesGroup(ValueError()) # type: ignore[call-overload]
+ with RaisesGroup(ValueError):
+ raise ExceptionGroup("foo", (ValueError(),))
+
+ with (
+ fails_raises_group("`SyntaxError()` is not an instance of `ValueError`"),
+ RaisesGroup(ValueError),
+ ):
+ raise ExceptionGroup("foo", (SyntaxError(),))
+
+ # multiple exceptions
+ with RaisesGroup(ValueError, SyntaxError):
+ raise ExceptionGroup("foo", (ValueError(), SyntaxError()))
+
+ # order doesn't matter
+ with RaisesGroup(SyntaxError, ValueError):
+ raise ExceptionGroup("foo", (ValueError(), SyntaxError()))
+
+ # nested exceptions
+ with RaisesGroup(RaisesGroup(ValueError)):
+ raise ExceptionGroup("foo", (ExceptionGroup("bar", (ValueError(),)),))
+
+ with RaisesGroup(
+ SyntaxError,
+ RaisesGroup(ValueError),
+ RaisesGroup(RuntimeError),
+ ):
+ raise ExceptionGroup(
+ "foo",
+ (
+ SyntaxError(),
+ ExceptionGroup("bar", (ValueError(),)),
+ ExceptionGroup("", (RuntimeError(),)),
+ ),
+ )
+
+
+def test_incorrect_number_exceptions() -> None:
+ # We previously gave an error saying the number of exceptions was wrong,
+ # but we now instead indicate excess/missing exceptions
+ with (
+ fails_raises_group(
+ "1 matched exception. Unexpected exception(s): [RuntimeError()]"
+ ),
+ RaisesGroup(ValueError),
+ ):
+ raise ExceptionGroup("", (RuntimeError(), ValueError()))
+
+ # will error if there's missing exceptions
+ with (
+ fails_raises_group(
+ "1 matched exception. Too few exceptions raised, found no match for: [SyntaxError]"
+ ),
+ RaisesGroup(ValueError, SyntaxError),
+ ):
+ raise ExceptionGroup("", (ValueError(),))
+
+ with (
+ fails_raises_group(
+ "\n"
+ "1 matched exception. \n"
+ "Too few exceptions raised!\n"
+ "The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " It matches `ValueError()` which was paired with `ValueError`"
+ ),
+ RaisesGroup(ValueError, ValueError),
+ ):
+ raise ExceptionGroup("", (ValueError(),))
+
+ with (
+ fails_raises_group(
+ "\n"
+ "1 matched exception. \n"
+ "Unexpected exception(s)!\n"
+ "The following raised exceptions did not find a match\n"
+ " ValueError('b'):\n"
+ " It matches `ValueError` which was paired with `ValueError('a')`"
+ ),
+ RaisesGroup(ValueError),
+ ):
+ raise ExceptionGroup("", (ValueError("a"), ValueError("b")))
+
+ with (
+ fails_raises_group(
+ "\n"
+ "1 matched exception. \n"
+ "The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " It matches `ValueError()` which was paired with `ValueError`\n"
+ "The following raised exceptions did not find a match\n"
+ " SyntaxError():\n"
+ " `SyntaxError()` is not an instance of `ValueError`"
+ ),
+ RaisesGroup(ValueError, ValueError),
+ ):
+ raise ExceptionGroup("", [ValueError(), SyntaxError()])
+
+
+def test_flatten_subgroups() -> None:
+ # loose semantics, as with expect*
+ with RaisesGroup(ValueError, flatten_subgroups=True):
+ raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),))
+
+ with RaisesGroup(ValueError, TypeError, flatten_subgroups=True):
+ raise ExceptionGroup("", (ExceptionGroup("", (ValueError(), TypeError())),))
+ with RaisesGroup(ValueError, TypeError, flatten_subgroups=True):
+ raise ExceptionGroup("", [ExceptionGroup("", [ValueError()]), TypeError()])
+
+ # mixed loose is possible if you want it to be at least N deep
+ with RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)):
+ raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),))
+ with RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)):
+ raise ExceptionGroup(
+ "",
+ (ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),)),),
+ )
+
+ # but not the other way around
+ with pytest.raises(
+ ValueError,
+ match=r"^You cannot specify a nested structure inside a RaisesGroup with",
+ ):
+ RaisesGroup(RaisesGroup(ValueError), flatten_subgroups=True) # type: ignore[call-overload]
+
+ # flatten_subgroups is not sufficient to catch fully unwrapped
+ with (
+ fails_raises_group(
+ "`ValueError()` is not an exception group, but would match with `allow_unwrapped=True`"
+ ),
+ RaisesGroup(ValueError, flatten_subgroups=True),
+ ):
+ raise ValueError
+ with (
+ fails_raises_group(
+ "RaisesGroup(ValueError, flatten_subgroups=True): `ValueError()` is not an exception group, but would match with `allow_unwrapped=True`"
+ ),
+ RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)),
+ ):
+ raise ExceptionGroup("", (ValueError(),))
+
+ # helpful suggestion if flatten_subgroups would make it pass
+ with (
+ fails_raises_group(
+ "Raised exception group did not match: \n"
+ "The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " TypeError\n"
+ "The following raised exceptions did not find a match\n"
+ " ExceptionGroup('', [ValueError(), TypeError()]):\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Unexpected nested `ExceptionGroup()`, expected `TypeError`\n"
+ "Did you mean to use `flatten_subgroups=True`?",
+ add_prefix=False,
+ ),
+ RaisesGroup(ValueError, TypeError),
+ ):
+ raise ExceptionGroup("", [ExceptionGroup("", [ValueError(), TypeError()])])
+ # but doesn't consider check (otherwise we'd break typing guarantees)
+ with (
+ fails_raises_group(
+ "Raised exception group did not match: \n"
+ "The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " TypeError\n"
+ "The following raised exceptions did not find a match\n"
+ " ExceptionGroup('', [ValueError(), TypeError()]):\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Unexpected nested `ExceptionGroup()`, expected `TypeError`\n"
+ "Did you mean to use `flatten_subgroups=True`?",
+ add_prefix=False,
+ ),
+ RaisesGroup(
+ ValueError,
+ TypeError,
+ check=lambda eg: len(eg.exceptions) == 1,
+ ),
+ ):
+ raise ExceptionGroup("", [ExceptionGroup("", [ValueError(), TypeError()])])
+ # correct number of exceptions, and flatten_subgroups would make it pass
+ # This now doesn't print a repr of the caught exception at all, but that can be found in the traceback
+ with (
+ fails_raises_group(
+ "Raised exception group did not match: Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Did you mean to use `flatten_subgroups=True`?",
+ add_prefix=False,
+ ),
+ RaisesGroup(ValueError),
+ ):
+ raise ExceptionGroup("", [ExceptionGroup("", [ValueError()])])
+ # correct number of exceptions, but flatten_subgroups wouldn't help, so we don't suggest it
+ with (
+ fails_raises_group(
+ "Unexpected nested `ExceptionGroup()`, expected `ValueError`"
+ ),
+ RaisesGroup(ValueError),
+ ):
+ raise ExceptionGroup("", [ExceptionGroup("", [TypeError()])])
+
+ # flatten_subgroups can be suggested if nested. This will implicitly ask the user to
+ # do `RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True))` which is unlikely
+ # to be what they actually want - but I don't think it's worth trying to special-case
+ with (
+ fails_raises_group(
+ "RaisesGroup(ValueError): Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Did you mean to use `flatten_subgroups=True`?",
+ ),
+ RaisesGroup(RaisesGroup(ValueError)),
+ ):
+ raise ExceptionGroup(
+ "",
+ [ExceptionGroup("", [ExceptionGroup("", [ValueError()])])],
+ )
+
+ # Don't mention "unexpected nested" if expecting an ExceptionGroup.
+ # Although it should perhaps be an error to specify `RaisesGroup(ExceptionGroup)` in
+ # favor of doing `RaisesGroup(RaisesGroup(...))`.
+ with (
+ fails_raises_group(
+ "`BaseExceptionGroup()` is not an instance of `ExceptionGroup`"
+ ),
+ RaisesGroup(ExceptionGroup),
+ ):
+ raise BaseExceptionGroup("", [BaseExceptionGroup("", [KeyboardInterrupt()])])
+
+
+def test_catch_unwrapped_exceptions() -> None:
+ # Catches lone exceptions with strict=False
+ # just as except* would
+ with RaisesGroup(ValueError, allow_unwrapped=True):
+ raise ValueError
+
+ # expecting multiple unwrapped exceptions is not possible
+ with pytest.raises(
+ ValueError,
+ match=r"^You cannot specify multiple exceptions with",
+ ):
+ RaisesGroup(SyntaxError, ValueError, allow_unwrapped=True) # type: ignore[call-overload]
+ # if users want one of several exception types they need to use a RaisesExc
+ # (which the error message suggests)
+ with RaisesGroup(
+ RaisesExc(check=lambda e: isinstance(e, SyntaxError | ValueError)),
+ allow_unwrapped=True,
+ ):
+ raise ValueError
+
+ # Unwrapped nested `RaisesGroup` is likely a user error, so we raise an error.
+ with pytest.raises(ValueError, match="has no effect when expecting"):
+ RaisesGroup(RaisesGroup(ValueError), allow_unwrapped=True) # type: ignore[call-overload]
+
+ # But it *can* be used to check for nesting level +- 1 if they move it to
+ # the nested RaisesGroup. Users should probably use `RaisesExc`s instead though.
+ with RaisesGroup(RaisesGroup(ValueError, allow_unwrapped=True)):
+ raise ExceptionGroup("", [ExceptionGroup("", [ValueError()])])
+ with RaisesGroup(RaisesGroup(ValueError, allow_unwrapped=True)):
+ raise ExceptionGroup("", [ValueError()])
+
+ # with allow_unwrapped=False (default) it will not be caught
+ with (
+ fails_raises_group(
+ "`ValueError()` is not an exception group, but would match with `allow_unwrapped=True`"
+ ),
+ RaisesGroup(ValueError),
+ ):
+ raise ValueError("value error text")
+
+ # allow_unwrapped on its own won't match against nested groups
+ with (
+ fails_raises_group(
+ "Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Did you mean to use `flatten_subgroups=True`?",
+ ),
+ RaisesGroup(ValueError, allow_unwrapped=True),
+ ):
+ raise ExceptionGroup("foo", [ExceptionGroup("bar", [ValueError()])])
+
+ # you need both allow_unwrapped and flatten_subgroups to fully emulate except*
+ with RaisesGroup(ValueError, allow_unwrapped=True, flatten_subgroups=True):
+ raise ExceptionGroup("", [ExceptionGroup("", [ValueError()])])
+
+ # code coverage
+ with (
+ fails_raises_group(
+ "Raised exception (group) did not match: `TypeError()` is not an instance of `ValueError`",
+ add_prefix=False,
+ ),
+ RaisesGroup(ValueError, allow_unwrapped=True),
+ ):
+ raise TypeError("this text doesn't show up in the error message")
+ with (
+ fails_raises_group(
+ "Raised exception (group) did not match: RaisesExc(ValueError): `TypeError()` is not an instance of `ValueError`",
+ add_prefix=False,
+ ),
+ RaisesGroup(RaisesExc(ValueError), allow_unwrapped=True),
+ ):
+ raise TypeError
+
+ # check we don't suggest unwrapping with nested RaisesGroup
+ with (
+ fails_raises_group("`ValueError()` is not an exception group"),
+ RaisesGroup(RaisesGroup(ValueError)),
+ ):
+ raise ValueError
+
+
+def test_match() -> None:
+ # supports match string
+ with RaisesGroup(ValueError, match="bar"):
+ raise ExceptionGroup("bar", (ValueError(),))
+
+ # now also works with ^$
+ with RaisesGroup(ValueError, match="^bar$"):
+ raise ExceptionGroup("bar", (ValueError(),))
+
+ # it also includes notes
+ with RaisesGroup(ValueError, match="my note"):
+ e = ExceptionGroup("bar", (ValueError(),))
+ e.add_note("my note")
+ raise e
+
+ # and technically you can match it all with ^$
+ # but you're probably better off using a RaisesExc at that point
+ with RaisesGroup(ValueError, match="^bar\nmy note$"):
+ e = ExceptionGroup("bar", (ValueError(),))
+ e.add_note("my note")
+ raise e
+
+ with (
+ fails_raises_group(
+ "Regex pattern did not match the `ExceptionGroup()`.\n"
+ " Expected regex: 'foo'\n"
+ " Actual message: 'bar'"
+ ),
+ RaisesGroup(ValueError, match="foo"),
+ ):
+ raise ExceptionGroup("bar", (ValueError(),))
+
+ # Suggest a fix for easy pitfall of adding match to the RaisesGroup instead of
+ # using a RaisesExc.
+ # This requires a single expected & raised exception, the expected is a type,
+ # and `isinstance(raised, expected_type)`.
+ with (
+ fails_raises_group(
+ "Regex pattern did not match the `ExceptionGroup()`.\n"
+ " Expected regex: 'foo'\n"
+ " Actual message: 'bar'\n"
+ " but matched the expected `ValueError`.\n"
+ " You might want `RaisesGroup(RaisesExc(ValueError, match='foo'))`"
+ ),
+ RaisesGroup(ValueError, match="foo"),
+ ):
+ raise ExceptionGroup("bar", [ValueError("foo")])
+
+
+def test_check() -> None:
+ exc = ExceptionGroup("", (ValueError(),))
+
+ def is_exc(e: ExceptionGroup[ValueError]) -> bool:
+ return e is exc
+
+ is_exc_repr = repr_callable(is_exc)
+ with RaisesGroup(ValueError, check=is_exc):
+ raise exc
+
+ with (
+ fails_raises_group(
+ f"check {is_exc_repr} did not return True on the ExceptionGroup"
+ ),
+ RaisesGroup(ValueError, check=is_exc),
+ ):
+ raise ExceptionGroup("", (ValueError(),))
+
+ def is_value_error(e: BaseException) -> bool:
+ return isinstance(e, ValueError)
+
+ # helpful suggestion if the user thinks the check is for the sub-exception
+ with (
+ fails_raises_group(
+ f"check {is_value_error} did not return True on the ExceptionGroup, but did return True for the expected ValueError. You might want RaisesGroup(RaisesExc(ValueError, check=<...>))"
+ ),
+ RaisesGroup(ValueError, check=is_value_error),
+ ):
+ raise ExceptionGroup("", (ValueError(),))
+
+
+def test_unwrapped_match_check() -> None:
+ def my_check(e: object) -> bool: # pragma: no cover
+ return True
+
+ msg = (
+ "`allow_unwrapped=True` bypasses the `match` and `check` parameters"
+ " if the exception is unwrapped. If you intended to match/check the"
+ " exception you should use a `RaisesExc` object. If you want to match/check"
+ " the exceptiongroup when the exception *is* wrapped you need to"
+ " do e.g. `if isinstance(exc.value, ExceptionGroup):"
+ " assert RaisesGroup(...).matches(exc.value)` afterwards."
+ )
+ with pytest.raises(ValueError, match=re.escape(msg)):
+ RaisesGroup(ValueError, allow_unwrapped=True, match="foo") # type: ignore[call-overload]
+ with pytest.raises(ValueError, match=re.escape(msg)):
+ RaisesGroup(ValueError, allow_unwrapped=True, check=my_check) # type: ignore[call-overload]
+
+ # Users should instead use a RaisesExc
+ rg = RaisesGroup(RaisesExc(ValueError, match="^foo$"), allow_unwrapped=True)
+ with rg:
+ raise ValueError("foo")
+ with rg:
+ raise ExceptionGroup("", [ValueError("foo")])
+
+ # or if they wanted to match/check the group, do a conditional `.matches()`
+ with RaisesGroup(ValueError, allow_unwrapped=True) as exc:
+ raise ExceptionGroup("bar", [ValueError("foo")])
+ if isinstance(exc.value, ExceptionGroup): # pragma: no branch
+ assert RaisesGroup(ValueError, match="bar").matches(exc.value)
+
+
+def test_matches() -> None:
+ rg = RaisesGroup(ValueError)
+ assert not rg.matches(None)
+ assert not rg.matches(ValueError())
+ assert rg.matches(ExceptionGroup("", (ValueError(),)))
+
+ re = RaisesExc(ValueError)
+ assert not re.matches(None)
+ assert re.matches(ValueError())
+
+
+def test_message() -> None:
+ def check_message(
+ message: str,
+ body: RaisesGroup[BaseException],
+ ) -> None:
+ with (
+ pytest.raises(
+ Failed,
+ match=f"^DID NOT RAISE any exception, expected `{re.escape(message)}`$",
+ ),
+ body,
+ ):
+ ...
+
+ # basic
+ check_message("ExceptionGroup(ValueError)", RaisesGroup(ValueError))
+ # multiple exceptions
+ check_message(
+ "ExceptionGroup(ValueError, ValueError)",
+ RaisesGroup(ValueError, ValueError),
+ )
+ # nested
+ check_message(
+ "ExceptionGroup(ExceptionGroup(ValueError))",
+ RaisesGroup(RaisesGroup(ValueError)),
+ )
+
+ # RaisesExc
+ check_message(
+ "ExceptionGroup(RaisesExc(ValueError, match='my_str'))",
+ RaisesGroup(RaisesExc(ValueError, match="my_str")),
+ )
+ check_message(
+ "ExceptionGroup(RaisesExc(match='my_str'))",
+ RaisesGroup(RaisesExc(match="my_str")),
+ )
+ # one-size tuple is printed as not being a tuple
+ check_message(
+ "ExceptionGroup(RaisesExc(ValueError))",
+ RaisesGroup(RaisesExc((ValueError,))),
+ )
+ check_message(
+ "ExceptionGroup(RaisesExc((ValueError, IndexError)))",
+ RaisesGroup(RaisesExc((ValueError, IndexError))),
+ )
+
+ # BaseExceptionGroup
+ check_message(
+ "BaseExceptionGroup(KeyboardInterrupt)",
+ RaisesGroup(KeyboardInterrupt),
+ )
+ # BaseExceptionGroup with type inside RaisesExc
+ check_message(
+ "BaseExceptionGroup(RaisesExc(KeyboardInterrupt))",
+ RaisesGroup(RaisesExc(KeyboardInterrupt)),
+ )
+ check_message(
+ "BaseExceptionGroup(RaisesExc((ValueError, KeyboardInterrupt)))",
+ RaisesGroup(RaisesExc((ValueError, KeyboardInterrupt))),
+ )
+ # Base-ness transfers to parent containers
+ check_message(
+ "BaseExceptionGroup(BaseExceptionGroup(KeyboardInterrupt))",
+ RaisesGroup(RaisesGroup(KeyboardInterrupt)),
+ )
+ # but not to child containers
+ check_message(
+ "BaseExceptionGroup(BaseExceptionGroup(KeyboardInterrupt), ExceptionGroup(ValueError))",
+ RaisesGroup(RaisesGroup(KeyboardInterrupt), RaisesGroup(ValueError)),
+ )
+
+
+def test_assert_message() -> None:
+ # the message does not need to list all parameters to RaisesGroup, nor all exceptions
+ # in the exception group, as those are both visible in the traceback.
+ # first fails to match
+ with (
+ fails_raises_group("`TypeError()` is not an instance of `ValueError`"),
+ RaisesGroup(ValueError),
+ ):
+ raise ExceptionGroup("a", [TypeError()])
+ with (
+ fails_raises_group(
+ "Raised exception group did not match: \n"
+ "The following expected exceptions did not find a match:\n"
+ " RaisesGroup(ValueError)\n"
+ " RaisesGroup(ValueError, match='a')\n"
+ "The following raised exceptions did not find a match\n"
+ " ExceptionGroup('', [RuntimeError()]):\n"
+ " RaisesGroup(ValueError): `RuntimeError()` is not an instance of `ValueError`\n"
+ " RaisesGroup(ValueError, match='a'): Regex pattern did not match the `ExceptionGroup()`.\n"
+ " Expected regex: 'a'\n"
+ " Actual message: ''\n"
+ " RuntimeError():\n"
+ " RaisesGroup(ValueError): `RuntimeError()` is not an exception group\n"
+ " RaisesGroup(ValueError, match='a'): `RuntimeError()` is not an exception group",
+ add_prefix=False, # to see the full structure
+ ),
+ RaisesGroup(RaisesGroup(ValueError), RaisesGroup(ValueError, match="a")),
+ ):
+ raise ExceptionGroup(
+ "",
+ [ExceptionGroup("", [RuntimeError()]), RuntimeError()],
+ )
+
+ with (
+ fails_raises_group(
+ "Raised exception group did not match: \n"
+ "2 matched exceptions. \n"
+ "The following expected exceptions did not find a match:\n"
+ " RaisesGroup(RuntimeError)\n"
+ " RaisesGroup(ValueError)\n"
+ "The following raised exceptions did not find a match\n"
+ " RuntimeError():\n"
+ " RaisesGroup(RuntimeError): `RuntimeError()` is not an exception group, but would match with `allow_unwrapped=True`\n"
+ " RaisesGroup(ValueError): `RuntimeError()` is not an exception group\n"
+ " ValueError('bar'):\n"
+ " It matches `ValueError` which was paired with `ValueError('foo')`\n"
+ " RaisesGroup(RuntimeError): `ValueError()` is not an exception group\n"
+ " RaisesGroup(ValueError): `ValueError()` is not an exception group, but would match with `allow_unwrapped=True`",
+ add_prefix=False, # to see the full structure
+ ),
+ RaisesGroup(
+ ValueError,
+ RaisesExc(TypeError),
+ RaisesGroup(RuntimeError),
+ RaisesGroup(ValueError),
+ ),
+ ):
+ raise ExceptionGroup(
+ "a",
+ [RuntimeError(), TypeError(), ValueError("foo"), ValueError("bar")],
+ )
+
+ with (
+ fails_raises_group(
+ "1 matched exception. `AssertionError()` is not an instance of `TypeError`"
+ ),
+ RaisesGroup(ValueError, TypeError),
+ ):
+ raise ExceptionGroup("a", [ValueError(), AssertionError()])
+
+ with (
+ fails_raises_group(
+ "RaisesExc(ValueError): `TypeError()` is not an instance of `ValueError`"
+ ),
+ RaisesGroup(RaisesExc(ValueError)),
+ ):
+ raise ExceptionGroup("a", [TypeError()])
+
+ # suggest escaping
+ with (
+ fails_raises_group(
+ # TODO: did not match Exceptiongroup('h(ell)o', ...) ?
+ "Raised exception group did not match: Regex pattern did not match the `ExceptionGroup()`.\n"
+ " Expected regex: 'h(ell)o'\n"
+ " Actual message: 'h(ell)o'\n"
+ " Did you mean to `re.escape()` the regex?",
+ add_prefix=False, # to see the full structure
+ ),
+ RaisesGroup(ValueError, match="h(ell)o"),
+ ):
+ raise ExceptionGroup("h(ell)o", [ValueError()])
+ with (
+ fails_raises_group(
+ "RaisesExc(match='h(ell)o'): Regex pattern did not match.\n"
+ " Expected regex: 'h(ell)o'\n"
+ " Actual message: 'h(ell)o'\n"
+ " Did you mean to `re.escape()` the regex?",
+ ),
+ RaisesGroup(RaisesExc(match="h(ell)o")),
+ ):
+ raise ExceptionGroup("", [ValueError("h(ell)o")])
+
+ with (
+ fails_raises_group(
+ "Raised exception group did not match: \n"
+ "The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " ValueError\n"
+ " ValueError\n"
+ " ValueError\n"
+ "The following raised exceptions did not find a match\n"
+ " ExceptionGroup('', [ValueError(), TypeError()]):\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`",
+ add_prefix=False, # to see the full structure
+ ),
+ RaisesGroup(ValueError, ValueError, ValueError, ValueError),
+ ):
+ raise ExceptionGroup("", [ExceptionGroup("", [ValueError(), TypeError()])])
+
+
+def test_message_indent() -> None:
+ with (
+ fails_raises_group(
+ "Raised exception group did not match: \n"
+ "The following expected exceptions did not find a match:\n"
+ " RaisesGroup(ValueError, ValueError)\n"
+ " ValueError\n"
+ "The following raised exceptions did not find a match\n"
+ " ExceptionGroup('', [TypeError(), RuntimeError()]):\n"
+ " RaisesGroup(ValueError, ValueError): \n"
+ " The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " ValueError\n"
+ " The following raised exceptions did not find a match\n"
+ " TypeError():\n"
+ " `TypeError()` is not an instance of `ValueError`\n"
+ " `TypeError()` is not an instance of `ValueError`\n"
+ " RuntimeError():\n"
+ " `RuntimeError()` is not an instance of `ValueError`\n"
+ " `RuntimeError()` is not an instance of `ValueError`\n"
+ # TODO: this line is not great, should maybe follow the same format as the other and say
+ # ValueError: Unexpected nested `ExceptionGroup()` (?)
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " TypeError():\n"
+ " RaisesGroup(ValueError, ValueError): `TypeError()` is not an exception group\n"
+ " `TypeError()` is not an instance of `ValueError`",
+ add_prefix=False,
+ ),
+ RaisesGroup(
+ RaisesGroup(ValueError, ValueError),
+ ValueError,
+ ),
+ ):
+ raise ExceptionGroup(
+ "",
+ [
+ ExceptionGroup("", [TypeError(), RuntimeError()]),
+ TypeError(),
+ ],
+ )
+ with (
+ fails_raises_group(
+ "Raised exception group did not match: \n"
+ "RaisesGroup(ValueError, ValueError): \n"
+ " The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " ValueError\n"
+ " The following raised exceptions did not find a match\n"
+ " TypeError():\n"
+ " `TypeError()` is not an instance of `ValueError`\n"
+ " `TypeError()` is not an instance of `ValueError`\n"
+ " RuntimeError():\n"
+ " `RuntimeError()` is not an instance of `ValueError`\n"
+ " `RuntimeError()` is not an instance of `ValueError`",
+ add_prefix=False,
+ ),
+ RaisesGroup(
+ RaisesGroup(ValueError, ValueError),
+ ),
+ ):
+ raise ExceptionGroup(
+ "",
+ [
+ ExceptionGroup("", [TypeError(), RuntimeError()]),
+ ],
+ )
+
+
+def test_suggestion_on_nested_and_brief_error() -> None:
+ # Make sure "Did you mean" suggestion gets indented iff it follows a single-line error
+ with (
+ fails_raises_group(
+ "\n"
+ "The following expected exceptions did not find a match:\n"
+ " RaisesGroup(ValueError)\n"
+ " ValueError\n"
+ "The following raised exceptions did not find a match\n"
+ " ExceptionGroup('', [ExceptionGroup('', [ValueError()])]):\n"
+ " RaisesGroup(ValueError): Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Did you mean to use `flatten_subgroups=True`?\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`",
+ ),
+ RaisesGroup(RaisesGroup(ValueError), ValueError),
+ ):
+ raise ExceptionGroup(
+ "",
+ [ExceptionGroup("", [ExceptionGroup("", [ValueError()])])],
+ )
+ # if indented here it would look like another raised exception
+ with (
+ fails_raises_group(
+ "\n"
+ "The following expected exceptions did not find a match:\n"
+ " RaisesGroup(ValueError, ValueError)\n"
+ " ValueError\n"
+ "The following raised exceptions did not find a match\n"
+ " ExceptionGroup('', [ValueError(), ExceptionGroup('', [ValueError()])]):\n"
+ " RaisesGroup(ValueError, ValueError): \n"
+ " 1 matched exception. \n"
+ " The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " It matches `ValueError()` which was paired with `ValueError`\n"
+ " The following raised exceptions did not find a match\n"
+ " ExceptionGroup('', [ValueError()]):\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
+ " Did you mean to use `flatten_subgroups=True`?\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`"
+ ),
+ RaisesGroup(RaisesGroup(ValueError, ValueError), ValueError),
+ ):
+ raise ExceptionGroup(
+ "",
+ [ExceptionGroup("", [ValueError(), ExceptionGroup("", [ValueError()])])],
+ )
+
+ # re.escape always comes after single-line errors
+ with (
+ fails_raises_group(
+ "\n"
+ "The following expected exceptions did not find a match:\n"
+ " RaisesGroup(Exception, match='^hello')\n"
+ " ValueError\n"
+ "The following raised exceptions did not find a match\n"
+ " ExceptionGroup('^hello', [Exception()]):\n"
+ " RaisesGroup(Exception, match='^hello'): Regex pattern did not match the `ExceptionGroup()`.\n"
+ " Expected regex: '^hello'\n"
+ " Actual message: '^hello'\n"
+ " Did you mean to `re.escape()` the regex?\n"
+ " Unexpected nested `ExceptionGroup()`, expected `ValueError`"
+ ),
+ RaisesGroup(RaisesGroup(Exception, match="^hello"), ValueError),
+ ):
+ raise ExceptionGroup("", [ExceptionGroup("^hello", [Exception()])])
+
+
+def test_assert_message_nested() -> None:
+ # we only get one instance of aaaaaaaaaa... and bbbbbb..., but we do get multiple instances of ccccc... and dddddd..
+ # but I think this now only prints the full repr when that is necessary to disambiguate exceptions
+ with (
+ fails_raises_group(
+ "Raised exception group did not match: \n"
+ "The following expected exceptions did not find a match:\n"
+ " RaisesGroup(ValueError)\n"
+ " RaisesGroup(RaisesGroup(ValueError))\n"
+ " RaisesGroup(RaisesExc(TypeError, match='foo'))\n"
+ " RaisesGroup(TypeError, ValueError)\n"
+ "The following raised exceptions did not find a match\n"
+ " TypeError('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'):\n"
+ " RaisesGroup(ValueError): `TypeError()` is not an exception group\n"
+ " RaisesGroup(RaisesGroup(ValueError)): `TypeError()` is not an exception group\n"
+ " RaisesGroup(RaisesExc(TypeError, match='foo')): `TypeError()` is not an exception group\n"
+ " RaisesGroup(TypeError, ValueError): `TypeError()` is not an exception group\n"
+ " ExceptionGroup('Exceptions from Trio nursery', [TypeError('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')]):\n"
+ " RaisesGroup(ValueError): `TypeError()` is not an instance of `ValueError`\n"
+ " RaisesGroup(RaisesGroup(ValueError)): RaisesGroup(ValueError): `TypeError()` is not an exception group\n"
+ " RaisesGroup(RaisesExc(TypeError, match='foo')): RaisesExc(TypeError, match='foo'): Regex pattern did not match.\n"
+ " Expected regex: 'foo'\n"
+ " Actual message: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'\n"
+ " RaisesGroup(TypeError, ValueError): 1 matched exception. Too few exceptions raised, found no match for: [ValueError]\n"
+ " ExceptionGroup('Exceptions from Trio nursery', [TypeError('cccccccccccccccccccccccccccccc'), TypeError('dddddddddddddddddddddddddddddd')]):\n"
+ " RaisesGroup(ValueError): \n"
+ " The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " The following raised exceptions did not find a match\n"
+ " TypeError('cccccccccccccccccccccccccccccc'):\n"
+ " `TypeError()` is not an instance of `ValueError`\n"
+ " TypeError('dddddddddddddddddddddddddddddd'):\n"
+ " `TypeError()` is not an instance of `ValueError`\n"
+ " RaisesGroup(RaisesGroup(ValueError)): \n"
+ " The following expected exceptions did not find a match:\n"
+ " RaisesGroup(ValueError)\n"
+ " The following raised exceptions did not find a match\n"
+ " TypeError('cccccccccccccccccccccccccccccc'):\n"
+ " RaisesGroup(ValueError): `TypeError()` is not an exception group\n"
+ " TypeError('dddddddddddddddddddddddddddddd'):\n"
+ " RaisesGroup(ValueError): `TypeError()` is not an exception group\n"
+ " RaisesGroup(RaisesExc(TypeError, match='foo')): \n"
+ " The following expected exceptions did not find a match:\n"
+ " RaisesExc(TypeError, match='foo')\n"
+ " The following raised exceptions did not find a match\n"
+ " TypeError('cccccccccccccccccccccccccccccc'):\n"
+ " RaisesExc(TypeError, match='foo'): Regex pattern did not match.\n"
+ " Expected regex: 'foo'\n"
+ " Actual message: 'cccccccccccccccccccccccccccccc'\n"
+ " TypeError('dddddddddddddddddddddddddddddd'):\n"
+ " RaisesExc(TypeError, match='foo'): Regex pattern did not match.\n"
+ " Expected regex: 'foo'\n"
+ " Actual message: 'dddddddddddddddddddddddddddddd'\n"
+ " RaisesGroup(TypeError, ValueError): \n"
+ " 1 matched exception. \n"
+ " The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " The following raised exceptions did not find a match\n"
+ " TypeError('dddddddddddddddddddddddddddddd'):\n"
+ " It matches `TypeError` which was paired with `TypeError('cccccccccccccccccccccccccccccc')`\n"
+ " `TypeError()` is not an instance of `ValueError`",
+ add_prefix=False, # to see the full structure
+ ),
+ RaisesGroup(
+ RaisesGroup(ValueError),
+ RaisesGroup(RaisesGroup(ValueError)),
+ RaisesGroup(RaisesExc(TypeError, match="foo")),
+ RaisesGroup(TypeError, ValueError),
+ ),
+ ):
+ raise ExceptionGroup(
+ "",
+ [
+ TypeError("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
+ ExceptionGroup(
+ "Exceptions from Trio nursery",
+ [TypeError("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")],
+ ),
+ ExceptionGroup(
+ "Exceptions from Trio nursery",
+ [
+ TypeError("cccccccccccccccccccccccccccccc"),
+ TypeError("dddddddddddddddddddddddddddddd"),
+ ],
+ ),
+ ],
+ )
+
+
+# CI always runs with hypothesis, but this is not a critical test - it overlaps
+# with several others
+@pytest.mark.skipif(
+ "hypothesis" in sys.modules,
+ reason="hypothesis may have monkeypatched _check_repr",
+)
+def test_check_no_patched_repr() -> None: # pragma: no cover
+ # We make `_check_repr` monkeypatchable to avoid this very ugly and verbose
+ # repr. The other tests that use `check` make use of `_check_repr` so they'll
+ # continue passing in case it is patched - but we have this one test that
+ # demonstrates just how nasty it gets otherwise.
+ match_str = (
+ r"^Raised exception group did not match: \n"
+ r"The following expected exceptions did not find a match:\n"
+ r" RaisesExc\(check=. at .*>\)\n"
+ r" TypeError\n"
+ r"The following raised exceptions did not find a match\n"
+ r" ValueError\('foo'\):\n"
+ r" RaisesExc\(check=. at .*>\): check did not return True\n"
+ r" `ValueError\(\)` is not an instance of `TypeError`\n"
+ r" ValueError\('bar'\):\n"
+ r" RaisesExc\(check=. at .*>\): check did not return True\n"
+ r" `ValueError\(\)` is not an instance of `TypeError`$"
+ )
+ with (
+ pytest.raises(Failed, match=match_str),
+ RaisesGroup(RaisesExc(check=lambda x: False), TypeError),
+ ):
+ raise ExceptionGroup("", [ValueError("foo"), ValueError("bar")])
+
+
+def test_misordering_example() -> None:
+ with (
+ fails_raises_group(
+ "\n"
+ "3 matched exceptions. \n"
+ "The following expected exceptions did not find a match:\n"
+ " RaisesExc(ValueError, match='foo')\n"
+ " It matches `ValueError('foo')` which was paired with `ValueError`\n"
+ " It matches `ValueError('foo')` which was paired with `ValueError`\n"
+ " It matches `ValueError('foo')` which was paired with `ValueError`\n"
+ "The following raised exceptions did not find a match\n"
+ " ValueError('bar'):\n"
+ " It matches `ValueError` which was paired with `ValueError('foo')`\n"
+ " It matches `ValueError` which was paired with `ValueError('foo')`\n"
+ " It matches `ValueError` which was paired with `ValueError('foo')`\n"
+ " RaisesExc(ValueError, match='foo'): Regex pattern did not match.\n"
+ " Expected regex: 'foo'\n"
+ " Actual message: 'bar'\n"
+ "There exist a possible match when attempting an exhaustive check, but RaisesGroup uses a greedy algorithm. Please make your expected exceptions more stringent with `RaisesExc` etc so the greedy algorithm can function."
+ ),
+ RaisesGroup(
+ ValueError, ValueError, ValueError, RaisesExc(ValueError, match="foo")
+ ),
+ ):
+ raise ExceptionGroup(
+ "",
+ [
+ ValueError("foo"),
+ ValueError("foo"),
+ ValueError("foo"),
+ ValueError("bar"),
+ ],
+ )
+
+
+def test_brief_error_on_one_fail() -> None:
+ """If only one raised and one expected fail to match up, we print a full table iff
+ the raised exception would match one of the expected that previously got matched"""
+ # no also-matched
+ with (
+ fails_raises_group(
+ "1 matched exception. `TypeError()` is not an instance of `RuntimeError`"
+ ),
+ RaisesGroup(ValueError, RuntimeError),
+ ):
+ raise ExceptionGroup("", [ValueError(), TypeError()])
+
+ # raised would match an expected
+ with (
+ fails_raises_group(
+ "\n"
+ "1 matched exception. \n"
+ "The following expected exceptions did not find a match:\n"
+ " RuntimeError\n"
+ "The following raised exceptions did not find a match\n"
+ " TypeError():\n"
+ " It matches `Exception` which was paired with `ValueError()`\n"
+ " `TypeError()` is not an instance of `RuntimeError`"
+ ),
+ RaisesGroup(Exception, RuntimeError),
+ ):
+ raise ExceptionGroup("", [ValueError(), TypeError()])
+
+ # expected would match a raised
+ with (
+ fails_raises_group(
+ "\n"
+ "1 matched exception. \n"
+ "The following expected exceptions did not find a match:\n"
+ " ValueError\n"
+ " It matches `ValueError()` which was paired with `ValueError`\n"
+ "The following raised exceptions did not find a match\n"
+ " TypeError():\n"
+ " `TypeError()` is not an instance of `ValueError`"
+ ),
+ RaisesGroup(ValueError, ValueError),
+ ):
+ raise ExceptionGroup("", [ValueError(), TypeError()])
+
+
+def test_identity_oopsies() -> None:
+ # it's both possible to have several instances of the same exception in the same group
+ # and to expect multiple of the same type
+ # this previously messed up the logic
+
+ with (
+ fails_raises_group(
+ "3 matched exceptions. `RuntimeError()` is not an instance of `TypeError`"
+ ),
+ RaisesGroup(ValueError, ValueError, ValueError, TypeError),
+ ):
+ raise ExceptionGroup(
+ "", [ValueError(), ValueError(), ValueError(), RuntimeError()]
+ )
+
+ e = ValueError("foo")
+ m = RaisesExc(match="bar")
+ with (
+ fails_raises_group(
+ "\n"
+ "The following expected exceptions did not find a match:\n"
+ " RaisesExc(match='bar')\n"
+ " RaisesExc(match='bar')\n"
+ " RaisesExc(match='bar')\n"
+ "The following raised exceptions did not find a match\n"
+ " ValueError('foo'):\n"
+ " RaisesExc(match='bar'): Regex pattern did not match.\n"
+ " Expected regex: 'bar'\n"
+ " Actual message: 'foo'\n"
+ " RaisesExc(match='bar'): Regex pattern did not match.\n"
+ " Expected regex: 'bar'\n"
+ " Actual message: 'foo'\n"
+ " RaisesExc(match='bar'): Regex pattern did not match.\n"
+ " Expected regex: 'bar'\n"
+ " Actual message: 'foo'\n"
+ " ValueError('foo'):\n"
+ " RaisesExc(match='bar'): Regex pattern did not match.\n"
+ " Expected regex: 'bar'\n"
+ " Actual message: 'foo'\n"
+ " RaisesExc(match='bar'): Regex pattern did not match.\n"
+ " Expected regex: 'bar'\n"
+ " Actual message: 'foo'\n"
+ " RaisesExc(match='bar'): Regex pattern did not match.\n"
+ " Expected regex: 'bar'\n"
+ " Actual message: 'foo'\n"
+ " ValueError('foo'):\n"
+ " RaisesExc(match='bar'): Regex pattern did not match.\n"
+ " Expected regex: 'bar'\n"
+ " Actual message: 'foo'\n"
+ " RaisesExc(match='bar'): Regex pattern did not match.\n"
+ " Expected regex: 'bar'\n"
+ " Actual message: 'foo'\n"
+ " RaisesExc(match='bar'): Regex pattern did not match.\n"
+ " Expected regex: 'bar'\n"
+ " Actual message: 'foo'"
+ ),
+ RaisesGroup(m, m, m),
+ ):
+ raise ExceptionGroup("", [e, e, e])
+
+
+def test_raisesexc() -> None:
+ with pytest.raises(
+ ValueError,
+ match=r"^You must specify at least one parameter to match on.$",
+ ):
+ RaisesExc() # type: ignore[call-overload]
+ with pytest.raises(
+ ValueError,
+ match=wrap_escape("Expected a BaseException type, but got 'object'"),
+ ):
+ RaisesExc(object) # type: ignore[type-var]
+
+ with RaisesGroup(RaisesExc(ValueError)):
+ raise ExceptionGroup("", (ValueError(),))
+ with (
+ fails_raises_group(
+ "RaisesExc(TypeError): `ValueError()` is not an instance of `TypeError`"
+ ),
+ RaisesGroup(RaisesExc(TypeError)),
+ ):
+ raise ExceptionGroup("", (ValueError(),))
+
+ with RaisesExc(ValueError):
+ raise ValueError
+
+ # FIXME: leaving this one formatted differently for now to not change
+ # tests in python/raises.py
+ with pytest.raises(Failed, match=wrap_escape("DID NOT RAISE ")):
+ with RaisesExc(ValueError):
+ ...
+
+ with pytest.raises(Failed, match=wrap_escape("DID NOT RAISE any exception")):
+ with RaisesExc(match="foo"):
+ ...
+
+ with pytest.raises(
+ # FIXME: do we want repr(type) or type.__name__ ?
+ Failed,
+ match=wrap_escape(
+ "DID NOT RAISE any of (, )"
+ ),
+ ):
+ with RaisesExc((ValueError, TypeError)):
+ ...
+
+ # currently RaisesGroup says "Raised exception did not match" but RaisesExc doesn't...
+ with pytest.raises(
+ AssertionError,
+ match=wrap_escape(
+ "Regex pattern did not match.\n Expected regex: 'foo'\n Actual message: 'bar'"
+ ),
+ ):
+ with RaisesExc(TypeError, match="foo"):
+ raise TypeError("bar")
+
+
+def test_raisesexc_match() -> None:
+ with RaisesGroup(RaisesExc(ValueError, match="foo")):
+ raise ExceptionGroup("", (ValueError("foo"),))
+ with (
+ fails_raises_group(
+ "RaisesExc(ValueError, match='foo'): Regex pattern did not match.\n"
+ " Expected regex: 'foo'\n"
+ " Actual message: 'bar'"
+ ),
+ RaisesGroup(RaisesExc(ValueError, match="foo")),
+ ):
+ raise ExceptionGroup("", (ValueError("bar"),))
+
+ # Can be used without specifying the type
+ with RaisesGroup(RaisesExc(match="foo")):
+ raise ExceptionGroup("", (ValueError("foo"),))
+ with (
+ fails_raises_group(
+ "RaisesExc(match='foo'): Regex pattern did not match.\n"
+ " Expected regex: 'foo'\n"
+ " Actual message: 'bar'"
+ ),
+ RaisesGroup(RaisesExc(match="foo")),
+ ):
+ raise ExceptionGroup("", (ValueError("bar"),))
+
+ # check ^$
+ with RaisesGroup(RaisesExc(ValueError, match="^bar$")):
+ raise ExceptionGroup("", [ValueError("bar")])
+ with (
+ fails_raises_group(
+ "\nRaisesExc(ValueError, match='^bar$'): \n - barr\n ? -\n + bar"
+ ),
+ RaisesGroup(RaisesExc(ValueError, match="^bar$")),
+ ):
+ raise ExceptionGroup("", [ValueError("barr")])
+
+
+def test_RaisesExc_check() -> None:
+ def check_oserror_and_errno_is_5(e: BaseException) -> bool:
+ return isinstance(e, OSError) and e.errno == 5
+
+ with RaisesGroup(RaisesExc(check=check_oserror_and_errno_is_5)):
+ raise ExceptionGroup("", (OSError(5, ""),))
+
+ # specifying exception_type narrows the parameter type to the callable
+ def check_errno_is_5(e: OSError) -> bool:
+ return e.errno == 5
+
+ with RaisesGroup(RaisesExc(OSError, check=check_errno_is_5)):
+ raise ExceptionGroup("", (OSError(5, ""),))
+
+ # avoid printing overly verbose repr multiple times
+ with (
+ fails_raises_group(
+ f"RaisesExc(OSError, check={check_errno_is_5!r}): check did not return True"
+ ),
+ RaisesGroup(RaisesExc(OSError, check=check_errno_is_5)),
+ ):
+ raise ExceptionGroup("", (OSError(6, ""),))
+
+ # in nested cases you still get it multiple times though
+ # to address this you'd need logic in RaisesExc.__repr__ and RaisesGroup.__repr__
+ with (
+ fails_raises_group(
+ f"RaisesGroup(RaisesExc(OSError, check={check_errno_is_5!r})): RaisesExc(OSError, check={check_errno_is_5!r}): check did not return True"
+ ),
+ RaisesGroup(RaisesGroup(RaisesExc(OSError, check=check_errno_is_5))),
+ ):
+ raise ExceptionGroup("", [ExceptionGroup("", [OSError(6, "")])])
+
+
+def test_raisesexc_tostring() -> None:
+ assert str(RaisesExc(ValueError)) == "RaisesExc(ValueError)"
+ assert str(RaisesExc(match="[a-z]")) == "RaisesExc(match='[a-z]')"
+ pattern_no_flags = re.compile(r"noflag", 0)
+ assert str(RaisesExc(match=pattern_no_flags)) == "RaisesExc(match='noflag')"
+ pattern_flags = re.compile(r"noflag", re.IGNORECASE)
+ assert str(RaisesExc(match=pattern_flags)) == f"RaisesExc(match={pattern_flags!r})"
+ assert (
+ str(RaisesExc(ValueError, match="re", check=bool))
+ == f"RaisesExc(ValueError, match='re', check={bool!r})"
+ )
+
+
+def test_raisesgroup_tostring() -> None:
+ def check_str_and_repr(s: str) -> None:
+ evaled = eval(s)
+ assert s == str(evaled) == repr(evaled)
+
+ check_str_and_repr("RaisesGroup(ValueError)")
+ check_str_and_repr("RaisesGroup(RaisesGroup(ValueError))")
+ check_str_and_repr("RaisesGroup(RaisesExc(ValueError))")
+ check_str_and_repr("RaisesGroup(ValueError, allow_unwrapped=True)")
+ check_str_and_repr("RaisesGroup(ValueError, match='aoeu')")
+
+ assert (
+ str(RaisesGroup(ValueError, match="[a-z]", check=bool))
+ == f"RaisesGroup(ValueError, match='[a-z]', check={bool!r})"
+ )
+
+
+def test_assert_matches() -> None:
+ e = ValueError()
+
+ # it's easy to do this
+ assert RaisesExc(ValueError).matches(e)
+
+ # but you don't get a helpful error
+ with pytest.raises(AssertionError, match=r"assert False\n \+ where False = .*"):
+ assert RaisesExc(TypeError).matches(e)
+
+ with pytest.raises(
+ AssertionError,
+ match=wrap_escape(
+ "`ValueError()` is not an instance of `TypeError`\n"
+ "assert False\n"
+ " + where False = matches(ValueError())\n"
+ " + where matches = RaisesExc(TypeError).matches"
+ ),
+ ):
+ # you'd need to do this arcane incantation
+ assert (m := RaisesExc(TypeError)).matches(e), m.fail_reason
+
+ # but even if we add assert_matches, will people remember to use it?
+ # other than writing a linter rule, I don't think we can catch `assert RaisesExc(...).matches`
+ # ... no wait pytest catches other asserts ... so we probably can??
+
+
+# https://github.com/pytest-dev/pytest/issues/12504
+def test_xfail_raisesgroup(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import sys
+ import pytest
+ if sys.version_info < (3, 11):
+ from exceptiongroup import ExceptionGroup
+ @pytest.mark.xfail(raises=pytest.RaisesGroup(ValueError))
+ def test_foo() -> None:
+ raise ExceptionGroup("foo", [ValueError()])
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(xfailed=1)
+
+
+def test_xfail_RaisesExc(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.mark.xfail(raises=pytest.RaisesExc(ValueError))
+ def test_foo() -> None:
+ raise ValueError
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(xfailed=1)
+
+
+@pytest.mark.parametrize(
+ "wrap_in_group,handler",
+ [
+ (False, pytest.raises(ValueError)),
+ (True, RaisesGroup(ValueError)),
+ ],
+)
+def test_parametrizing_conditional_raisesgroup(
+ wrap_in_group: bool, handler: AbstractContextManager[ExceptionInfo[BaseException]]
+) -> None:
+ with handler:
+ if wrap_in_group:
+ raise ExceptionGroup("", [ValueError()])
+ raise ValueError()
+
+
+def test_annotated_group() -> None:
+ # repr depends on if exceptiongroup backport is being used or not
+ t = repr(ExceptionGroup[ValueError])
+ msg = "Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseException]` are accepted as generic types but got `{}`. As `raises` will catch all instances of the specified group regardless of the generic argument specific nested exceptions has to be checked with `RaisesGroup`."
+
+ fail_msg = wrap_escape(msg.format(t))
+ with pytest.raises(ValueError, match=fail_msg):
+ RaisesGroup(ExceptionGroup[ValueError])
+ with pytest.raises(ValueError, match=fail_msg):
+ RaisesExc(ExceptionGroup[ValueError])
+ with pytest.raises(
+ ValueError,
+ match=wrap_escape(msg.format(repr(BaseExceptionGroup[KeyboardInterrupt]))),
+ ):
+ with RaisesExc(BaseExceptionGroup[KeyboardInterrupt]):
+ raise BaseExceptionGroup("", [KeyboardInterrupt()])
+
+ with RaisesGroup(ExceptionGroup[Exception]):
+ raise ExceptionGroup(
+ "", [ExceptionGroup("", [ValueError(), ValueError(), ValueError()])]
+ )
+ with RaisesExc(BaseExceptionGroup[BaseException]):
+ raise BaseExceptionGroup("", [KeyboardInterrupt()])
+
+ # assure AbstractRaises.is_baseexception is set properly
+ assert (
+ RaisesGroup(ExceptionGroup[Exception]).expected_type()
+ == "ExceptionGroup(ExceptionGroup)"
+ )
+ assert (
+ RaisesGroup(BaseExceptionGroup[BaseException]).expected_type()
+ == "BaseExceptionGroup(BaseExceptionGroup)"
+ )
+
+
+def test_tuples() -> None:
+ # raises has historically supported one of several exceptions being raised
+ with pytest.raises((ValueError, IndexError)):
+ raise ValueError
+ # so now RaisesExc also does
+ with RaisesExc((ValueError, IndexError)):
+ raise IndexError
+ # but RaisesGroup currently doesn't. There's an argument it shouldn't because
+ # it can be confusing - RaisesGroup((ValueError, TypeError)) looks a lot like
+ # RaisesGroup(ValueError, TypeError), and the former might be interpreted as the latter.
+ with pytest.raises(
+ TypeError,
+ match=wrap_escape(
+ "Expected a BaseException type, RaisesExc, or RaisesGroup, but got 'tuple'.\n"
+ "RaisesGroup does not support tuples of exception types when expecting one of "
+ "several possible exception types like RaisesExc.\n"
+ "If you meant to expect a group with multiple exceptions, list them as separate arguments."
+ ),
+ ):
+ RaisesGroup((ValueError, IndexError)) # type: ignore[call-overload]
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/show_fixtures_per_test.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/show_fixtures_per_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..76fc3728267fb6e9240b5b867fa6a745e4b78e27
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/show_fixtures_per_test.py
@@ -0,0 +1,328 @@
+from __future__ import annotations
+
+from _pytest.pytester import Pytester
+
+
+def test_should_show_no_output_when_zero_items(pytester: Pytester) -> None:
+ result = pytester.runpytest("--fixtures-per-test")
+ result.stdout.no_fnmatch_line("*fixtures used by*")
+ assert result.ret == 0
+
+
+def test_fixtures_in_module(pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ '''
+ import pytest
+ @pytest.fixture
+ def _arg0():
+ """hidden arg0 fixture"""
+ @pytest.fixture
+ def arg1():
+ """arg1 docstring"""
+ def test_arg1(arg1):
+ pass
+ '''
+ )
+
+ result = pytester.runpytest("--fixtures-per-test", p)
+ assert result.ret == 0
+
+ result.stdout.fnmatch_lines(
+ [
+ "*fixtures used by test_arg1*",
+ "*(test_fixtures_in_module.py:9)*",
+ "arg1 -- test_fixtures_in_module.py:6",
+ " arg1 docstring",
+ ]
+ )
+ result.stdout.no_fnmatch_line("*_arg0*")
+
+
+def test_fixtures_in_conftest(pytester: Pytester) -> None:
+ pytester.makeconftest(
+ '''
+ import pytest
+ @pytest.fixture
+ def arg1():
+ """arg1 docstring"""
+ @pytest.fixture
+ def arg2():
+ """arg2 docstring"""
+ @pytest.fixture
+ def arg3(arg1, arg2):
+ """arg3
+ docstring
+ """
+ '''
+ )
+ p = pytester.makepyfile(
+ """
+ def test_arg2(arg2):
+ pass
+ def test_arg3(arg3):
+ pass
+ """
+ )
+ result = pytester.runpytest("--fixtures-per-test", p)
+ assert result.ret == 0
+
+ result.stdout.fnmatch_lines(
+ [
+ "*fixtures used by test_arg2*",
+ "*(test_fixtures_in_conftest.py:2)*",
+ "arg2 -- conftest.py:6",
+ " arg2 docstring",
+ "*fixtures used by test_arg3*",
+ "*(test_fixtures_in_conftest.py:4)*",
+ "arg1 -- conftest.py:3",
+ " arg1 docstring",
+ "arg2 -- conftest.py:6",
+ " arg2 docstring",
+ "arg3 -- conftest.py:9",
+ " arg3",
+ ]
+ )
+
+
+def test_should_show_fixtures_used_by_test(pytester: Pytester) -> None:
+ pytester.makeconftest(
+ '''
+ import pytest
+ @pytest.fixture
+ def arg1():
+ """arg1 from conftest"""
+ @pytest.fixture
+ def arg2():
+ """arg2 from conftest"""
+ '''
+ )
+ p = pytester.makepyfile(
+ '''
+ import pytest
+ @pytest.fixture
+ def arg1():
+ """arg1 from testmodule"""
+ def test_args(arg1, arg2):
+ pass
+ '''
+ )
+ result = pytester.runpytest("--fixtures-per-test", p)
+ assert result.ret == 0
+
+ result.stdout.fnmatch_lines(
+ [
+ "*fixtures used by test_args*",
+ "*(test_should_show_fixtures_used_by_test.py:6)*",
+ "arg1 -- test_should_show_fixtures_used_by_test.py:3",
+ " arg1 from testmodule",
+ "arg2 -- conftest.py:6",
+ " arg2 from conftest",
+ ]
+ )
+
+
+def test_verbose_include_private_fixtures_and_loc(pytester: Pytester) -> None:
+ pytester.makeconftest(
+ '''
+ import pytest
+ @pytest.fixture
+ def _arg1():
+ """_arg1 from conftest"""
+ @pytest.fixture
+ def arg2(_arg1):
+ """arg2 from conftest"""
+ '''
+ )
+ p = pytester.makepyfile(
+ '''
+ import pytest
+ @pytest.fixture
+ def arg3():
+ """arg3 from testmodule"""
+ def test_args(arg2, arg3):
+ pass
+ '''
+ )
+ result = pytester.runpytest("--fixtures-per-test", "-v", p)
+ assert result.ret == 0
+
+ result.stdout.fnmatch_lines(
+ [
+ "*fixtures used by test_args*",
+ "*(test_verbose_include_private_fixtures_and_loc.py:6)*",
+ "_arg1 -- conftest.py:3",
+ " _arg1 from conftest",
+ "arg2 -- conftest.py:6",
+ " arg2 from conftest",
+ "arg3 -- test_verbose_include_private_fixtures_and_loc.py:3",
+ " arg3 from testmodule",
+ ]
+ )
+
+
+def test_doctest_items(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ '''
+ def foo():
+ """
+ >>> 1 + 1
+ 2
+ """
+ '''
+ )
+ pytester.maketxtfile(
+ """
+ >>> 1 + 1
+ 2
+ """
+ )
+ result = pytester.runpytest(
+ "--fixtures-per-test", "--doctest-modules", "--doctest-glob=*.txt", "-v"
+ )
+ assert result.ret == 0
+
+ result.stdout.fnmatch_lines(["*collected 2 items*"])
+
+
+def test_multiline_docstring_in_module(pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ '''
+ import pytest
+ @pytest.fixture
+ def arg1():
+ """Docstring content that spans across multiple lines,
+ through second line,
+ and through third line.
+
+ Docstring content that extends into a second paragraph.
+
+ Docstring content that extends into a third paragraph.
+ """
+ def test_arg1(arg1):
+ pass
+ '''
+ )
+
+ result = pytester.runpytest("--fixtures-per-test", p)
+ assert result.ret == 0
+
+ result.stdout.fnmatch_lines(
+ [
+ "*fixtures used by test_arg1*",
+ "*(test_multiline_docstring_in_module.py:13)*",
+ "arg1 -- test_multiline_docstring_in_module.py:3",
+ " Docstring content that spans across multiple lines,",
+ " through second line,",
+ " and through third line.",
+ ]
+ )
+
+
+def test_verbose_include_multiline_docstring(pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ '''
+ import pytest
+ @pytest.fixture
+ def arg1():
+ """Docstring content that spans across multiple lines,
+ through second line,
+ and through third line.
+
+ Docstring content that extends into a second paragraph.
+
+ Docstring content that extends into a third paragraph.
+ """
+ def test_arg1(arg1):
+ pass
+ '''
+ )
+
+ result = pytester.runpytest("--fixtures-per-test", "-v", p)
+ assert result.ret == 0
+
+ result.stdout.fnmatch_lines(
+ [
+ "*fixtures used by test_arg1*",
+ "*(test_verbose_include_multiline_docstring.py:13)*",
+ "arg1 -- test_verbose_include_multiline_docstring.py:3",
+ " Docstring content that spans across multiple lines,",
+ " through second line,",
+ " and through third line.",
+ " ",
+ " Docstring content that extends into a second paragraph.",
+ " ",
+ " Docstring content that extends into a third paragraph.",
+ ]
+ )
+
+
+def test_should_not_show_direct_param_fixtures(pytester: Pytester) -> None:
+ """A direct-param fixture is a helper fixture created as an implementation
+ detail of direct parametrization.
+
+ These fixtures should not be included in the output because they don't
+ satisfy user expectations for how fixtures are created and used (#11295).
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize("x", [1])
+ def test_pseudo_fixture(x):
+ pass
+ """
+ )
+ result = pytester.runpytest("--fixtures-per-test")
+ result.stdout.no_fnmatch_line("*fixtures used by*")
+ assert result.ret == 0
+
+
+def test_should_show_parametrized_fixtures_used_by_test(pytester: Pytester) -> None:
+ """A fixture with parameters should be included if it was created using
+ the @pytest.fixture decorator, including those that are indirectly
+ parametrized."""
+ pytester.makepyfile(
+ '''
+ import pytest
+
+ @pytest.fixture(params=['a', 'b'])
+ def directly(request):
+ """parametrized fixture"""
+ return request.param
+
+ @pytest.fixture
+ def indirectly(request):
+ """indirectly parametrized fixture"""
+ return request.param
+
+ def test_directly_parametrized_fixture(directly):
+ pass
+
+ @pytest.mark.parametrize("indirectly", ["a", "b"], indirect=True)
+ def test_indirectly_parametrized_fixture(indirectly):
+ pass
+ '''
+ )
+ result = pytester.runpytest("--fixtures-per-test")
+ assert result.ret == 0
+
+ result.stdout.fnmatch_lines(
+ [
+ "*fixtures used by test_directly_parametrized_fixture*",
+ "*(test_should_show_parametrized_fixtures_used_by_test.py:14)*",
+ "directly -- test_should_show_parametrized_fixtures_used_by_test.py:4",
+ " parametrized fixture",
+ "*fixtures used by test_directly_parametrized_fixture*",
+ "*(test_should_show_parametrized_fixtures_used_by_test.py:14)*",
+ "directly -- test_should_show_parametrized_fixtures_used_by_test.py:4",
+ " parametrized fixture",
+ "*fixtures used by test_indirectly_parametrized_fixture*",
+ "*(test_should_show_parametrized_fixtures_used_by_test.py:17)*",
+ "indirectly -- test_should_show_parametrized_fixtures_used_by_test.py:9",
+ " indirectly parametrized fixture",
+ "*fixtures used by test_indirectly_parametrized_fixture*",
+ "*(test_should_show_parametrized_fixtures_used_by_test.py:17)*",
+ "indirectly -- test_should_show_parametrized_fixtures_used_by_test.py:9",
+ " indirectly parametrized fixture",
+ ]
+ )
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_argcomplete.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_argcomplete.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d1513b6206c0b62c1ef04bab7ecb952bd0fced8
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_argcomplete.py
@@ -0,0 +1,99 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from pathlib import Path
+import subprocess
+import sys
+
+from _pytest.monkeypatch import MonkeyPatch
+import pytest
+
+
+# Test for _argcomplete but not specific for any application.
+
+
+def equal_with_bash(prefix, ffc, fc, out=None):
+ res = ffc(prefix)
+ res_bash = set(fc(prefix))
+ retval = set(res) == res_bash
+ if out:
+ out.write(f"equal_with_bash({prefix}) {retval} {res}\n")
+ if not retval:
+ out.write(" python - bash: %s\n" % (set(res) - res_bash))
+ out.write(" bash - python: %s\n" % (res_bash - set(res)))
+ return retval
+
+
+# Copied from argcomplete.completers as import from there.
+# Also pulls in argcomplete.__init__ which opens filedescriptor 9.
+# This gives an OSError at the end of testrun.
+
+
+def _wrapcall(*args, **kargs):
+ try:
+ return subprocess.check_output(*args, **kargs).decode().splitlines()
+ except subprocess.CalledProcessError:
+ return []
+
+
+class FilesCompleter:
+ """File completer class, optionally takes a list of allowed extensions."""
+
+ def __init__(self, allowednames=(), directories=True):
+ # Fix if someone passes in a string instead of a list
+ if type(allowednames) is str:
+ allowednames = [allowednames]
+
+ self.allowednames = [x.lstrip("*").lstrip(".") for x in allowednames]
+ self.directories = directories
+
+ def __call__(self, prefix, **kwargs):
+ completion = []
+ if self.allowednames:
+ if self.directories:
+ files = _wrapcall(["bash", "-c", f"compgen -A directory -- '{prefix}'"])
+ completion += [f + "/" for f in files]
+ for x in self.allowednames:
+ completion += _wrapcall(
+ ["bash", "-c", f"compgen -A file -X '!*.{x}' -- '{prefix}'"]
+ )
+ else:
+ completion += _wrapcall(["bash", "-c", f"compgen -A file -- '{prefix}'"])
+
+ anticomp = _wrapcall(["bash", "-c", f"compgen -A directory -- '{prefix}'"])
+
+ completion = list(set(completion) - set(anticomp))
+
+ if self.directories:
+ completion += [f + "/" for f in anticomp]
+ return completion
+
+
+class TestArgComplete:
+ @pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
+ def test_compare_with_compgen(
+ self, tmp_path: Path, monkeypatch: MonkeyPatch
+ ) -> None:
+ from _pytest._argcomplete import FastFilesCompleter
+
+ ffc = FastFilesCompleter()
+ fc = FilesCompleter()
+
+ monkeypatch.chdir(tmp_path)
+
+ assert equal_with_bash("", ffc, fc, out=sys.stdout)
+
+ tmp_path.cwd().joinpath("data").touch()
+
+ for x in ["d", "data", "doesnotexist", ""]:
+ assert equal_with_bash(x, ffc, fc, out=sys.stdout)
+
+ @pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
+ def test_remove_dir_prefix(self):
+ """This is not compatible with compgen but it is with bash itself: ls /usr/."""
+ from _pytest._argcomplete import FastFilesCompleter
+
+ ffc = FastFilesCompleter()
+ fc = FilesCompleter()
+ for x in "/usr/".split():
+ assert not equal_with_bash(x, ffc, fc, out=sys.stdout)
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_assertion.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_assertion.py
new file mode 100644
index 0000000000000000000000000000000000000000..d68fd0b1fba9b3c1d2eb56c5a96a770fee06674c
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_assertion.py
@@ -0,0 +1,2242 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from collections.abc import MutableSequence
+import sys
+import textwrap
+from typing import Any
+from typing import NamedTuple
+
+import attr
+
+from _pytest import outcomes
+import _pytest.assertion as plugin
+from _pytest.assertion import truncate
+from _pytest.assertion import util
+from _pytest.config import Config as _Config
+from _pytest.monkeypatch import MonkeyPatch
+from _pytest.pytester import Pytester
+import pytest
+
+
+def mock_config(verbose: int = 0, assertion_override: int | None = None):
+ class TerminalWriter:
+ def _highlight(self, source, lexer="python"):
+ return source
+
+ class Config:
+ def get_terminal_writer(self):
+ return TerminalWriter()
+
+ def get_verbosity(self, verbosity_type: str | None = None) -> int:
+ if verbosity_type is None:
+ return verbose
+ if verbosity_type == _Config.VERBOSITY_ASSERTIONS:
+ if assertion_override is not None:
+ return assertion_override
+ return verbose
+
+ raise KeyError(f"Not mocked out: {verbosity_type}")
+
+ return Config()
+
+
+class TestMockConfig:
+ SOME_VERBOSITY_LEVEL = 3
+ SOME_OTHER_VERBOSITY_LEVEL = 10
+
+ def test_verbose_exposes_value(self):
+ config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)
+
+ assert config.get_verbosity() == TestMockConfig.SOME_VERBOSITY_LEVEL
+
+ def test_get_assertion_override_not_set_verbose_value(self):
+ config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)
+
+ assert (
+ config.get_verbosity(_Config.VERBOSITY_ASSERTIONS)
+ == TestMockConfig.SOME_VERBOSITY_LEVEL
+ )
+
+ def test_get_assertion_override_set_custom_value(self):
+ config = mock_config(
+ verbose=TestMockConfig.SOME_VERBOSITY_LEVEL,
+ assertion_override=TestMockConfig.SOME_OTHER_VERBOSITY_LEVEL,
+ )
+
+ assert (
+ config.get_verbosity(_Config.VERBOSITY_ASSERTIONS)
+ == TestMockConfig.SOME_OTHER_VERBOSITY_LEVEL
+ )
+
+ def test_get_unsupported_type_error(self):
+ config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)
+
+ with pytest.raises(KeyError):
+ config.get_verbosity("--- NOT A VERBOSITY LEVEL ---")
+
+
+class TestImportHookInstallation:
+ @pytest.mark.parametrize("initial_conftest", [True, False])
+ @pytest.mark.parametrize("mode", ["plain", "rewrite"])
+ def test_conftest_assertion_rewrite(
+ self, pytester: Pytester, initial_conftest, mode
+ ) -> None:
+ """Test that conftest files are using assertion rewrite on import (#1619)."""
+ pytester.mkdir("foo")
+ pytester.mkdir("foo/tests")
+ conftest_path = "conftest.py" if initial_conftest else "foo/conftest.py"
+ contents = {
+ conftest_path: """
+ import pytest
+ @pytest.fixture
+ def check_first():
+ def check(values, value):
+ assert values.pop(0) == value
+ return check
+ """,
+ "foo/tests/test_foo.py": """
+ def test(check_first):
+ check_first([10, 30], 30)
+ """,
+ }
+ pytester.makepyfile(**contents)
+ result = pytester.runpytest_subprocess(f"--assert={mode}")
+ if mode == "plain":
+ expected = "E AssertionError"
+ elif mode == "rewrite":
+ expected = "*assert 10 == 30*"
+ else:
+ assert 0
+ result.stdout.fnmatch_lines([expected])
+
+ def test_rewrite_assertions_pytester_plugin(self, pytester: Pytester) -> None:
+ """
+ Assertions in the pytester plugin must also benefit from assertion
+ rewriting (#1920).
+ """
+ pytester.makepyfile(
+ """
+ pytest_plugins = ['pytester']
+ def test_dummy_failure(pytester): # how meta!
+ pytester.makepyfile('def test(): assert 0')
+ r = pytester.inline_run()
+ r.assertoutcome(passed=1)
+ """
+ )
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(
+ [
+ "> r.assertoutcome(passed=1)",
+ "E AssertionError: ([[][]], [[][]], [[][]])*",
+ "E assert {'failed': 1,... 'skipped': 0} == {'failed': 0,... 'skipped': 0}",
+ "E Omitting 1 identical items, use -vv to show",
+ "E Differing items:",
+ "E Use -v to get more diff",
+ ]
+ )
+ # XXX: unstable output.
+ result.stdout.fnmatch_lines_random(
+ [
+ "E {'failed': 1} != {'failed': 0}",
+ "E {'passed': 0} != {'passed': 1}",
+ ]
+ )
+
+ @pytest.mark.parametrize("mode", ["plain", "rewrite"])
+ def test_pytest_plugins_rewrite(self, pytester: Pytester, mode) -> None:
+ contents = {
+ "conftest.py": """
+ pytest_plugins = ['ham']
+ """,
+ "ham.py": """
+ import pytest
+ @pytest.fixture
+ def check_first():
+ def check(values, value):
+ assert values.pop(0) == value
+ return check
+ """,
+ "test_foo.py": """
+ def test_foo(check_first):
+ check_first([10, 30], 30)
+ """,
+ }
+ pytester.makepyfile(**contents)
+ result = pytester.runpytest_subprocess(f"--assert={mode}")
+ if mode == "plain":
+ expected = "E AssertionError"
+ elif mode == "rewrite":
+ expected = "*assert 10 == 30*"
+ else:
+ assert 0
+ result.stdout.fnmatch_lines([expected])
+
+ @pytest.mark.parametrize("mode", ["str", "list"])
+ def test_pytest_plugins_rewrite_module_names(
+ self, pytester: Pytester, mode
+ ) -> None:
+ """Test that pluginmanager correct marks pytest_plugins variables
+ for assertion rewriting if they are defined as plain strings or
+ list of strings (#1888).
+ """
+ plugins = '"ham"' if mode == "str" else '["ham"]'
+ contents = {
+ "conftest.py": f"""
+ pytest_plugins = {plugins}
+ """,
+ "ham.py": """
+ import pytest
+ """,
+ "test_foo.py": """
+ def test_foo(pytestconfig):
+ assert 'ham' in pytestconfig.pluginmanager.rewrite_hook._must_rewrite
+ """,
+ }
+ pytester.makepyfile(**contents)
+ result = pytester.runpytest_subprocess("--assert=rewrite")
+ assert result.ret == 0
+
+ def test_pytest_plugins_rewrite_module_names_correctly(
+ self, pytester: Pytester
+ ) -> None:
+ """Test that we match files correctly when they are marked for rewriting (#2939)."""
+ contents = {
+ "conftest.py": """\
+ pytest_plugins = "ham"
+ """,
+ "ham.py": "",
+ "hamster.py": "",
+ "test_foo.py": """\
+ def test_foo(pytestconfig):
+ assert pytestconfig.pluginmanager.rewrite_hook.find_spec('ham') is not None
+ assert pytestconfig.pluginmanager.rewrite_hook.find_spec('hamster') is None
+ """,
+ }
+ pytester.makepyfile(**contents)
+ result = pytester.runpytest_subprocess("--assert=rewrite")
+ assert result.ret == 0
+
+ @pytest.mark.parametrize("mode", ["plain", "rewrite"])
+ @pytest.mark.parametrize("disable_plugin_autoload", ["env_var", "cli", ""])
+ @pytest.mark.parametrize("explicit_specify", ["env_var", "cli", ""])
+ def test_installed_plugin_rewrite(
+ self,
+ pytester: Pytester,
+ mode: str,
+ monkeypatch: pytest.MonkeyPatch,
+ disable_plugin_autoload: str,
+ explicit_specify: str,
+ ) -> None:
+ args = ["mainwrapper.py", "-s", f"--assert={mode}"]
+ if disable_plugin_autoload == "env_var":
+ monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")
+ elif disable_plugin_autoload == "cli":
+ monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
+ args.append("--disable-plugin-autoload")
+ else:
+ assert disable_plugin_autoload == ""
+ monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
+
+ name = "spamplugin"
+
+ if explicit_specify == "env_var":
+ monkeypatch.setenv("PYTEST_PLUGINS", name)
+ elif explicit_specify == "cli":
+ args.append("-p")
+ args.append(name)
+ else:
+ assert explicit_specify == ""
+
+ # Make sure the hook is installed early enough so that plugins
+ # installed via distribution package are rewritten.
+ pytester.mkdir("hampkg")
+ contents = {
+ "hampkg/__init__.py": """\
+ import pytest
+
+ @pytest.fixture
+ def check_first2():
+ def check(values, value):
+ assert values.pop(0) == value
+ return check
+ """,
+ "spamplugin.py": """\
+ import pytest
+ from hampkg import check_first2
+
+ @pytest.fixture
+ def check_first():
+ def check(values, value):
+ assert values.pop(0) == value
+ return check
+ """,
+ "mainwrapper.py": """\
+ import importlib.metadata
+ import pytest
+
+ class DummyEntryPoint(object):
+ name = 'spamplugin'
+ module_name = 'spam.py'
+ group = 'pytest11'
+
+ def load(self):
+ import spamplugin
+ return spamplugin
+
+ class DummyDistInfo(object):
+ version = '1.0'
+ files = ('spamplugin.py', 'hampkg/__init__.py')
+ entry_points = (DummyEntryPoint(),)
+ metadata = {'name': 'foo'}
+
+ def distributions():
+ return (DummyDistInfo(),)
+
+ importlib.metadata.distributions = distributions
+ pytest.main()
+ """,
+ "test_foo.py": """\
+ def test(check_first):
+ check_first([10, 30], 30)
+
+ def test2(check_first2):
+ check_first2([10, 30], 30)
+ """,
+ }
+ pytester.makepyfile(**contents)
+ result = pytester.run(sys.executable, *args)
+ if mode == "plain":
+ expected = "E AssertionError"
+ elif mode == "rewrite":
+ expected = "*assert 10 == 30*"
+ else:
+ assert 0
+
+ if not disable_plugin_autoload or explicit_specify:
+ result.assert_outcomes(failed=2)
+ result.stdout.fnmatch_lines([expected, expected])
+ else:
+ result.assert_outcomes(errors=2)
+ result.stdout.fnmatch_lines(
+ [
+ "E fixture 'check_first' not found",
+ "E fixture 'check_first2' not found",
+ ]
+ )
+
+ def test_rewrite_ast(self, pytester: Pytester) -> None:
+ pytester.mkdir("pkg")
+ contents = {
+ "pkg/__init__.py": """
+ import pytest
+ pytest.register_assert_rewrite('pkg.helper')
+ """,
+ "pkg/helper.py": """
+ def tool():
+ a, b = 2, 3
+ assert a == b
+ """,
+ "pkg/plugin.py": """
+ import pytest, pkg.helper
+ @pytest.fixture
+ def tool():
+ return pkg.helper.tool
+ """,
+ "pkg/other.py": """
+ values = [3, 2]
+ def tool():
+ assert values.pop() == 3
+ """,
+ "conftest.py": """
+ pytest_plugins = ['pkg.plugin']
+ """,
+ "test_pkg.py": """
+ import pkg.other
+ def test_tool(tool):
+ tool()
+ def test_other():
+ pkg.other.tool()
+ """,
+ }
+ pytester.makepyfile(**contents)
+ result = pytester.runpytest_subprocess("--assert=rewrite")
+ result.stdout.fnmatch_lines(
+ [
+ ">*assert a == b*",
+ "E*assert 2 == 3*",
+ ">*assert values.pop() == 3*",
+ "E*AssertionError",
+ ]
+ )
+
+ def test_register_assert_rewrite_checks_types(self) -> None:
+ with pytest.raises(TypeError):
+ pytest.register_assert_rewrite(["pytest_tests_internal_non_existing"]) # type: ignore
+ pytest.register_assert_rewrite(
+ "pytest_tests_internal_non_existing", "pytest_tests_internal_non_existing2"
+ )
+
+
+class TestBinReprIntegration:
+ def test_pytest_assertrepr_compare_called(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ values = []
+ def pytest_assertrepr_compare(op, left, right):
+ values.append((op, left, right))
+
+ @pytest.fixture
+ def list(request):
+ return values
+ """
+ )
+ pytester.makepyfile(
+ """
+ def test_hello():
+ assert 0 == 1
+ def test_check(list):
+ assert list == [("==", 0, 1)]
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines(["*test_hello*FAIL*", "*test_check*PASS*"])
+
+
+def callop(op: str, left: Any, right: Any, verbose: int = 0) -> list[str] | None:
+ config = mock_config(verbose=verbose)
+ return plugin.pytest_assertrepr_compare(config, op, left, right)
+
+
+def callequal(left: Any, right: Any, verbose: int = 0) -> list[str] | None:
+ return callop("==", left, right, verbose)
+
+
+class TestAssert_reprcompare:
+ def test_different_types(self) -> None:
+ assert callequal([0, 1], "foo") is None
+
+ def test_summary(self) -> None:
+ lines = callequal([0, 1], [0, 2])
+ assert lines is not None
+ summary = lines[0]
+ assert len(summary) < 65
+
+ def test_text_diff(self) -> None:
+ assert callequal("spam", "eggs") == [
+ "'spam' == 'eggs'",
+ "",
+ "- eggs",
+ "+ spam",
+ ]
+
+ def test_text_skipping(self) -> None:
+ lines = callequal("a" * 50 + "spam", "a" * 50 + "eggs")
+ assert lines is not None
+ assert "Skipping" in lines[2]
+ for line in lines:
+ assert "a" * 50 not in line
+
+ def test_text_skipping_verbose(self) -> None:
+ lines = callequal("a" * 50 + "spam", "a" * 50 + "eggs", verbose=1)
+ assert lines is not None
+ assert "- " + "a" * 50 + "eggs" in lines
+ assert "+ " + "a" * 50 + "spam" in lines
+
+ def test_multiline_text_diff(self) -> None:
+ left = "foo\nspam\nbar"
+ right = "foo\neggs\nbar"
+ diff = callequal(left, right)
+ assert diff is not None
+ assert "- eggs" in diff
+ assert "+ spam" in diff
+
+ def test_bytes_diff_normal(self) -> None:
+ """Check special handling for bytes diff (#5260)"""
+ diff = callequal(b"spam", b"eggs")
+
+ assert diff == [
+ "b'spam' == b'eggs'",
+ "",
+ "At index 0 diff: b's' != b'e'",
+ "Use -v to get more diff",
+ ]
+
+ def test_bytes_diff_verbose(self) -> None:
+ """Check special handling for bytes diff (#5260)"""
+ diff = callequal(b"spam", b"eggs", verbose=1)
+ assert diff == [
+ "b'spam' == b'eggs'",
+ "",
+ "At index 0 diff: b's' != b'e'",
+ "",
+ "Full diff:",
+ "- b'eggs'",
+ "+ b'spam'",
+ ]
+
+ def test_list(self) -> None:
+ expl = callequal([0, 1], [0, 2])
+ assert expl is not None
+ assert len(expl) > 1
+
+ @pytest.mark.parametrize(
+ ["left", "right", "expected"],
+ [
+ pytest.param(
+ [0, 1],
+ [0, 2],
+ """
+ Full diff:
+ [
+ 0,
+ - 2,
+ ? ^
+ + 1,
+ ? ^
+ ]
+ """,
+ id="lists",
+ ),
+ pytest.param(
+ {0: 1},
+ {0: 2},
+ """
+ Full diff:
+ {
+ - 0: 2,
+ ? ^
+ + 0: 1,
+ ? ^
+ }
+ """,
+ id="dicts",
+ ),
+ pytest.param(
+ {0, 1},
+ {0, 2},
+ """
+ Full diff:
+ {
+ 0,
+ - 2,
+ ? ^
+ + 1,
+ ? ^
+ }
+ """,
+ id="sets",
+ ),
+ ],
+ )
+ def test_iterable_full_diff(self, left, right, expected) -> None:
+ """Test the full diff assertion failure explanation.
+
+ When verbose is False, then just a -v notice to get the diff is rendered,
+ when verbose is True, then ndiff of the pprint is returned.
+ """
+ expl = callequal(left, right, verbose=0)
+ assert expl is not None
+ assert expl[-1] == "Use -v to get more diff"
+ verbose_expl = callequal(left, right, verbose=1)
+ assert verbose_expl is not None
+ assert "\n".join(verbose_expl).endswith(textwrap.dedent(expected).strip())
+
+ def test_iterable_quiet(self) -> None:
+ expl = callequal([1, 2], [10, 2], verbose=-1)
+ assert expl == [
+ "[1, 2] == [10, 2]",
+ "",
+ "At index 0 diff: 1 != 10",
+ "Use -v to get more diff",
+ ]
+
+ def test_iterable_full_diff_ci(
+ self, monkeypatch: MonkeyPatch, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ r"""
+ def test_full_diff():
+ left = [0, 1]
+ right = [0, 2]
+ assert left == right
+ """
+ )
+ monkeypatch.setenv("CI", "true")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["E Full diff:"])
+
+ # Setting CI to empty string is same as having it undefined
+ monkeypatch.setenv("CI", "")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["E Use -v to get more diff"])
+
+ monkeypatch.delenv("CI", raising=False)
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["E Use -v to get more diff"])
+
+ def test_list_different_lengths(self) -> None:
+ expl = callequal([0, 1], [0, 1, 2])
+ assert expl is not None
+ assert len(expl) > 1
+ expl = callequal([0, 1, 2], [0, 1])
+ assert expl is not None
+ assert len(expl) > 1
+
+ def test_list_wrap_for_multiple_lines(self) -> None:
+ long_d = "d" * 80
+ l1 = ["a", "b", "c"]
+ l2 = ["a", "b", "c", long_d]
+ diff = callequal(l1, l2, verbose=True)
+ assert diff == [
+ "['a', 'b', 'c'] == ['a', 'b', 'c...dddddddddddd']",
+ "",
+ "Right contains one more item: '" + long_d + "'",
+ "",
+ "Full diff:",
+ " [",
+ " 'a',",
+ " 'b',",
+ " 'c',",
+ "- '" + long_d + "',",
+ " ]",
+ ]
+
+ diff = callequal(l2, l1, verbose=True)
+ assert diff == [
+ "['a', 'b', 'c...dddddddddddd'] == ['a', 'b', 'c']",
+ "",
+ "Left contains one more item: '" + long_d + "'",
+ "",
+ "Full diff:",
+ " [",
+ " 'a',",
+ " 'b',",
+ " 'c',",
+ "+ '" + long_d + "',",
+ " ]",
+ ]
+
+ def test_list_wrap_for_width_rewrap_same_length(self) -> None:
+ long_a = "a" * 30
+ long_b = "b" * 30
+ long_c = "c" * 30
+ l1 = [long_a, long_b, long_c]
+ l2 = [long_b, long_c, long_a]
+ diff = callequal(l1, l2, verbose=True)
+ assert diff == [
+ "['aaaaaaaaaaa...cccccccccccc'] == ['bbbbbbbbbbb...aaaaaaaaaaaa']",
+ "",
+ "At index 0 diff: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' != 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'",
+ "",
+ "Full diff:",
+ " [",
+ "+ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',",
+ " 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',",
+ " 'cccccccccccccccccccccccccccccc',",
+ "- 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',",
+ " ]",
+ ]
+
+ def test_list_dont_wrap_strings(self) -> None:
+ long_a = "a" * 10
+ l1 = ["a"] + [long_a for _ in range(7)]
+ l2 = ["should not get wrapped"]
+ diff = callequal(l1, l2, verbose=True)
+ assert diff == [
+ "['a', 'aaaaaa...aaaaaaa', ...] == ['should not get wrapped']",
+ "",
+ "At index 0 diff: 'a' != 'should not get wrapped'",
+ "Left contains 7 more items, first extra item: 'aaaaaaaaaa'",
+ "",
+ "Full diff:",
+ " [",
+ "- 'should not get wrapped',",
+ "+ 'a',",
+ "+ 'aaaaaaaaaa',",
+ "+ 'aaaaaaaaaa',",
+ "+ 'aaaaaaaaaa',",
+ "+ 'aaaaaaaaaa',",
+ "+ 'aaaaaaaaaa',",
+ "+ 'aaaaaaaaaa',",
+ "+ 'aaaaaaaaaa',",
+ " ]",
+ ]
+
+ def test_dict_wrap(self) -> None:
+ d1 = {"common": 1, "env": {"env1": 1, "env2": 2}}
+ d2 = {"common": 1, "env": {"env1": 1}}
+
+ diff = callequal(d1, d2, verbose=True)
+ assert diff == [
+ "{'common': 1,...1, 'env2': 2}} == {'common': 1,...: {'env1': 1}}",
+ "",
+ "Omitting 1 identical items, use -vv to show",
+ "Differing items:",
+ "{'env': {'env1': 1, 'env2': 2}} != {'env': {'env1': 1}}",
+ "",
+ "Full diff:",
+ " {",
+ " 'common': 1,",
+ " 'env': {",
+ " 'env1': 1,",
+ "+ 'env2': 2,",
+ " },",
+ " }",
+ ]
+
+ long_a = "a" * 80
+ sub = {"long_a": long_a, "sub1": {"long_a": "substring that gets wrapped " * 3}}
+ d1 = {"env": {"sub": sub}}
+ d2 = {"env": {"sub": sub}, "new": 1}
+ diff = callequal(d1, d2, verbose=True)
+ assert diff == [
+ "{'env': {'sub... wrapped '}}}} == {'env': {'sub...}}}, 'new': 1}",
+ "",
+ "Omitting 1 identical items, use -vv to show",
+ "Right contains 1 more item:",
+ "{'new': 1}",
+ "",
+ "Full diff:",
+ " {",
+ " 'env': {",
+ " 'sub': {",
+ f" 'long_a': '{long_a}',",
+ " 'sub1': {",
+ " 'long_a': 'substring that gets wrapped substring that gets wrapped '",
+ " 'substring that gets wrapped ',",
+ " },",
+ " },",
+ " },",
+ "- 'new': 1,",
+ " }",
+ ]
+
+ def test_dict(self) -> None:
+ expl = callequal({"a": 0}, {"a": 1})
+ assert expl is not None
+ assert len(expl) > 1
+
+ def test_dict_omitting(self) -> None:
+ lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1})
+ assert lines is not None
+ assert lines[2].startswith("Omitting 1 identical item")
+ assert "Common items" not in lines
+ for line in lines[1:]:
+ assert "b" not in line
+
+ def test_dict_omitting_with_verbosity_1(self) -> None:
+ """Ensure differing items are visible for verbosity=1 (#1512)."""
+ lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}, verbose=1)
+ assert lines is not None
+ assert lines[1] == ""
+ assert lines[2].startswith("Omitting 1 identical item")
+ assert lines[3].startswith("Differing items")
+ assert lines[4] == "{'a': 0} != {'a': 1}"
+ assert "Common items" not in lines
+
+ def test_dict_omitting_with_verbosity_2(self) -> None:
+ lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}, verbose=2)
+ assert lines is not None
+ assert lines[2].startswith("Common items:")
+ assert "Omitting" not in lines[2]
+ assert lines[3] == "{'b': 1}"
+
+ def test_dict_different_items(self) -> None:
+ lines = callequal({"a": 0}, {"b": 1, "c": 2}, verbose=2)
+ assert lines == [
+ "{'a': 0} == {'b': 1, 'c': 2}",
+ "",
+ "Left contains 1 more item:",
+ "{'a': 0}",
+ "Right contains 2 more items:",
+ "{'b': 1, 'c': 2}",
+ "",
+ "Full diff:",
+ " {",
+ "- 'b': 1,",
+ "? ^ ^",
+ "+ 'a': 0,",
+ "? ^ ^",
+ "- 'c': 2,",
+ " }",
+ ]
+ lines = callequal({"b": 1, "c": 2}, {"a": 0}, verbose=2)
+ assert lines == [
+ "{'b': 1, 'c': 2} == {'a': 0}",
+ "",
+ "Left contains 2 more items:",
+ "{'b': 1, 'c': 2}",
+ "Right contains 1 more item:",
+ "{'a': 0}",
+ "",
+ "Full diff:",
+ " {",
+ "- 'a': 0,",
+ "? ^ ^",
+ "+ 'b': 1,",
+ "? ^ ^",
+ "+ 'c': 2,",
+ " }",
+ ]
+
+ def test_sequence_different_items(self) -> None:
+ lines = callequal((1, 2), (3, 4, 5), verbose=2)
+ assert lines == [
+ "(1, 2) == (3, 4, 5)",
+ "",
+ "At index 0 diff: 1 != 3",
+ "Right contains one more item: 5",
+ "",
+ "Full diff:",
+ " (",
+ "- 3,",
+ "? ^",
+ "+ 1,",
+ "? ^",
+ "- 4,",
+ "? ^",
+ "+ 2,",
+ "? ^",
+ "- 5,",
+ " )",
+ ]
+ lines = callequal((1, 2, 3), (4,), verbose=2)
+ assert lines == [
+ "(1, 2, 3) == (4,)",
+ "",
+ "At index 0 diff: 1 != 4",
+ "Left contains 2 more items, first extra item: 2",
+ "",
+ "Full diff:",
+ " (",
+ "- 4,",
+ "? ^",
+ "+ 1,",
+ "? ^",
+ "+ 2,",
+ "+ 3,",
+ " )",
+ ]
+ lines = callequal((1, 2, 3), (1, 20, 3), verbose=2)
+ assert lines == [
+ "(1, 2, 3) == (1, 20, 3)",
+ "",
+ "At index 1 diff: 2 != 20",
+ "",
+ "Full diff:",
+ " (",
+ " 1,",
+ "- 20,",
+ "? -",
+ "+ 2,",
+ " 3,",
+ " )",
+ ]
+
+ def test_set(self) -> None:
+ expl = callequal({0, 1}, {0, 2})
+ assert expl is not None
+ assert len(expl) > 1
+
+ def test_frozenzet(self) -> None:
+ expl = callequal(frozenset([0, 1]), {0, 2})
+ assert expl is not None
+ assert len(expl) > 1
+
+ def test_Sequence(self) -> None:
+ # Test comparing with a Sequence subclass.
+ class TestSequence(MutableSequence[int]):
+ def __init__(self, iterable):
+ self.elements = list(iterable)
+
+ def __getitem__(self, item):
+ return self.elements[item]
+
+ def __len__(self):
+ return len(self.elements)
+
+ def __setitem__(self, item, value):
+ pass
+
+ def __delitem__(self, item):
+ pass
+
+ def insert(self, index, value):
+ pass
+
+ expl = callequal(TestSequence([0, 1]), list([0, 2]))
+ assert expl is not None
+ assert len(expl) > 1
+
+ def test_list_tuples(self) -> None:
+ expl = callequal([], [(1, 2)])
+ assert expl is not None
+ assert len(expl) > 1
+ expl = callequal([(1, 2)], [])
+ assert expl is not None
+ assert len(expl) > 1
+
+ def test_list_bad_repr(self) -> None:
+ class A:
+ def __repr__(self):
+ raise ValueError(42)
+
+ expl = callequal([], [A()])
+ assert expl is not None
+ assert "ValueError" in "".join(expl)
+ expl = callequal({}, {"1": A()}, verbose=2)
+ assert expl is not None
+ assert expl[0].startswith("{} == <[ValueError")
+ assert "raised in repr" in expl[0]
+ assert expl[2:] == [
+ "(pytest_assertion plugin: representation of details failed:"
+ f" {__file__}:{A.__repr__.__code__.co_firstlineno + 1}: ValueError: 42.",
+ " Probably an object has a faulty __repr__.)",
+ ]
+
+ def test_one_repr_empty(self) -> None:
+ """The faulty empty string repr did trigger an unbound local error in _diff_text."""
+
+ class A(str):
+ def __repr__(self):
+ return ""
+
+ expl = callequal(A(), "")
+ assert not expl
+
+ def test_repr_no_exc(self) -> None:
+ expl = callequal("foo", "bar")
+ assert expl is not None
+ assert "raised in repr()" not in " ".join(expl)
+
+ def test_unicode(self) -> None:
+ assert callequal("£€", "£") == [
+ "'£€' == '£'",
+ "",
+ "- £",
+ "+ £€",
+ ]
+
+ def test_nonascii_text(self) -> None:
+ """
+ :issue: 877
+ non ascii python2 str caused a UnicodeDecodeError
+ """
+
+ class A(str):
+ def __repr__(self):
+ return "\xff"
+
+ expl = callequal(A(), "1")
+ assert expl == ["ÿ == '1'", "", "- 1"]
+
+ def test_format_nonascii_explanation(self) -> None:
+ assert util.format_explanation("λ")
+
+ def test_mojibake(self) -> None:
+ # issue 429
+ left = b"e"
+ right = b"\xc3\xa9"
+ expl = callequal(left, right)
+ assert expl is not None
+ for line in expl:
+ assert isinstance(line, str)
+ msg = "\n".join(expl)
+ assert msg
+
+ def test_nfc_nfd_same_string(self) -> None:
+ # issue 3426
+ left = "hyv\xe4"
+ right = "hyva\u0308"
+ expl = callequal(left, right)
+ assert expl == [
+ r"'hyv\xe4' == 'hyva\u0308'",
+ "",
+ f"- {right!s}",
+ f"+ {left!s}",
+ ]
+
+ expl = callequal(left, right, verbose=2)
+ assert expl == [
+ r"'hyv\xe4' == 'hyva\u0308'",
+ "",
+ f"- {right!s}",
+ f"+ {left!s}",
+ ]
+
+
+class TestAssert_reprcompare_dataclass:
+ def test_dataclasses(self, pytester: Pytester) -> None:
+ p = pytester.copy_example("dataclasses/test_compare_dataclasses.py")
+ result = pytester.runpytest(p)
+ result.assert_outcomes(failed=1, passed=0)
+ result.stdout.fnmatch_lines(
+ [
+ "E Omitting 1 identical items, use -vv to show",
+ "E Differing attributes:",
+ "E ['field_b']",
+ "E ",
+ "E Drill down into differing attribute field_b:",
+ "E field_b: 'b' != 'c'",
+ "E - c",
+ "E + b",
+ ],
+ consecutive=True,
+ )
+
+ def test_recursive_dataclasses(self, pytester: Pytester) -> None:
+ p = pytester.copy_example("dataclasses/test_compare_recursive_dataclasses.py")
+ result = pytester.runpytest(p)
+ result.assert_outcomes(failed=1, passed=0)
+ result.stdout.fnmatch_lines(
+ [
+ "E Omitting 1 identical items, use -vv to show",
+ "E Differing attributes:",
+ "E ['g', 'h', 'j']",
+ "E ",
+ "E Drill down into differing attribute g:",
+ "E g: S(a=10, b='ten') != S(a=20, b='xxx')...",
+ "E ",
+ "E ...Full output truncated (51 lines hidden), use '-vv' to show",
+ ],
+ consecutive=True,
+ )
+
+ def test_recursive_dataclasses_verbose(self, pytester: Pytester) -> None:
+ p = pytester.copy_example("dataclasses/test_compare_recursive_dataclasses.py")
+ result = pytester.runpytest(p, "-vv")
+ result.assert_outcomes(failed=1, passed=0)
+ result.stdout.fnmatch_lines(
+ [
+ "E Matching attributes:",
+ "E ['i']",
+ "E Differing attributes:",
+ "E ['g', 'h', 'j']",
+ "E ",
+ "E Drill down into differing attribute g:",
+ "E g: S(a=10, b='ten') != S(a=20, b='xxx')",
+ "E ",
+ "E Differing attributes:",
+ "E ['a', 'b']",
+ "E ",
+ "E Drill down into differing attribute a:",
+ "E a: 10 != 20",
+ "E ",
+ "E Drill down into differing attribute b:",
+ "E b: 'ten' != 'xxx'",
+ "E - xxx",
+ "E + ten",
+ "E ",
+ "E Drill down into differing attribute h:",
+ ],
+ consecutive=True,
+ )
+
+ def test_dataclasses_verbose(self, pytester: Pytester) -> None:
+ p = pytester.copy_example("dataclasses/test_compare_dataclasses_verbose.py")
+ result = pytester.runpytest(p, "-vv")
+ result.assert_outcomes(failed=1, passed=0)
+ result.stdout.fnmatch_lines(
+ [
+ "*Matching attributes:*",
+ "*['field_a']*",
+ "*Differing attributes:*",
+ "*field_b: 'b' != 'c'*",
+ ]
+ )
+
+ def test_dataclasses_with_attribute_comparison_off(
+ self, pytester: Pytester
+ ) -> None:
+ p = pytester.copy_example(
+ "dataclasses/test_compare_dataclasses_field_comparison_off.py"
+ )
+ result = pytester.runpytest(p, "-vv")
+ result.assert_outcomes(failed=0, passed=1)
+
+ def test_comparing_two_different_data_classes(self, pytester: Pytester) -> None:
+ p = pytester.copy_example(
+ "dataclasses/test_compare_two_different_dataclasses.py"
+ )
+ result = pytester.runpytest(p, "-vv")
+ result.assert_outcomes(failed=0, passed=1)
+
+ def test_data_classes_with_custom_eq(self, pytester: Pytester) -> None:
+ p = pytester.copy_example(
+ "dataclasses/test_compare_dataclasses_with_custom_eq.py"
+ )
+ # issue 9362
+ result = pytester.runpytest(p, "-vv")
+ result.assert_outcomes(failed=1, passed=0)
+ result.stdout.no_re_match_line(".*Differing attributes.*")
+
+ def test_data_classes_with_initvar(self, pytester: Pytester) -> None:
+ p = pytester.copy_example("dataclasses/test_compare_initvar.py")
+ # issue 9820
+ result = pytester.runpytest(p, "-vv")
+ result.assert_outcomes(failed=1, passed=0)
+ result.stdout.no_re_match_line(".*AttributeError.*")
+
+
+class TestAssert_reprcompare_attrsclass:
+ def test_attrs(self) -> None:
+ @attr.s
+ class SimpleDataObject:
+ field_a = attr.ib()
+ field_b = attr.ib()
+
+ left = SimpleDataObject(1, "b")
+ right = SimpleDataObject(1, "c")
+
+ lines = callequal(left, right)
+ assert lines is not None
+ assert lines[2].startswith("Omitting 1 identical item")
+ assert "Matching attributes" not in lines
+ for line in lines[2:]:
+ assert "field_a" not in line
+
+ def test_attrs_recursive(self) -> None:
+ @attr.s
+ class OtherDataObject:
+ field_c = attr.ib()
+ field_d = attr.ib()
+
+ @attr.s
+ class SimpleDataObject:
+ field_a = attr.ib()
+ field_b = attr.ib()
+
+ left = SimpleDataObject(OtherDataObject(1, "a"), "b")
+ right = SimpleDataObject(OtherDataObject(1, "b"), "b")
+
+ lines = callequal(left, right)
+ assert lines is not None
+ assert "Matching attributes" not in lines
+ for line in lines[1:]:
+ assert "field_b:" not in line
+ assert "field_c:" not in line
+
+ def test_attrs_recursive_verbose(self) -> None:
+ @attr.s
+ class OtherDataObject:
+ field_c = attr.ib()
+ field_d = attr.ib()
+
+ @attr.s
+ class SimpleDataObject:
+ field_a = attr.ib()
+ field_b = attr.ib()
+
+ left = SimpleDataObject(OtherDataObject(1, "a"), "b")
+ right = SimpleDataObject(OtherDataObject(1, "b"), "b")
+
+ lines = callequal(left, right)
+ assert lines is not None
+ # indentation in output because of nested object structure
+ assert " field_d: 'a' != 'b'" in lines
+
+ def test_attrs_verbose(self) -> None:
+ @attr.s
+ class SimpleDataObject:
+ field_a = attr.ib()
+ field_b = attr.ib()
+
+ left = SimpleDataObject(1, "b")
+ right = SimpleDataObject(1, "c")
+
+ lines = callequal(left, right, verbose=2)
+ assert lines is not None
+ assert lines[2].startswith("Matching attributes:")
+ assert "Omitting" not in lines[2]
+ assert lines[3] == "['field_a']"
+
+ def test_attrs_with_attribute_comparison_off(self) -> None:
+ @attr.s
+ class SimpleDataObject:
+ field_a = attr.ib()
+ field_b = attr.ib(eq=False)
+
+ left = SimpleDataObject(1, "b")
+ right = SimpleDataObject(1, "b")
+
+ lines = callequal(left, right, verbose=2)
+ assert lines is not None
+ assert lines[2].startswith("Matching attributes:")
+ assert "Omitting" not in lines[1]
+ assert lines[3] == "['field_a']"
+ for line in lines[3:]:
+ assert "field_b" not in line
+
+ def test_comparing_two_different_attrs_classes(self) -> None:
+ @attr.s
+ class SimpleDataObjectOne:
+ field_a = attr.ib()
+ field_b = attr.ib()
+
+ @attr.s
+ class SimpleDataObjectTwo:
+ field_a = attr.ib()
+ field_b = attr.ib()
+
+ left = SimpleDataObjectOne(1, "b")
+ right = SimpleDataObjectTwo(1, "c")
+
+ lines = callequal(left, right)
+ assert lines is None
+
+ def test_attrs_with_auto_detect_and_custom_eq(self) -> None:
+ @attr.s(
+ auto_detect=True
+ ) # attr.s doesn't ignore a custom eq if auto_detect=True
+ class SimpleDataObject:
+ field_a = attr.ib()
+
+ def __eq__(self, other): # pragma: no cover
+ return super().__eq__(other)
+
+ left = SimpleDataObject(1)
+ right = SimpleDataObject(2)
+ # issue 9362
+ lines = callequal(left, right, verbose=2)
+ assert lines is None
+
+ def test_attrs_with_custom_eq(self) -> None:
+ @attr.define(slots=False)
+ class SimpleDataObject:
+ field_a = attr.ib()
+
+ def __eq__(self, other): # pragma: no cover
+ return super().__eq__(other)
+
+ left = SimpleDataObject(1)
+ right = SimpleDataObject(2)
+ # issue 9362
+ lines = callequal(left, right, verbose=2)
+ assert lines is None
+
+
+class TestAssert_reprcompare_namedtuple:
+ def test_namedtuple(self) -> None:
+ class NT(NamedTuple):
+ a: Any
+ b: Any
+
+ left = NT(1, "b")
+ right = NT(1, "c")
+
+ lines = callequal(left, right)
+ assert lines == [
+ "NT(a=1, b='b') == NT(a=1, b='c')",
+ "",
+ "Omitting 1 identical items, use -vv to show",
+ "Differing attributes:",
+ "['b']",
+ "",
+ "Drill down into differing attribute b:",
+ " b: 'b' != 'c'",
+ " - c",
+ " + b",
+ "Use -v to get more diff",
+ ]
+
+ def test_comparing_two_different_namedtuple(self) -> None:
+ class NT1(NamedTuple):
+ a: Any
+ b: Any
+
+ class NT2(NamedTuple):
+ a: Any
+ b: Any
+
+ left = NT1(1, "b")
+ right = NT2(2, "b")
+
+ lines = callequal(left, right)
+ # Because the types are different, uses the generic sequence matcher.
+ assert lines == [
+ "NT1(a=1, b='b') == NT2(a=2, b='b')",
+ "",
+ "At index 0 diff: 1 != 2",
+ "Use -v to get more diff",
+ ]
+
+
+class TestFormatExplanation:
+ def test_special_chars_full(self, pytester: Pytester) -> None:
+ # Issue 453, for the bug this would raise IndexError
+ pytester.makepyfile(
+ """
+ def test_foo():
+ assert '\\n}' == ''
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*AssertionError*"])
+
+ def test_fmt_simple(self) -> None:
+ expl = "assert foo"
+ assert util.format_explanation(expl) == "assert foo"
+
+ def test_fmt_where(self) -> None:
+ expl = "\n".join(["assert 1", "{1 = foo", "} == 2"])
+ res = "\n".join(["assert 1 == 2", " + where 1 = foo"])
+ assert util.format_explanation(expl) == res
+
+ def test_fmt_and(self) -> None:
+ expl = "\n".join(["assert 1", "{1 = foo", "} == 2", "{2 = bar", "}"])
+ res = "\n".join(["assert 1 == 2", " + where 1 = foo", " + and 2 = bar"])
+ assert util.format_explanation(expl) == res
+
+ def test_fmt_where_nested(self) -> None:
+ expl = "\n".join(["assert 1", "{1 = foo", "{foo = bar", "}", "} == 2"])
+ res = "\n".join(["assert 1 == 2", " + where 1 = foo", " + where foo = bar"])
+ assert util.format_explanation(expl) == res
+
+ def test_fmt_newline(self) -> None:
+ expl = "\n".join(['assert "foo" == "bar"', "~- foo", "~+ bar"])
+ res = "\n".join(['assert "foo" == "bar"', " - foo", " + bar"])
+ assert util.format_explanation(expl) == res
+
+ def test_fmt_newline_escaped(self) -> None:
+ expl = "\n".join(["assert foo == bar", "baz"])
+ res = "assert foo == bar\\nbaz"
+ assert util.format_explanation(expl) == res
+
+ def test_fmt_newline_before_where(self) -> None:
+ expl = "\n".join(
+ [
+ "the assertion message here",
+ ">assert 1",
+ "{1 = foo",
+ "} == 2",
+ "{2 = bar",
+ "}",
+ ]
+ )
+ res = "\n".join(
+ [
+ "the assertion message here",
+ "assert 1 == 2",
+ " + where 1 = foo",
+ " + and 2 = bar",
+ ]
+ )
+ assert util.format_explanation(expl) == res
+
+ def test_fmt_multi_newline_before_where(self) -> None:
+ expl = "\n".join(
+ [
+ "the assertion",
+ "~message here",
+ ">assert 1",
+ "{1 = foo",
+ "} == 2",
+ "{2 = bar",
+ "}",
+ ]
+ )
+ res = "\n".join(
+ [
+ "the assertion",
+ " message here",
+ "assert 1 == 2",
+ " + where 1 = foo",
+ " + and 2 = bar",
+ ]
+ )
+ assert util.format_explanation(expl) == res
+
+
+class TestTruncateExplanation:
+ # The number of lines in the truncation explanation message. Used
+ # to calculate that results have the expected length.
+ LINES_IN_TRUNCATION_MSG = 2
+
+ def test_doesnt_truncate_when_input_is_empty_list(self) -> None:
+ expl: list[str] = []
+ result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)
+ assert result == expl
+
+ def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self) -> None:
+ expl = ["a" * 100 for x in range(5)]
+ result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
+ assert result == expl
+
+ def test_truncates_at_8_lines_when_given_list_of_empty_strings(self) -> None:
+ expl = ["" for x in range(50)]
+ result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)
+ assert len(result) != len(expl)
+ assert result != expl
+ assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG
+ assert "Full output truncated" in result[-1]
+ assert "42 lines hidden" in result[-1]
+ last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
+ assert last_line_before_trunc_msg.endswith("...")
+
+ def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self) -> None:
+ total_lines = 100
+ expl = ["a" for x in range(total_lines)]
+ result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
+ assert result != expl
+ assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG
+ assert "Full output truncated" in result[-1]
+ assert f"{total_lines - 8} lines hidden" in result[-1]
+ last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
+ assert last_line_before_trunc_msg.endswith("...")
+
+ def test_truncates_at_8_lines_when_there_is_one_line_to_remove(self) -> None:
+ """The number of line in the result is 9, the same number as if we truncated."""
+ expl = ["a" for x in range(9)]
+ result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
+ assert result == expl
+ assert "truncated" not in result[-1]
+
+ def test_truncates_full_line_because_of_max_chars(self) -> None:
+ """A line is fully truncated because of the max_chars value."""
+ expl = ["a" * 10, "b" * 71]
+ result = truncate._truncate_explanation(expl, max_lines=10, max_chars=10)
+ assert result == [
+ "a" * 10,
+ "...",
+ "",
+ "...Full output truncated (1 line hidden), use '-vv' to show",
+ ]
+
+ def test_truncates_edgecase_when_truncation_message_makes_the_result_longer_for_chars(
+ self,
+ ) -> None:
+ line = "a" * 10
+ expl = [line, line]
+ result = truncate._truncate_explanation(expl, max_lines=10, max_chars=10)
+ assert result == [line, line]
+
+ def test_truncates_edgecase_when_truncation_message_makes_the_result_longer_for_lines(
+ self,
+ ) -> None:
+ line = "a" * 10
+ expl = [line, line]
+ result = truncate._truncate_explanation(expl, max_lines=1, max_chars=100)
+ assert result == [line, line]
+
+ def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self) -> None:
+ expl = [chr(97 + x) * 80 for x in range(16)]
+ result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
+ assert result != expl
+ assert len(result) == 16 - 8 + self.LINES_IN_TRUNCATION_MSG
+ assert "Full output truncated" in result[-1]
+ assert "8 lines hidden" in result[-1]
+ last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
+ assert last_line_before_trunc_msg.endswith("...")
+
+ def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self) -> None:
+ expl = ["a" * 250 for x in range(10)]
+ result = truncate._truncate_explanation(expl, max_lines=8, max_chars=999)
+ assert result != expl
+ assert len(result) == 4 + self.LINES_IN_TRUNCATION_MSG
+ assert "Full output truncated" in result[-1]
+ assert "7 lines hidden" in result[-1]
+ last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
+ assert last_line_before_trunc_msg.endswith("...")
+
+ def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self) -> None:
+ expl = ["a" * 250 for x in range(1000)]
+ result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)
+ assert result != expl
+ assert len(result) == 1 + self.LINES_IN_TRUNCATION_MSG
+ assert "Full output truncated" in result[-1]
+ assert "1000 lines hidden" in result[-1]
+ last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
+ assert last_line_before_trunc_msg.endswith("...")
+
+ def test_full_output_truncated(self, monkeypatch, pytester: Pytester) -> None:
+ """Test against full runpytest() output."""
+ line_count = 7
+ line_len = 100
+ expected_truncated_lines = 2
+ pytester.makepyfile(
+ rf"""
+ def test_many_lines():
+ a = list([str(i)[0] * {line_len} for i in range({line_count})])
+ b = a[::2]
+ a = '\n'.join(map(str, a))
+ b = '\n'.join(map(str, b))
+ assert a == b
+ """
+ )
+ monkeypatch.delenv("CI", raising=False)
+
+ result = pytester.runpytest()
+ # without -vv, truncate the message showing a few diff lines only
+ result.stdout.fnmatch_lines(
+ [
+ "*+ 1*",
+ "*+ 3*",
+ f"*truncated ({expected_truncated_lines} lines hidden)*use*-vv*",
+ ]
+ )
+
+ result = pytester.runpytest("-vv")
+ result.stdout.fnmatch_lines(["* 6*"])
+
+ # Setting CI to empty string is same as having it undefined
+ monkeypatch.setenv("CI", "")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*+ 1*",
+ "*+ 3*",
+ f"*truncated ({expected_truncated_lines} lines hidden)*use*-vv*",
+ ]
+ )
+
+ monkeypatch.setenv("CI", "1")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 6*"])
+
+ @pytest.mark.parametrize(
+ ["truncation_lines", "truncation_chars", "expected_lines_hidden"],
+ (
+ (3, None, 3),
+ (4, None, 0),
+ (0, None, 0),
+ (None, 8, 6),
+ (None, 9, 0),
+ (None, 0, 0),
+ (0, 0, 0),
+ (0, 1000, 0),
+ (1000, 0, 0),
+ ),
+ )
+ def test_truncation_with_ini(
+ self,
+ monkeypatch,
+ pytester: Pytester,
+ truncation_lines: int | None,
+ truncation_chars: int | None,
+ expected_lines_hidden: int,
+ ) -> None:
+ pytester.makepyfile(
+ """\
+ string_a = "123456789\\n23456789\\n3"
+ string_b = "123456789\\n23456789\\n4"
+
+ def test():
+ assert string_a == string_b
+ """
+ )
+
+ # This test produces 6 lines of diff output or 79 characters
+ # So the effect should be when threshold is < 4 lines (considering 2 additional lines for explanation)
+ # Or < 9 characters (considering 70 additional characters for explanation)
+
+ monkeypatch.delenv("CI", raising=False)
+
+ ini = "[pytest]\n"
+ if truncation_lines is not None:
+ ini += f"truncation_limit_lines = {truncation_lines}\n"
+ if truncation_chars is not None:
+ ini += f"truncation_limit_chars = {truncation_chars}\n"
+ pytester.makeini(ini)
+
+ result = pytester.runpytest()
+
+ if expected_lines_hidden != 0:
+ result.stdout.fnmatch_lines(
+ [f"*truncated ({expected_lines_hidden} lines hidden)*"]
+ )
+ else:
+ result.stdout.no_fnmatch_line("*truncated*")
+ result.stdout.fnmatch_lines(
+ [
+ "*- 4*",
+ "*+ 3*",
+ ]
+ )
+
+
+def test_python25_compile_issue257(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_rewritten():
+ assert 1 == 2
+ # some comment
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(
+ """
+ *E*assert 1 == 2*
+ *1 failed*
+ """
+ )
+
+
+def test_rewritten(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_rewritten():
+ assert "@py_builtins" in globals()
+ """
+ )
+ assert pytester.runpytest().ret == 0
+
+
+def test_reprcompare_notin() -> None:
+ assert callop("not in", "foo", "aaafoobbb") == [
+ "'foo' not in 'aaafoobbb'",
+ "",
+ "'foo' is contained here:",
+ " aaafoobbb",
+ "? +++",
+ ]
+
+
+def test_reprcompare_whitespaces() -> None:
+ assert callequal("\r\n", "\n") == [
+ r"'\r\n' == '\n'",
+ "",
+ r"Strings contain only whitespace, escaping them using repr()",
+ r"- '\n'",
+ r"+ '\r\n'",
+ r"? ++",
+ ]
+
+
+class TestSetAssertions:
+ @pytest.mark.parametrize("op", [">=", ">", "<=", "<", "=="])
+ def test_set_extra_item(self, op, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ f"""
+ def test_hello():
+ x = set("hello x")
+ y = set("hello y")
+ assert x {op} y
+ """
+ )
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*def test_hello():*",
+ f"*assert x {op} y*",
+ ]
+ )
+ if op in [">=", ">", "=="]:
+ result.stdout.fnmatch_lines(
+ [
+ "*E*Extra items in the right set:*",
+ "*E*'y'",
+ ]
+ )
+ if op in ["<=", "<", "=="]:
+ result.stdout.fnmatch_lines(
+ [
+ "*E*Extra items in the left set:*",
+ "*E*'x'",
+ ]
+ )
+
+ @pytest.mark.parametrize("op", [">", "<", "!="])
+ def test_set_proper_superset_equal(self, pytester: Pytester, op) -> None:
+ pytester.makepyfile(
+ f"""
+ def test_hello():
+ x = set([1, 2, 3])
+ y = x.copy()
+ assert x {op} y
+ """
+ )
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*def test_hello():*",
+ f"*assert x {op} y*",
+ "*E*Both sets are equal*",
+ ]
+ )
+
+ def test_pytest_assertrepr_compare_integration(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_hello():
+ x = set(range(100))
+ y = x.copy()
+ y.remove(50)
+ assert x == y
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*def test_hello():*",
+ "*assert x == y*",
+ "*E*Extra items*left*",
+ "*E*50*",
+ "*= 1 failed in*",
+ ]
+ )
+
+
+def test_assertrepr_loaded_per_dir(pytester: Pytester) -> None:
+ pytester.makepyfile(test_base=["def test_base(): assert 1 == 2"])
+ a = pytester.mkdir("a")
+ a.joinpath("test_a.py").write_text("def test_a(): assert 1 == 2", encoding="utf-8")
+ a.joinpath("conftest.py").write_text(
+ 'def pytest_assertrepr_compare(): return ["summary a"]', encoding="utf-8"
+ )
+ b = pytester.mkdir("b")
+ b.joinpath("test_b.py").write_text("def test_b(): assert 1 == 2", encoding="utf-8")
+ b.joinpath("conftest.py").write_text(
+ 'def pytest_assertrepr_compare(): return ["summary b"]', encoding="utf-8"
+ )
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*def test_a():*",
+ "*E*assert summary a*",
+ "*def test_b():*",
+ "*E*assert summary b*",
+ "*def test_base():*",
+ "*E*assert 1 == 2*",
+ ]
+ )
+
+
+def test_assertion_options(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_hello():
+ x = 3
+ assert x == 4
+ """
+ )
+ result = pytester.runpytest()
+ assert "3 == 4" in result.stdout.str()
+ result = pytester.runpytest_subprocess("--assert=plain")
+ result.stdout.no_fnmatch_line("*3 == 4*")
+
+
+def test_triple_quoted_string_issue113(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_hello():
+ assert "" == '''
+ '''"""
+ )
+ result = pytester.runpytest("--fulltrace")
+ result.stdout.fnmatch_lines(["*1 failed*"])
+ result.stdout.no_fnmatch_line("*SyntaxError*")
+
+
+def test_traceback_failure(pytester: Pytester) -> None:
+ p1 = pytester.makepyfile(
+ """
+ def g():
+ return 2
+ def f(x):
+ assert x == g()
+ def test_onefails():
+ f(3)
+ """
+ )
+ result = pytester.runpytest(p1, "--tb=long")
+ result.stdout.fnmatch_lines(
+ [
+ "*test_traceback_failure.py F*",
+ "====* FAILURES *====",
+ "____*____",
+ "",
+ " def test_onefails():",
+ "> f(3)",
+ "",
+ "*test_*.py:6: ",
+ "_ _ _ *",
+ # "",
+ " def f(x):",
+ "> assert x == g()",
+ "E assert 3 == 2",
+ "E + where 2 = g()",
+ "",
+ "*test_traceback_failure.py:4: AssertionError",
+ ]
+ )
+
+ result = pytester.runpytest(p1) # "auto"
+ result.stdout.fnmatch_lines(
+ [
+ "*test_traceback_failure.py F*",
+ "====* FAILURES *====",
+ "____*____",
+ "",
+ " def test_onefails():",
+ "> f(3)",
+ "",
+ "*test_*.py:6: ",
+ "",
+ " def f(x):",
+ "> assert x == g()",
+ "E assert 3 == 2",
+ "E + where 2 = g()",
+ "",
+ "*test_traceback_failure.py:4: AssertionError",
+ ]
+ )
+
+
+def test_exception_handling_no_traceback(pytester: Pytester) -> None:
+ """Handle chain exceptions in tasks submitted by the multiprocess module (#1984)."""
+ p1 = pytester.makepyfile(
+ """
+ from multiprocessing import Pool
+
+ def process_task(n):
+ assert n == 10
+
+ def multitask_job():
+ tasks = [1]
+ with Pool(processes=1) as pool:
+ pool.map(process_task, tasks)
+
+ def test_multitask_job():
+ multitask_job()
+ """
+ )
+ pytester.syspathinsert()
+ result = pytester.runpytest(p1, "--tb=long")
+ result.stdout.fnmatch_lines(
+ [
+ "====* FAILURES *====",
+ "*multiprocessing.pool.RemoteTraceback:*",
+ "Traceback (most recent call last):",
+ "*assert n == 10",
+ "The above exception was the direct cause of the following exception:",
+ "> * multitask_job()",
+ ]
+ )
+
+
+@pytest.mark.skipif("'__pypy__' in sys.builtin_module_names")
+@pytest.mark.parametrize(
+ "cmdline_args, warning_output",
+ [
+ (
+ ["-OO", "-m", "pytest", "-h"],
+ ["warning :*PytestConfigWarning:*assert statements are not executed*"],
+ ),
+ (
+ ["-OO", "-m", "pytest"],
+ [
+ "=*= warnings summary =*=",
+ "*PytestConfigWarning:*assert statements are not executed*",
+ ],
+ ),
+ (
+ ["-OO", "-m", "pytest", "--assert=plain"],
+ [
+ "=*= warnings summary =*=",
+ "*PytestConfigWarning: ASSERTIONS ARE NOT EXECUTED and FAILING TESTS WILL PASS. "
+ "Are you using python -O?",
+ ],
+ ),
+ ],
+)
+def test_warn_missing(pytester: Pytester, cmdline_args, warning_output) -> None:
+ pytester.makepyfile("")
+
+ result = pytester.run(sys.executable, *cmdline_args)
+ result.stdout.fnmatch_lines(warning_output)
+
+
+def test_recursion_source_decode(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_something():
+ pass
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ python_files = *.py
+ """
+ )
+ result = pytester.runpytest("--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ " ",
+ ]
+ )
+
+
+def test_AssertionError_message(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_hello():
+ x,y = 1,2
+ assert 0, (x,y)
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ """
+ *def test_hello*
+ *assert 0, (x,y)*
+ *AssertionError: (1, 2)*
+ """
+ )
+
+
+def test_diff_newline_at_end(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ r"""
+ def test_diff():
+ assert 'asdf' == 'asdf\n'
+ """
+ )
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ r"""
+ *assert 'asdf' == 'asdf\n'
+ * - asdf
+ * ? -
+ * + asdf
+ """
+ )
+
+
+@pytest.mark.filterwarnings("default")
+def test_assert_tuple_warning(pytester: Pytester) -> None:
+ msg = "assertion is always true"
+ pytester.makepyfile(
+ """
+ def test_tuple():
+ assert(False, 'you shall not pass')
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines([f"*test_assert_tuple_warning.py:2:*{msg}*"])
+
+ # tuples with size != 2 should not trigger the warning
+ pytester.makepyfile(
+ """
+ def test_tuple():
+ assert ()
+ """
+ )
+ result = pytester.runpytest()
+ assert msg not in result.stdout.str()
+
+
+def test_assert_indirect_tuple_no_warning(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_tuple():
+ tpl = ('foo', 'bar')
+ assert tpl
+ """
+ )
+ result = pytester.runpytest()
+ output = "\n".join(result.stdout.lines)
+ assert "WR1" not in output
+
+
+def test_assert_with_unicode(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """\
+ def test_unicode():
+ assert '유니코드' == 'Unicode'
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*AssertionError*"])
+
+
+def test_raise_unprintable_assertion_error(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ r"""
+ def test_raise_assertion_error():
+ raise AssertionError('\xff')
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [r"> raise AssertionError('\xff')", "E AssertionError: *"]
+ )
+
+
+def test_raise_assertion_error_raising_repr(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ class RaisingRepr(object):
+ def __repr__(self):
+ raise Exception()
+ def test_raising_repr():
+ raise AssertionError(RaisingRepr())
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["E AssertionError: "])
+
+
+def test_issue_1944(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def f():
+ return
+
+ assert f() == 10
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 error*"])
+ assert (
+ "AttributeError: 'Module' object has no attribute '_obj'"
+ not in result.stdout.str()
+ )
+
+
+def test_exit_from_assertrepr_compare(monkeypatch) -> None:
+ def raise_exit(obj):
+ outcomes.exit("Quitting debugger")
+
+ monkeypatch.setattr(util, "istext", raise_exit)
+
+ with pytest.raises(outcomes.Exit, match="Quitting debugger"):
+ callequal(1, 1)
+
+
+def test_assertion_location_with_coverage(pytester: Pytester) -> None:
+ """This used to report the wrong location when run with coverage (#5754)."""
+ p = pytester.makepyfile(
+ """
+ def test():
+ assert False, 1
+ assert False, 2
+ """
+ )
+ result = pytester.runpytest(str(p))
+ result.stdout.fnmatch_lines(
+ [
+ "> assert False, 1",
+ "E AssertionError: 1",
+ "E assert False",
+ "*= 1 failed in*",
+ ]
+ )
+
+
+def test_reprcompare_verbose_long() -> None:
+ a = {f"v{i}": i for i in range(11)}
+ b = a.copy()
+ b["v2"] += 10
+ lines = callop("==", a, b, verbose=2)
+ assert lines is not None
+ assert lines[0] == (
+ "{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4, 'v5': 5, "
+ "'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}"
+ " == "
+ "{'v0': 0, 'v1': 1, 'v2': 12, 'v3': 3, 'v4': 4, 'v5': 5, "
+ "'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}"
+ )
+
+
+@pytest.mark.parametrize("enable_colors", [True, False])
+@pytest.mark.parametrize(
+ ("test_code", "expected_lines"),
+ (
+ (
+ """
+ def test():
+ assert [0, 1] == [0, 2]
+ """,
+ [
+ "{bold}{red}E At index 1 diff: {reset}{number}1{hl-reset}{endline} != {reset}{number}2*",
+ "{bold}{red}E {light-red}- 2,{hl-reset}{endline}{reset}",
+ "{bold}{red}E {light-green}+ 1,{hl-reset}{endline}{reset}",
+ ],
+ ),
+ (
+ """
+ def test():
+ assert {f"number-is-{i}": i for i in range(1, 6)} == {
+ f"number-is-{i}": i for i in range(5)
+ }
+ """,
+ [
+ "{bold}{red}E Common items:{reset}",
+ "{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-1{hl-reset}{str}'{hl-reset}: {number}1*",
+ "{bold}{red}E Left contains 1 more item:{reset}",
+ "{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-5{hl-reset}{str}'{hl-reset}: {number}5*",
+ "{bold}{red}E Right contains 1 more item:{reset}",
+ "{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-0{hl-reset}{str}'{hl-reset}: {number}0*",
+ "{bold}{red}E {reset}{light-gray} {hl-reset} {{{endline}{reset}",
+ "{bold}{red}E {light-gray} {hl-reset} 'number-is-1': 1,{endline}{reset}",
+ "{bold}{red}E {light-green}+ 'number-is-5': 5,{hl-reset}{endline}{reset}",
+ ],
+ ),
+ (
+ """
+ def test():
+ assert "abcd" == "abce"
+ """,
+ [
+ "{bold}{red}E {reset}{light-red}- abce{hl-reset}{endline}{reset}",
+ "{bold}{red}E {light-green}+ abcd{hl-reset}{endline}{reset}",
+ ],
+ ),
+ ),
+)
+def test_comparisons_handle_colors(
+ pytester: Pytester, color_mapping, enable_colors, test_code, expected_lines
+) -> None:
+ p = pytester.makepyfile(test_code)
+ result = pytester.runpytest(
+ f"--color={'yes' if enable_colors else 'no'}", "-vv", str(p)
+ )
+ formatter = (
+ color_mapping.format_for_fnmatch
+ if enable_colors
+ else color_mapping.strip_colors
+ )
+
+ result.stdout.fnmatch_lines(formatter(expected_lines), consecutive=False)
+
+
+def test_fine_grained_assertion_verbosity(pytester: Pytester):
+ long_text = "Lorem ipsum dolor sit amet " * 10
+ p = pytester.makepyfile(
+ f"""
+ def test_ok():
+ pass
+
+
+ def test_words_fail():
+ fruits1 = ["banana", "apple", "grapes", "melon", "kiwi"]
+ fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
+ assert fruits1 == fruits2
+
+
+ def test_numbers_fail():
+ number_to_text1 = {{str(x): x for x in range(5)}}
+ number_to_text2 = {{str(x * 10): x * 10 for x in range(5)}}
+ assert number_to_text1 == number_to_text2
+
+
+ def test_long_text_fail():
+ long_text = "{long_text}"
+ assert "hello world" in long_text
+ """
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ verbosity_assertions = 2
+ """
+ )
+ result = pytester.runpytest(p)
+
+ result.stdout.fnmatch_lines(
+ [
+ f"{p.name} .FFF [100%]",
+ "E At index 2 diff: 'grapes' != 'orange'",
+ "E Full diff:",
+ "E [",
+ "E 'banana',",
+ "E 'apple',",
+ "E - 'orange',",
+ "E ? ^ ^^",
+ "E + 'grapes',",
+ "E ? ^ ^ +",
+ "E 'melon',",
+ "E 'kiwi',",
+ "E ]",
+ "E Full diff:",
+ "E {",
+ "E '0': 0,",
+ "E - '10': 10,",
+ "E ? - -",
+ "E + '1': 1,",
+ "E - '20': 20,",
+ "E ? - -",
+ "E + '2': 2,",
+ "E - '30': 30,",
+ "E ? - -",
+ "E + '3': 3,",
+ "E - '40': 40,",
+ "E ? - -",
+ "E + '4': 4,",
+ "E }",
+ f"E AssertionError: assert 'hello world' in '{long_text}'",
+ ]
+ )
+
+
+def test_full_output_vvv(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ r"""
+ def crash_helper(m):
+ assert 1 == 2
+ def test_vvv():
+ crash_helper(500 * "a")
+ """
+ )
+ result = pytester.runpytest("")
+ # without -vvv, the passed args are truncated
+ expected_non_vvv_arg_line = "m = 'aaaaaaaaaaaaaaa*..aaaaaaaaaaaa*"
+ result.stdout.fnmatch_lines(
+ [
+ expected_non_vvv_arg_line,
+ "test_full_output_vvv.py:2: AssertionError",
+ ],
+ )
+ # double check that the untruncated part is not in the output
+ expected_vvv_arg_line = "m = '{}'".format(500 * "a")
+ result.stdout.no_fnmatch_line(expected_vvv_arg_line)
+
+ # but with "-vvv" the args are not truncated
+ result = pytester.runpytest("-vvv")
+ result.stdout.fnmatch_lines(
+ [
+ expected_vvv_arg_line,
+ "test_full_output_vvv.py:2: AssertionError",
+ ]
+ )
+ result.stdout.no_fnmatch_line(expected_non_vvv_arg_line)
+
+
+def test_dict_extra_items_preserve_insertion_order(pytester: Pytester) -> None:
+ """Assertion output of dict diff shows keys in insertion order (#13503)."""
+ pytester.makepyfile(
+ test_order="""
+ def test_order():
+ a = {
+ "b": 2,
+ "a": 1,
+ "d": 4,
+ "e": 5,
+ "c": 3,
+ }
+ assert a == {}
+ """
+ )
+
+ result = pytester.runpytest("-vv")
+ result.stdout.fnmatch_lines(
+ [
+ "*Left contains 5 more items:*",
+ "*Full diff:",
+ "* + *'b': 2,",
+ "* + *'a': 1,",
+ "* + *'d': 4,",
+ "* + *'e': 5,",
+ "* + *'c': 3,",
+ "test_order.py:*: AssertionError",
+ ]
+ )
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_assertrewrite.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_assertrewrite.py
new file mode 100644
index 0000000000000000000000000000000000000000..926643544703f9ea9d98be0c90669429d329a20f
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_assertrewrite.py
@@ -0,0 +1,2406 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import ast
+from collections.abc import Generator
+from collections.abc import Mapping
+import dis
+import errno
+from functools import partial
+import glob
+import importlib
+import inspect
+import marshal
+import os
+from pathlib import Path
+import py_compile
+import re
+import stat
+import sys
+import textwrap
+from typing import cast
+from unittest import mock
+import zipfile
+
+import _pytest._code
+from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
+from _pytest.assertion import util
+from _pytest.assertion.rewrite import _get_assertion_exprs
+from _pytest.assertion.rewrite import _get_maxsize_for_saferepr
+from _pytest.assertion.rewrite import _saferepr
+from _pytest.assertion.rewrite import AssertionRewritingHook
+from _pytest.assertion.rewrite import get_cache_dir
+from _pytest.assertion.rewrite import PYC_TAIL
+from _pytest.assertion.rewrite import PYTEST_TAG
+from _pytest.assertion.rewrite import rewrite_asserts
+from _pytest.config import Config
+from _pytest.config import ExitCode
+from _pytest.pathlib import make_numbered_dir
+from _pytest.pytester import Pytester
+import pytest
+
+
+def rewrite(src: str) -> ast.Module:
+ tree = ast.parse(src)
+ rewrite_asserts(tree, src.encode())
+ return tree
+
+
+def getmsg(
+ f, extra_ns: Mapping[str, object] | None = None, *, must_pass: bool = False
+) -> str | None:
+ """Rewrite the assertions in f, run it, and get the failure message."""
+ src = "\n".join(_pytest._code.Code.from_function(f).source().lines)
+ mod = rewrite(src)
+ code = compile(mod, "", "exec")
+ ns: dict[str, object] = {}
+ if extra_ns is not None:
+ ns.update(extra_ns)
+ exec(code, ns)
+ func = ns[f.__name__]
+ try:
+ func() # type: ignore[operator]
+ except AssertionError:
+ if must_pass:
+ pytest.fail("shouldn't have raised")
+ s = str(sys.exc_info()[1])
+ if not s.startswith("assert"):
+ return "AssertionError: " + s
+ return s
+ else:
+ if not must_pass:
+ pytest.fail("function didn't raise at all")
+ return None
+
+
+class TestAssertionRewrite:
+ def test_place_initial_imports(self) -> None:
+ s = """'Doc string'\nother = stuff"""
+ m = rewrite(s)
+ assert isinstance(m.body[0], ast.Expr)
+ for imp in m.body[1:3]:
+ assert isinstance(imp, ast.Import)
+ assert imp.lineno == 2
+ assert imp.col_offset == 0
+ assert isinstance(m.body[3], ast.Assign)
+ s = """from __future__ import division\nother_stuff"""
+ m = rewrite(s)
+ assert isinstance(m.body[0], ast.ImportFrom)
+ for imp in m.body[1:3]:
+ assert isinstance(imp, ast.Import)
+ assert imp.lineno == 2
+ assert imp.col_offset == 0
+ assert isinstance(m.body[3], ast.Expr)
+ s = """'doc string'\nfrom __future__ import division"""
+ m = rewrite(s)
+ assert isinstance(m.body[0], ast.Expr)
+ assert isinstance(m.body[1], ast.ImportFrom)
+ for imp in m.body[2:4]:
+ assert isinstance(imp, ast.Import)
+ assert imp.lineno == 2
+ assert imp.col_offset == 0
+ s = """'doc string'\nfrom __future__ import division\nother"""
+ m = rewrite(s)
+ assert isinstance(m.body[0], ast.Expr)
+ assert isinstance(m.body[1], ast.ImportFrom)
+ for imp in m.body[2:4]:
+ assert isinstance(imp, ast.Import)
+ assert imp.lineno == 3
+ assert imp.col_offset == 0
+ assert isinstance(m.body[4], ast.Expr)
+ s = """from . import relative\nother_stuff"""
+ m = rewrite(s)
+ for imp in m.body[:2]:
+ assert isinstance(imp, ast.Import)
+ assert imp.lineno == 1
+ assert imp.col_offset == 0
+ assert isinstance(m.body[3], ast.Expr)
+
+ def test_location_is_set(self) -> None:
+ s = textwrap.dedent(
+ """
+
+ assert False, (
+
+ "Ouch"
+ )
+
+ """
+ )
+ m = rewrite(s)
+ for node in m.body:
+ if isinstance(node, ast.Import):
+ continue
+ for n in [node, *ast.iter_child_nodes(node)]:
+ assert isinstance(n, ast.stmt | ast.expr)
+ for location in [
+ (n.lineno, n.col_offset),
+ (n.end_lineno, n.end_col_offset),
+ ]:
+ assert (3, 0) <= location <= (6, 3)
+
+ def test_positions_are_preserved(self) -> None:
+ """Ensure AST positions are preserved during rewriting (#12818)."""
+
+ def preserved(code: str) -> None:
+ s = textwrap.dedent(code)
+ locations = []
+
+ def loc(msg: str | None = None) -> None:
+ frame = inspect.currentframe()
+ assert frame
+ frame = frame.f_back
+ assert frame
+ frame = frame.f_back
+ assert frame
+
+ offset = frame.f_lasti
+
+ instructions = {i.offset: i for i in dis.get_instructions(frame.f_code)}
+
+ # skip CACHE instructions
+ while offset not in instructions and offset >= 0:
+ offset -= 1
+
+ instruction = instructions[offset]
+ if sys.version_info >= (3, 11):
+ position = instruction.positions
+ else:
+ position = instruction.starts_line
+
+ locations.append((msg, instruction.opname, position))
+
+ globals = {"loc": loc}
+
+ m = rewrite(s)
+ mod = compile(m, "", "exec")
+ exec(mod, globals, globals)
+ transformed_locations = locations
+ locations = []
+
+ mod = compile(s, "", "exec")
+ exec(mod, globals, globals)
+ original_locations = locations
+
+ assert len(original_locations) > 0
+ assert original_locations == transformed_locations
+
+ preserved("""
+ def f():
+ loc()
+ return 8
+
+ assert f() in [8]
+ assert (f()
+ in
+ [8])
+ """)
+
+ preserved("""
+ class T:
+ def __init__(self):
+ loc("init")
+ def __getitem__(self,index):
+ loc("getitem")
+ return index
+
+ assert T()[5] == 5
+ assert (T
+ ()
+ [5]
+ ==
+ 5)
+ """)
+
+ for name, op in [
+ ("pos", "+"),
+ ("neg", "-"),
+ ("invert", "~"),
+ ]:
+ preserved(f"""
+ class T:
+ def __{name}__(self):
+ loc("{name}")
+ return "{name}"
+
+ assert {op}T() == "{name}"
+ assert ({op}
+ T
+ ()
+ ==
+ "{name}")
+ """)
+
+ for name, op in [
+ ("add", "+"),
+ ("sub", "-"),
+ ("mul", "*"),
+ ("truediv", "/"),
+ ("floordiv", "//"),
+ ("mod", "%"),
+ ("pow", "**"),
+ ("lshift", "<<"),
+ ("rshift", ">>"),
+ ("or", "|"),
+ ("xor", "^"),
+ ("and", "&"),
+ ("matmul", "@"),
+ ]:
+ preserved(f"""
+ class T:
+ def __{name}__(self,other):
+ loc("{name}")
+ return other
+
+ def __r{name}__(self,other):
+ loc("r{name}")
+ return other
+
+ assert T() {op} 2 == 2
+ assert 2 {op} T() == 2
+
+ assert (T
+ ()
+ {op}
+ 2
+ ==
+ 2)
+
+ assert (2
+ {op}
+ T
+ ()
+ ==
+ 2)
+ """)
+
+ for name, op in [
+ ("eq", "=="),
+ ("ne", "!="),
+ ("lt", "<"),
+ ("le", "<="),
+ ("gt", ">"),
+ ("ge", ">="),
+ ]:
+ preserved(f"""
+ class T:
+ def __{name}__(self,other):
+ loc()
+ return True
+
+ assert T() {op} 5
+ assert (T
+ ()
+ {op}
+ 5)
+ """)
+
+ for name, op in [
+ ("eq", "=="),
+ ("ne", "!="),
+ ("lt", ">"),
+ ("le", ">="),
+ ("gt", "<"),
+ ("ge", "<="),
+ ("contains", "in"),
+ ]:
+ preserved(f"""
+ class T:
+ def __{name}__(self,other):
+ loc()
+ return True
+
+ assert 5 {op} T()
+ assert (5
+ {op}
+ T
+ ())
+ """)
+
+ preserved("""
+ def func(value):
+ loc("func")
+ return value
+
+ class T:
+ def __iter__(self):
+ loc("iter")
+ return iter([5])
+
+ assert func(*T()) == 5
+ """)
+
+ preserved("""
+ class T:
+ def __getattr__(self,name):
+ loc()
+ return name
+
+ assert T().attr == "attr"
+ """)
+
+ def test_dont_rewrite(self) -> None:
+ s = """'PYTEST_DONT_REWRITE'\nassert 14"""
+ m = rewrite(s)
+ assert len(m.body) == 2
+ assert isinstance(m.body[1], ast.Assert)
+ assert m.body[1].msg is None
+
+ def test_dont_rewrite_plugin(self, pytester: Pytester) -> None:
+ contents = {
+ "conftest.py": "pytest_plugins = 'plugin'; import plugin",
+ "plugin.py": "'PYTEST_DONT_REWRITE'",
+ "test_foo.py": "def test_foo(): pass",
+ }
+ pytester.makepyfile(**contents)
+ result = pytester.runpytest_subprocess()
+ assert "warning" not in "".join(result.outlines)
+
+ def test_rewrites_plugin_as_a_package(self, pytester: Pytester) -> None:
+ pkgdir = pytester.mkpydir("plugin")
+ pkgdir.joinpath("__init__.py").write_text(
+ "import pytest\n"
+ "@pytest.fixture\n"
+ "def special_asserter():\n"
+ " def special_assert(x, y):\n"
+ " assert x == y\n"
+ " return special_assert\n",
+ encoding="utf-8",
+ )
+ pytester.makeconftest('pytest_plugins = ["plugin"]')
+ pytester.makepyfile("def test(special_asserter): special_asserter(1, 2)\n")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*assert 1 == 2*"])
+
+ def test_honors_pep_235(self, pytester: Pytester, monkeypatch) -> None:
+ # note: couldn't make it fail on macos with a single `sys.path` entry
+ # note: these modules are named `test_*` to trigger rewriting
+ pytester.makepyfile(test_y="x = 1")
+ xdir = pytester.mkdir("x")
+ pytester.mkpydir(str(xdir.joinpath("test_Y")))
+ xdir.joinpath("test_Y").joinpath("__init__.py").write_text(
+ "x = 2", encoding="utf-8"
+ )
+ pytester.makepyfile(
+ "import test_y\n"
+ "import test_Y\n"
+ "def test():\n"
+ " assert test_y.x == 1\n"
+ " assert test_Y.x == 2\n"
+ )
+ monkeypatch.syspath_prepend(str(xdir))
+ pytester.runpytest().assert_outcomes(passed=1)
+
+ def test_name(self, request) -> None:
+ def f1() -> None:
+ assert False
+
+ assert getmsg(f1) == "assert False"
+
+ def f2() -> None:
+ f = False
+ assert f
+
+ assert getmsg(f2) == "assert False"
+
+ def f3() -> None:
+ assert a_global # type: ignore[name-defined] # noqa: F821
+
+ assert getmsg(f3, {"a_global": False}) == "assert False"
+
+ def f4() -> None:
+ assert sys == 42 # type: ignore[comparison-overlap]
+
+ msg = getmsg(f4, {"sys": sys})
+ assert msg == "assert sys == 42"
+
+ def f5() -> None:
+ assert cls == 42 # type: ignore[name-defined] # noqa: F821
+
+ class X:
+ pass
+
+ msg = getmsg(f5, {"cls": X})
+ assert msg is not None
+ lines = msg.splitlines()
+ assert lines == ["assert cls == 42"]
+
+ def test_assertrepr_compare_same_width(self, request) -> None:
+ """Should use same width/truncation with same initial width."""
+
+ def f() -> None:
+ assert "1234567890" * 5 + "A" == "1234567890" * 5 + "B"
+
+ msg = getmsg(f)
+ assert msg is not None
+ line = msg.splitlines()[0]
+ if request.config.getoption("verbose") > 1:
+ assert line == (
+ "assert '12345678901234567890123456789012345678901234567890A' "
+ "== '12345678901234567890123456789012345678901234567890B'"
+ )
+ else:
+ assert line == (
+ "assert '123456789012...901234567890A' "
+ "== '123456789012...901234567890B'"
+ )
+
+ def test_dont_rewrite_if_hasattr_fails(self, request) -> None:
+ class Y:
+ """A class whose getattr fails, but not with `AttributeError`."""
+
+ def __getattr__(self, attribute_name):
+ raise KeyError()
+
+ def __repr__(self) -> str:
+ return "Y"
+
+ def __init__(self) -> None:
+ self.foo = 3
+
+ def f() -> None:
+ assert cls().foo == 2 # type: ignore[name-defined] # noqa: F821
+
+ # XXX: looks like the "where" should also be there in verbose mode?!
+ msg = getmsg(f, {"cls": Y})
+ assert msg is not None
+ lines = msg.splitlines()
+ assert lines == [
+ "assert 3 == 2",
+ " + where 3 = Y.foo",
+ " + where Y = cls()",
+ ]
+
+ def test_assert_already_has_message(self) -> None:
+ def f():
+ assert False, "something bad!"
+
+ assert getmsg(f) == "AssertionError: something bad!\nassert False"
+
+ def test_assertion_message(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_foo():
+ assert 1 == 2, "The failure message"
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(
+ ["*AssertionError*The failure message*", "*assert 1 == 2*"]
+ )
+
+ def test_assertion_message_multiline(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_foo():
+ assert 1 == 2, "A multiline\\nfailure message"
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(
+ ["*AssertionError*A multiline*", "*failure message*", "*assert 1 == 2*"]
+ )
+
+ def test_assertion_message_tuple(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_foo():
+ assert 1 == 2, (1, 2)
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines([f"*AssertionError*{(1, 2)!r}*", "*assert 1 == 2*"])
+
+ def test_assertion_message_expr(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_foo():
+ assert 1 == 2, 1 + 2
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*AssertionError*3*", "*assert 1 == 2*"])
+
+ def test_assertion_message_escape(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_foo():
+ assert 1 == 2, 'To be escaped: %'
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(
+ ["*AssertionError: To be escaped: %", "*assert 1 == 2"]
+ )
+
+ def test_assertion_messages_bytes(self, pytester: Pytester) -> None:
+ pytester.makepyfile("def test_bytes_assertion():\n assert False, b'ohai!'\n")
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*AssertionError: b'ohai!'", "*assert False"])
+
+ def test_assertion_message_verbosity(self, pytester: Pytester) -> None:
+ """
+ Obey verbosity levels when printing the "message" part of assertions, when they are
+ non-strings (#6682).
+ """
+ pytester.makepyfile(
+ """
+ class LongRepr:
+
+ def __repr__(self):
+ return "A" * 500
+
+ def test_assertion_verbosity():
+ assert False, LongRepr()
+ """
+ )
+ # Normal verbosity: assertion message gets abbreviated.
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.re_match_lines(
+ [r".*AssertionError: A+\.\.\.A+$", ".*assert False"]
+ )
+
+ # High-verbosity: do not abbreviate the assertion message.
+ result = pytester.runpytest("-vv")
+ assert result.ret == 1
+ result.stdout.re_match_lines([r".*AssertionError: A+$", ".*assert False"])
+
+ def test_boolop(self) -> None:
+ def f1() -> None:
+ f = g = False
+ assert f and g
+
+ assert getmsg(f1) == "assert (False)"
+
+ def f2() -> None:
+ f = True
+ g = False
+ assert f and g
+
+ assert getmsg(f2) == "assert (True and False)"
+
+ def f3() -> None:
+ f = False
+ g = True
+ assert f and g
+
+ assert getmsg(f3) == "assert (False)"
+
+ def f4() -> None:
+ f = g = False
+ assert f or g
+
+ assert getmsg(f4) == "assert (False or False)"
+
+ def f5() -> None:
+ f = g = False
+ assert not f and not g
+
+ getmsg(f5, must_pass=True)
+
+ def x() -> bool:
+ return False
+
+ def f6() -> None:
+ assert x() and x()
+
+ assert (
+ getmsg(f6, {"x": x})
+ == """assert (False)
+ + where False = x()"""
+ )
+
+ def f7() -> None:
+ assert False or x()
+
+ assert (
+ getmsg(f7, {"x": x})
+ == """assert (False or False)
+ + where False = x()"""
+ )
+
+ def f8() -> None:
+ assert 1 in {} and 2 in {}
+
+ assert getmsg(f8) == "assert (1 in {})"
+
+ def f9() -> None:
+ x = 1
+ y = 2
+ assert x in {1: None} and y in {}
+
+ assert getmsg(f9) == "assert (1 in {1: None} and 2 in {})"
+
+ def f10() -> None:
+ f = True
+ g = False
+ assert f or g
+
+ getmsg(f10, must_pass=True)
+
+ def f11() -> None:
+ f = g = h = lambda: True
+ assert f() and g() and h()
+
+ getmsg(f11, must_pass=True)
+
+ def test_short_circuit_evaluation(self) -> None:
+ def f1() -> None:
+ assert True or explode # type: ignore[name-defined,unreachable] # noqa: F821
+
+ getmsg(f1, must_pass=True)
+
+ def f2() -> None:
+ x = 1
+ assert x == 1 or x == 2 # noqa: PLR1714
+
+ getmsg(f2, must_pass=True)
+
+ def test_unary_op(self) -> None:
+ def f1() -> None:
+ x = True
+ assert not x
+
+ assert getmsg(f1) == "assert not True"
+
+ def f2() -> None:
+ x = 0
+ assert ~x + 1
+
+ assert getmsg(f2) == "assert (~0 + 1)"
+
+ def f3() -> None:
+ x = 3
+ assert -x + x
+
+ assert getmsg(f3) == "assert (-3 + 3)"
+
+ def f4() -> None:
+ x = 0
+ assert +x + x
+
+ assert getmsg(f4) == "assert (+0 + 0)"
+
+ def test_binary_op(self) -> None:
+ def f1() -> None:
+ x = 1
+ y = -1
+ assert x + y
+
+ assert getmsg(f1) == "assert (1 + -1)"
+
+ def f2() -> None:
+ assert not 5 % 4
+
+ assert getmsg(f2) == "assert not (5 % 4)"
+
+ def test_boolop_percent(self) -> None:
+ def f1() -> None:
+ assert 3 % 2 and False
+
+ assert getmsg(f1) == "assert ((3 % 2) and False)"
+
+ def f2() -> None:
+ assert False or 4 % 2
+
+ assert getmsg(f2) == "assert (False or (4 % 2))"
+
+ def test_at_operator_issue1290(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ class Matrix(object):
+ def __init__(self, num):
+ self.num = num
+ def __matmul__(self, other):
+ return self.num * other.num
+
+ def test_multmat_operator():
+ assert Matrix(2) @ Matrix(3) == 6"""
+ )
+ pytester.runpytest().assert_outcomes(passed=1)
+
+ def test_starred_with_side_effect(self, pytester: Pytester) -> None:
+ """See #4412"""
+ pytester.makepyfile(
+ """\
+ def test():
+ f = lambda x: x
+ x = iter([1, 2, 3])
+ assert 2 * next(x) == f(*[next(x)])
+ """
+ )
+ pytester.runpytest().assert_outcomes(passed=1)
+
+ def test_call(self) -> None:
+ def g(a=42, *args, **kwargs) -> bool:
+ return False
+
+ ns = {"g": g}
+
+ def f1() -> None:
+ assert g()
+
+ assert (
+ getmsg(f1, ns)
+ == """assert False
+ + where False = g()"""
+ )
+
+ def f2() -> None:
+ assert g(1)
+
+ assert (
+ getmsg(f2, ns)
+ == """assert False
+ + where False = g(1)"""
+ )
+
+ def f3() -> None:
+ assert g(1, 2)
+
+ assert (
+ getmsg(f3, ns)
+ == """assert False
+ + where False = g(1, 2)"""
+ )
+
+ def f4() -> None:
+ assert g(1, g=42)
+
+ assert (
+ getmsg(f4, ns)
+ == """assert False
+ + where False = g(1, g=42)"""
+ )
+
+ def f5() -> None:
+ assert g(1, 3, g=23)
+
+ assert (
+ getmsg(f5, ns)
+ == """assert False
+ + where False = g(1, 3, g=23)"""
+ )
+
+ def f6() -> None:
+ seq = [1, 2, 3]
+ assert g(*seq)
+
+ assert (
+ getmsg(f6, ns)
+ == """assert False
+ + where False = g(*[1, 2, 3])"""
+ )
+
+ def f7() -> None:
+ x = "a"
+ assert g(**{x: 2})
+
+ assert (
+ getmsg(f7, ns)
+ == """assert False
+ + where False = g(**{'a': 2})"""
+ )
+
+ def test_attribute(self) -> None:
+ class X:
+ g = 3
+
+ ns = {"x": X}
+
+ def f1() -> None:
+ assert not x.g # type: ignore[name-defined] # noqa: F821
+
+ assert (
+ getmsg(f1, ns)
+ == """assert not 3
+ + where 3 = x.g"""
+ )
+
+ def f2() -> None:
+ x.a = False # type: ignore[name-defined] # noqa: F821
+ assert x.a # type: ignore[name-defined] # noqa: F821
+
+ assert (
+ getmsg(f2, ns)
+ == """assert False
+ + where False = x.a"""
+ )
+
+ def test_comparisons(self) -> None:
+ def f1() -> None:
+ a, b = range(2)
+ assert b < a
+
+ assert getmsg(f1) == """assert 1 < 0"""
+
+ def f2() -> None:
+ a, b, c = range(3)
+ assert a > b > c
+
+ assert getmsg(f2) == """assert 0 > 1"""
+
+ def f3() -> None:
+ a, b, c = range(3)
+ assert a < b > c
+
+ assert getmsg(f3) == """assert 1 > 2"""
+
+ def f4() -> None:
+ a, b, c = range(3)
+ assert a < b <= c
+
+ getmsg(f4, must_pass=True)
+
+ def f5() -> None:
+ a, b, c = range(3)
+ assert a < b
+ assert b < c
+
+ getmsg(f5, must_pass=True)
+
+ def test_len(self, request) -> None:
+ def f():
+ values = list(range(10))
+ assert len(values) == 11
+
+ msg = getmsg(f)
+ assert msg == "assert 10 == 11\n + where 10 = len([0, 1, 2, 3, 4, 5, ...])"
+
+ def test_custom_reprcompare(self, monkeypatch) -> None:
+ def my_reprcompare1(op, left, right) -> str:
+ return "42"
+
+ monkeypatch.setattr(util, "_reprcompare", my_reprcompare1)
+
+ def f1() -> None:
+ assert 42 < 3
+
+ assert getmsg(f1) == "assert 42"
+
+ def my_reprcompare2(op, left, right) -> str:
+ return f"{left} {op} {right}"
+
+ monkeypatch.setattr(util, "_reprcompare", my_reprcompare2)
+
+ def f2() -> None:
+ assert 1 < 3 < 5 <= 4 < 7
+
+ assert getmsg(f2) == "assert 5 <= 4"
+
+ def test_assert_raising__bool__in_comparison(self) -> None:
+ def f() -> None:
+ class A:
+ def __bool__(self):
+ raise ValueError(42)
+
+ def __lt__(self, other):
+ return A()
+
+ def __repr__(self):
+ return ""
+
+ def myany(x) -> bool:
+ return False
+
+ assert myany(A() < 0)
+
+ msg = getmsg(f)
+ assert msg is not None
+ assert " < 0" in msg
+
+ def test_assert_handling_raise_in__iter__(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """\
+ class A:
+ def __iter__(self):
+ raise ValueError()
+
+ def __eq__(self, o: object) -> bool:
+ return self is o
+
+ def __repr__(self):
+ return ""
+
+ assert A() == A()
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*E*assert == "])
+
+ def test_formatchar(self) -> None:
+ def f() -> None:
+ assert "%test" == "test" # type: ignore[comparison-overlap]
+
+ msg = getmsg(f)
+ assert msg is not None
+ assert msg.startswith("assert '%test' == 'test'")
+
+ def test_custom_repr(self, request) -> None:
+ def f() -> None:
+ class Foo:
+ a = 1
+
+ def __repr__(self):
+ return "\n{ \n~ \n}"
+
+ f = Foo()
+ assert 0 == f.a
+
+ msg = getmsg(f)
+ assert msg is not None
+ lines = util._format_lines([msg])
+ assert lines == ["assert 0 == 1\n + where 1 = \\n{ \\n~ \\n}.a"]
+
+ def test_custom_repr_non_ascii(self) -> None:
+ def f() -> None:
+ class A:
+ name = "ä"
+
+ def __repr__(self):
+ return self.name.encode("UTF-8") # only legal in python2
+
+ a = A()
+ assert not a.name
+
+ msg = getmsg(f)
+ assert msg is not None
+ assert "UnicodeDecodeError" not in msg
+ assert "UnicodeEncodeError" not in msg
+
+ def test_assert_fixture(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """\
+ import pytest
+ @pytest.fixture
+ def fixt():
+ return 42
+
+ def test_something(): # missing "fixt" argument
+ assert fixt == 42
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ ["*assert )> == 42*"]
+ )
+
+
+class TestRewriteOnImport:
+ def test_pycache_is_a_file(self, pytester: Pytester) -> None:
+ pytester.path.joinpath("__pycache__").write_text("Hello", encoding="utf-8")
+ pytester.makepyfile(
+ """
+ def test_rewritten():
+ assert "@py_builtins" in globals()"""
+ )
+ assert pytester.runpytest().ret == 0
+
+ def test_pycache_is_readonly(self, pytester: Pytester) -> None:
+ cache = pytester.mkdir("__pycache__")
+ old_mode = cache.stat().st_mode
+ cache.chmod(old_mode ^ stat.S_IWRITE)
+ pytester.makepyfile(
+ """
+ def test_rewritten():
+ assert "@py_builtins" in globals()"""
+ )
+ try:
+ assert pytester.runpytest().ret == 0
+ finally:
+ cache.chmod(old_mode)
+
+ def test_zipfile(self, pytester: Pytester) -> None:
+ z = pytester.path.joinpath("myzip.zip")
+ z_fn = str(z)
+ f = zipfile.ZipFile(z_fn, "w")
+ try:
+ f.writestr("test_gum/__init__.py", "")
+ f.writestr("test_gum/test_lizard.py", "")
+ finally:
+ f.close()
+ z.chmod(256)
+ pytester.makepyfile(
+ f"""
+ import sys
+ sys.path.append({z_fn!r})
+ import test_gum.test_lizard"""
+ )
+ assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED
+
+ def test_load_resource_via_files_with_rewrite(self, pytester: Pytester) -> None:
+ example = pytester.path.joinpath("demo") / "example"
+ init = pytester.path.joinpath("demo") / "__init__.py"
+ pytester.makepyfile(
+ **{
+ "demo/__init__.py": """
+ from importlib.resources import files
+
+ def load():
+ return files(__name__)
+ """,
+ "test_load": f"""
+ pytest_plugins = ["demo"]
+
+ def test_load():
+ from demo import load
+ found = {{str(i) for i in load().iterdir() if i.name != "__pycache__"}}
+ assert found == {{{str(example)!r}, {str(init)!r}}}
+ """,
+ }
+ )
+ example.mkdir()
+
+ assert pytester.runpytest("-vv").ret == ExitCode.OK
+
+ def test_readonly(self, pytester: Pytester) -> None:
+ sub = pytester.mkdir("testing")
+ sub.joinpath("test_readonly.py").write_bytes(
+ b"""
+def test_rewritten():
+ assert "@py_builtins" in globals()
+ """,
+ )
+ old_mode = sub.stat().st_mode
+ sub.chmod(320)
+ try:
+ assert pytester.runpytest().ret == 0
+ finally:
+ sub.chmod(old_mode)
+
+ def test_dont_write_bytecode(self, pytester: Pytester, monkeypatch) -> None:
+ monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
+
+ pytester.makepyfile(
+ """
+ import os
+ def test_no_bytecode():
+ assert "__pycache__" in __cached__
+ assert not os.path.exists(__cached__)
+ assert not os.path.exists(os.path.dirname(__cached__))"""
+ )
+ monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1")
+ assert pytester.runpytest_subprocess().ret == 0
+
+ def test_orphaned_pyc_file(self, pytester: Pytester, monkeypatch) -> None:
+ monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
+ monkeypatch.setattr(sys, "pycache_prefix", None, raising=False)
+
+ pytester.makepyfile(
+ """
+ import orphan
+ def test_it():
+ assert orphan.value == 17
+ """
+ )
+ pytester.makepyfile(
+ orphan="""
+ value = 17
+ """
+ )
+ py_compile.compile("orphan.py")
+ os.remove("orphan.py")
+
+ # Python 3 puts the .pyc files in a __pycache__ directory, and will
+ # not import from there without source. It will import a .pyc from
+ # the source location though.
+ if not os.path.exists("orphan.pyc"):
+ pycs = glob.glob("__pycache__/orphan.*.pyc")
+ assert len(pycs) == 1
+ os.rename(pycs[0], "orphan.pyc")
+
+ assert pytester.runpytest().ret == 0
+
+ def test_cached_pyc_includes_pytest_version(
+ self, pytester: Pytester, monkeypatch
+ ) -> None:
+ """Avoid stale caches (#1671)"""
+ monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
+ monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
+ pytester.makepyfile(
+ test_foo="""
+ def test_foo():
+ assert True
+ """
+ )
+ result = pytester.runpytest_subprocess()
+ assert result.ret == 0
+ found_names = glob.glob(f"__pycache__/*-pytest-{pytest.__version__}.pyc")
+ assert found_names, "pyc with expected tag not found in names: {}".format(
+ glob.glob("__pycache__/*.pyc")
+ )
+
+ @pytest.mark.skipif('"__pypy__" in sys.modules')
+ def test_pyc_vs_pyo(
+ self,
+ pytester: Pytester,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ def test_optimized():
+ "hello"
+ assert test_optimized.__doc__ is None"""
+ )
+ p = make_numbered_dir(root=Path(pytester.path), prefix="runpytest-")
+ tmp = f"--basetemp={p}"
+ with monkeypatch.context() as mp:
+ mp.setenv("PYTHONOPTIMIZE", "2")
+ mp.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
+ mp.delenv("PYTHONPYCACHEPREFIX", raising=False)
+ assert pytester.runpytest_subprocess(tmp).ret == 0
+ tagged = "test_pyc_vs_pyo." + PYTEST_TAG
+ assert tagged + ".pyo" in os.listdir("__pycache__")
+ monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
+ monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
+ assert pytester.runpytest_subprocess(tmp).ret == 1
+ assert tagged + ".pyc" in os.listdir("__pycache__")
+
+ def test_package(self, pytester: Pytester) -> None:
+ pkg = pytester.path.joinpath("pkg")
+ pkg.mkdir()
+ pkg.joinpath("__init__.py")
+ pkg.joinpath("test_blah.py").write_text(
+ """
+def test_rewritten():
+ assert "@py_builtins" in globals()""",
+ encoding="utf-8",
+ )
+ assert pytester.runpytest().ret == 0
+
+ def test_translate_newlines(self, pytester: Pytester) -> None:
+ content = "def test_rewritten():\r\n assert '@py_builtins' in globals()"
+ b = content.encode("utf-8")
+ pytester.path.joinpath("test_newlines.py").write_bytes(b)
+ assert pytester.runpytest().ret == 0
+
+ def test_package_without__init__py(self, pytester: Pytester) -> None:
+ pkg = pytester.mkdir("a_package_without_init_py")
+ pkg.joinpath("module.py").touch()
+ pytester.makepyfile("import a_package_without_init_py.module")
+ assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED
+
+ def test_rewrite_warning(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ pytest.register_assert_rewrite("_pytest")
+ """
+ )
+ # needs to be a subprocess because pytester explicitly disables this warning
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(["*Module already imported*; _pytest"])
+
+ def test_rewrite_warning_ignore(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ pytest.register_assert_rewrite("_pytest")
+ """
+ )
+ # needs to be a subprocess because pytester explicitly disables this warning
+ result = pytester.runpytest_subprocess(
+ "-W",
+ "ignore:Module already imported so cannot be rewritten; _pytest:pytest.PytestAssertRewriteWarning",
+ )
+ # Previously, when the message pattern used to contain an extra `:`, an error was raised.
+ assert not result.stderr.str().strip()
+ result.stdout.no_fnmatch_line("*Module already imported*; _pytest")
+
+ def test_rewrite_module_imported_from_conftest(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import test_rewrite_module_imported
+ """
+ )
+ pytester.makepyfile(
+ test_rewrite_module_imported="""
+ def test_rewritten():
+ assert "@py_builtins" in globals()
+ """
+ )
+ assert pytester.runpytest_subprocess().ret == 0
+
+ def test_remember_rewritten_modules(
+ self, pytestconfig, pytester: Pytester, monkeypatch
+ ) -> None:
+ """`AssertionRewriteHook` should remember rewritten modules so it
+ doesn't give false positives (#2005)."""
+ monkeypatch.syspath_prepend(pytester.path)
+ pytester.makepyfile(test_remember_rewritten_modules="")
+ warnings = []
+ hook = AssertionRewritingHook(pytestconfig)
+ monkeypatch.setattr(
+ hook, "_warn_already_imported", lambda code, msg: warnings.append(msg)
+ )
+ spec = hook.find_spec("test_remember_rewritten_modules")
+ assert spec is not None
+ module = importlib.util.module_from_spec(spec)
+ hook.exec_module(module)
+ hook.mark_rewrite("test_remember_rewritten_modules")
+ hook.mark_rewrite("test_remember_rewritten_modules")
+ assert warnings == []
+
+ def test_rewrite_warning_using_pytest_plugins(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ **{
+ "conftest.py": "pytest_plugins = ['core', 'gui', 'sci']",
+ "core.py": "",
+ "gui.py": "pytest_plugins = ['core', 'sci']",
+ "sci.py": "pytest_plugins = ['core']",
+ "test_rewrite_warning_pytest_plugins.py": "def test(): pass",
+ }
+ )
+ pytester.chdir()
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(["*= 1 passed in *=*"])
+ result.stdout.no_fnmatch_line("*pytest-warning summary*")
+
+ def test_rewrite_warning_using_pytest_plugins_env_var(
+ self, pytester: Pytester, monkeypatch
+ ) -> None:
+ monkeypatch.setenv("PYTEST_PLUGINS", "plugin")
+ pytester.makepyfile(
+ **{
+ "plugin.py": "",
+ "test_rewrite_warning_using_pytest_plugins_env_var.py": """
+ import plugin
+ pytest_plugins = ['plugin']
+ def test():
+ pass
+ """,
+ }
+ )
+ pytester.chdir()
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(["*= 1 passed in *=*"])
+ result.stdout.no_fnmatch_line("*pytest-warning summary*")
+
+
+class TestAssertionRewriteHookDetails:
+ def test_sys_meta_path_munged(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_meta_path():
+ import sys; sys.meta_path = []"""
+ )
+ assert pytester.runpytest().ret == 0
+
+ def test_write_pyc(self, pytester: Pytester, tmp_path) -> None:
+ from _pytest.assertion import AssertionState
+ from _pytest.assertion.rewrite import _write_pyc
+
+ config = pytester.parseconfig()
+ state = AssertionState(config, "rewrite")
+ tmp_path.joinpath("source.py").touch()
+ source_path = str(tmp_path)
+ pycpath = tmp_path.joinpath("pyc")
+ co = compile("1", "f.py", "single")
+ assert _write_pyc(state, co, os.stat(source_path), pycpath)
+
+ with mock.patch.object(os, "replace", side_effect=OSError):
+ assert not _write_pyc(state, co, os.stat(source_path), pycpath)
+
+ def test_resources_provider_for_loader(self, pytester: Pytester) -> None:
+ """
+ Attempts to load resources from a package should succeed normally,
+ even when the AssertionRewriteHook is used to load the modules.
+
+ See #366 for details.
+ """
+ pytest.importorskip("pkg_resources")
+
+ pytester.mkpydir("testpkg")
+ contents = {
+ "testpkg/test_pkg": """
+ import pkg_resources
+
+ import pytest
+ from _pytest.assertion.rewrite import AssertionRewritingHook
+
+ def test_load_resource():
+ assert isinstance(__loader__, AssertionRewritingHook)
+ res = pkg_resources.resource_string(__name__, 'resource.txt')
+ res = res.decode('ascii')
+ assert res == 'Load me please.'
+ """
+ }
+ pytester.makepyfile(**contents)
+ pytester.maketxtfile(**{"testpkg/resource": "Load me please."})
+
+ result = pytester.runpytest_subprocess()
+ result.assert_outcomes(passed=1)
+
+ def test_read_pyc(self, tmp_path: Path) -> None:
+ """
+ Ensure that the `_read_pyc` can properly deal with corrupted pyc files.
+ In those circumstances it should just give up instead of generating
+ an exception that is propagated to the caller.
+ """
+ import py_compile
+
+ from _pytest.assertion.rewrite import _read_pyc
+
+ source = tmp_path / "source.py"
+ pyc = Path(str(source) + "c")
+
+ source.write_text("def test(): pass", encoding="utf-8")
+ py_compile.compile(str(source), str(pyc))
+
+ contents = pyc.read_bytes()
+ strip_bytes = 20 # header is around 16 bytes, strip a little more
+ assert len(contents) > strip_bytes
+ pyc.write_bytes(contents[:strip_bytes])
+
+ assert _read_pyc(source, pyc) is None # no error
+
+ def test_read_pyc_success(self, tmp_path: Path, pytester: Pytester) -> None:
+ """
+ Ensure that the _rewrite_test() -> _write_pyc() produces a pyc file
+ that can be properly read with _read_pyc()
+ """
+ from _pytest.assertion import AssertionState
+ from _pytest.assertion.rewrite import _read_pyc
+ from _pytest.assertion.rewrite import _rewrite_test
+ from _pytest.assertion.rewrite import _write_pyc
+
+ config = pytester.parseconfig()
+ state = AssertionState(config, "rewrite")
+
+ fn = tmp_path / "source.py"
+ pyc = Path(str(fn) + "c")
+
+ fn.write_text("def test(): assert True", encoding="utf-8")
+
+ source_stat, co = _rewrite_test(fn, config)
+ _write_pyc(state, co, source_stat, pyc)
+ assert _read_pyc(fn, pyc, state.trace) is not None
+
+ def test_read_pyc_more_invalid(self, tmp_path: Path) -> None:
+ from _pytest.assertion.rewrite import _read_pyc
+
+ source = tmp_path / "source.py"
+ pyc = tmp_path / "source.pyc"
+
+ source_bytes = b"def test(): pass\n"
+ source.write_bytes(source_bytes)
+
+ magic = importlib.util.MAGIC_NUMBER
+
+ flags = b"\x00\x00\x00\x00"
+
+ mtime = b"\x58\x3c\xb0\x5f"
+ mtime_int = int.from_bytes(mtime, "little")
+ os.utime(source, (mtime_int, mtime_int))
+
+ size = len(source_bytes).to_bytes(4, "little")
+
+ code = marshal.dumps(compile(source_bytes, str(source), "exec"))
+
+ # Good header.
+ pyc.write_bytes(magic + flags + mtime + size + code)
+ assert _read_pyc(source, pyc, print) is not None
+
+ # Too short.
+ pyc.write_bytes(magic + flags + mtime)
+ assert _read_pyc(source, pyc, print) is None
+
+ # Bad magic.
+ pyc.write_bytes(b"\x12\x34\x56\x78" + flags + mtime + size + code)
+ assert _read_pyc(source, pyc, print) is None
+
+ # Unsupported flags.
+ pyc.write_bytes(magic + b"\x00\xff\x00\x00" + mtime + size + code)
+ assert _read_pyc(source, pyc, print) is None
+
+ # Bad mtime.
+ pyc.write_bytes(magic + flags + b"\x58\x3d\xb0\x5f" + size + code)
+ assert _read_pyc(source, pyc, print) is None
+
+ # Bad size.
+ pyc.write_bytes(magic + flags + mtime + b"\x99\x00\x00\x00" + code)
+ assert _read_pyc(source, pyc, print) is None
+
+ def test_reload_is_same_and_reloads(self, pytester: Pytester) -> None:
+ """Reloading a (collected) module after change picks up the change."""
+ pytester.makeini(
+ """
+ [pytest]
+ python_files = *.py
+ """
+ )
+ pytester.makepyfile(
+ file="""
+ def reloaded():
+ return False
+
+ def rewrite_self():
+ with open(__file__, 'w', encoding='utf-8') as self:
+ self.write('def reloaded(): return True')
+ """,
+ test_fun="""
+ import sys
+ from importlib import reload
+
+ def test_loader():
+ import file
+ assert not file.reloaded()
+ file.rewrite_self()
+ assert sys.modules["file"] is reload(file)
+ assert file.reloaded()
+ """,
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 1 passed*"])
+
+ def test_get_data_support(self, pytester: Pytester) -> None:
+ """Implement optional PEP302 api (#808)."""
+ path = pytester.mkpydir("foo")
+ path.joinpath("test_foo.py").write_text(
+ textwrap.dedent(
+ """\
+ class Test(object):
+ def test_foo(self):
+ import pkgutil
+ data = pkgutil.get_data('foo.test_foo', 'data.txt')
+ assert data == b'Hey'
+ """
+ ),
+ encoding="utf-8",
+ )
+ path.joinpath("data.txt").write_text("Hey", encoding="utf-8")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+
+def test_issue731(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ class LongReprWithBraces(object):
+ def __repr__(self):
+ return 'LongReprWithBraces({' + ('a' * 80) + '}' + ('a' * 120) + ')'
+
+ def some_method(self):
+ return False
+
+ def test_long_repr():
+ obj = LongReprWithBraces()
+ assert obj.some_method()
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.no_fnmatch_line("*unbalanced braces*")
+
+
+class TestIssue925:
+ def test_simple_case(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_ternary_display():
+ assert (False == False) == False
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*E*assert (False == False) == False"])
+
+ def test_long_case(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_ternary_display():
+ assert False == (False == True) == True
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*E*assert (False == True) == True"])
+
+ def test_many_brackets(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_ternary_display():
+ assert True == ((False == True) == True)
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*E*assert True == ((False == True) == True)"])
+
+
+class TestIssue2121:
+ def test_rewrite_python_files_contain_subdirs(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ **{
+ "tests/file.py": """
+ def test_simple_failure():
+ assert 1 + 1 == 3
+ """
+ }
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ python_files = tests/**.py
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*E*assert (1 + 1) == 3"])
+
+
+class TestAssertionRewriteWalrusOperator:
+ """See #10743"""
+
+ def test_assertion_walrus_operator(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def my_func(before, after):
+ return before == after
+
+ def change_value(value):
+ return value.lower()
+
+ def test_walrus_conversion():
+ a = "Hello"
+ assert not my_func(a, a := change_value(a))
+ assert a == "hello"
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_walrus_operator_dont_rewrite(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ 'PYTEST_DONT_REWRITE'
+ def my_func(before, after):
+ return before == after
+
+ def change_value(value):
+ return value.lower()
+
+ def test_walrus_conversion_dont_rewrite():
+ a = "Hello"
+ assert not my_func(a, a := change_value(a))
+ assert a == "hello"
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_inline_walrus_operator(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def my_func(before, after):
+ return before == after
+
+ def test_walrus_conversion_inline():
+ a = "Hello"
+ assert not my_func(a, a := a.lower())
+ assert a == "hello"
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_inline_walrus_operator_reverse(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def my_func(before, after):
+ return before == after
+
+ def test_walrus_conversion_reverse():
+ a = "Hello"
+ assert my_func(a := a.lower(), a)
+ assert a == 'hello'
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_walrus_no_variable_name_conflict(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def test_walrus_conversion_no_conflict():
+ a = "Hello"
+ assert a == (b := a.lower())
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*AssertionError: assert 'Hello' == 'hello'"])
+
+ def test_assertion_walrus_operator_true_assertion_and_changes_variable_value(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def test_walrus_conversion_succeed():
+ a = "Hello"
+ assert a != (a := a.lower())
+ assert a == 'hello'
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_walrus_operator_fail_assertion(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_walrus_conversion_fails():
+ a = "Hello"
+ assert a == (a := a.lower())
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*AssertionError: assert 'Hello' == 'hello'"])
+
+ def test_assertion_walrus_operator_boolean_composite(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def test_walrus_operator_change_boolean_value():
+ a = True
+ assert a and True and ((a := False) is False) and (a is False) and ((a := None) is None)
+ assert a is None
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_walrus_operator_compare_boolean_fails(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def test_walrus_operator_change_boolean_value():
+ a = True
+ assert not (a and ((a := False) is False))
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*assert not (True and False is False)"])
+
+ def test_assertion_walrus_operator_boolean_none_fails(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def test_walrus_operator_change_boolean_value():
+ a = True
+ assert not (a and ((a := None) is None))
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*assert not (True and None is None)"])
+
+ def test_assertion_walrus_operator_value_changes_cleared_after_each_test(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def test_walrus_operator_change_value():
+ a = True
+ assert (a := None) is None
+
+ def test_walrus_operator_not_override_value():
+ a = True
+ assert a is True
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_namedexpr_compare_left_overwrite(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def test_namedexpr_compare_left_overwrite():
+ a = "Hello"
+ b = "World"
+ c = "Test"
+ assert (a := b) == c and (a := "Test") == "Test"
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*assert ('World' == 'Test'*"])
+
+
+class TestIssue11028:
+ def test_assertion_walrus_operator_in_operand(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_in_string():
+ assert (obj := "foo") in obj
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_walrus_operator_in_operand_json_dumps(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import json
+
+ def test_json_encoder():
+ assert (obj := "foo") in json.dumps(obj)
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_walrus_operator_equals_operand_function(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def f(a):
+ return a
+
+ def test_call_other_function_arg():
+ assert (obj := "foo") == f(obj)
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_walrus_operator_equals_operand_function_keyword_arg(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def f(a='test'):
+ return a
+
+ def test_call_other_function_k_arg():
+ assert (obj := "foo") == f(a=obj)
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_walrus_operator_equals_operand_function_arg_as_function(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def f(a='test'):
+ return a
+
+ def test_function_of_function():
+ assert (obj := "foo") == f(f(obj))
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ def test_assertion_walrus_operator_gt_operand_function(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def add_one(a):
+ return a + 1
+
+ def test_gt():
+ assert (obj := 4) > add_one(obj)
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*assert 4 > 5", "*where 5 = add_one(4)"])
+
+
+class TestIssue11239:
+ def test_assertion_walrus_different_test_cases(self, pytester: Pytester) -> None:
+ """Regression for (#11239)
+
+ Walrus operator rewriting would leak to separate test cases if they used the same variables.
+ """
+ pytester.makepyfile(
+ """
+ def test_1():
+ state = {"x": 2}.get("x")
+ assert state is not None
+
+ def test_2():
+ db = {"x": 2}
+ assert (state := db.get("x")) is not None
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+
+@pytest.mark.skipif(
+ sys.maxsize <= (2**31 - 1), reason="Causes OverflowError on 32bit systems"
+)
+@pytest.mark.parametrize("offset", [-1, +1])
+def test_source_mtime_long_long(pytester: Pytester, offset) -> None:
+ """Support modification dates after 2038 in rewritten files (#4903).
+
+ pytest would crash with:
+
+ fp.write(struct.pack(" None:
+ """Fix infinite recursion when writing pyc files: if an import happens to be triggered when writing the pyc
+ file, this would cause another call to the hook, which would trigger another pyc writing, which could
+ trigger another import, and so on. (#3506)"""
+ from _pytest.assertion import rewrite as rewritemod
+
+ pytester.syspathinsert()
+ pytester.makepyfile(test_foo="def test_foo(): pass")
+ pytester.makepyfile(test_bar="def test_bar(): pass")
+
+ original_write_pyc = rewritemod._write_pyc
+
+ write_pyc_called = []
+
+ def spy_write_pyc(*args, **kwargs):
+ # make a note that we have called _write_pyc
+ write_pyc_called.append(True)
+ # try to import a module at this point: we should not try to rewrite this module
+ assert hook.find_spec("test_bar") is None
+ return original_write_pyc(*args, **kwargs)
+
+ monkeypatch.setattr(rewritemod, "_write_pyc", spy_write_pyc)
+ monkeypatch.setattr(sys, "dont_write_bytecode", False)
+
+ hook = AssertionRewritingHook(pytestconfig)
+ spec = hook.find_spec("test_foo")
+ assert spec is not None
+ module = importlib.util.module_from_spec(spec)
+ hook.exec_module(module)
+ assert len(write_pyc_called) == 1
+
+
+class TestEarlyRewriteBailout:
+ @pytest.fixture
+ def hook(
+ self, pytestconfig, monkeypatch, pytester: Pytester
+ ) -> Generator[AssertionRewritingHook]:
+ """Returns a patched AssertionRewritingHook instance so we can configure its initial paths and track
+ if PathFinder.find_spec has been called.
+ """
+ import importlib.machinery
+
+ self.find_spec_calls: list[str] = []
+ self.initial_paths: set[Path] = set()
+
+ class StubSession:
+ _initialpaths = self.initial_paths
+
+ def isinitpath(self, p):
+ return p in self._initialpaths
+
+ def spy_find_spec(name, path):
+ self.find_spec_calls.append(name)
+ return importlib.machinery.PathFinder.find_spec(name, path)
+
+ hook = AssertionRewritingHook(pytestconfig)
+ # use default patterns, otherwise we inherit pytest's testing config
+ with mock.patch.object(hook, "fnpats", ["test_*.py", "*_test.py"]):
+ monkeypatch.setattr(hook, "_find_spec", spy_find_spec)
+ hook.set_session(StubSession()) # type: ignore[arg-type]
+ pytester.syspathinsert()
+ yield hook
+
+ def test_basic(self, pytester: Pytester, hook: AssertionRewritingHook) -> None:
+ """
+ Ensure we avoid calling PathFinder.find_spec when we know for sure a certain
+ module will not be rewritten to optimize assertion rewriting (#3918).
+ """
+ pytester.makeconftest(
+ """
+ import pytest
+ @pytest.fixture
+ def fix(): return 1
+ """
+ )
+ pytester.makepyfile(test_foo="def test_foo(): pass")
+ pytester.makepyfile(bar="def bar(): pass")
+ foobar_path = pytester.makepyfile(foobar="def foobar(): pass")
+ self.initial_paths.add(foobar_path)
+
+ # conftest files should always be rewritten
+ assert hook.find_spec("conftest") is not None
+ assert self.find_spec_calls == ["conftest"]
+
+ # files matching "python_files" mask should always be rewritten
+ assert hook.find_spec("test_foo") is not None
+ assert self.find_spec_calls == ["conftest", "test_foo"]
+
+ # file does not match "python_files": early bailout
+ assert hook.find_spec("bar") is None
+ assert self.find_spec_calls == ["conftest", "test_foo"]
+
+ # file is an initial path (passed on the command-line): should be rewritten
+ assert hook.find_spec("foobar") is not None
+ assert self.find_spec_calls == ["conftest", "test_foo", "foobar"]
+
+ def test_pattern_contains_subdirectories(
+ self, pytester: Pytester, hook: AssertionRewritingHook
+ ) -> None:
+ """If one of the python_files patterns contain subdirectories ("tests/**.py") we can't bailout early
+ because we need to match with the full path, which can only be found by calling PathFinder.find_spec
+ """
+ pytester.makepyfile(
+ **{
+ "tests/file.py": """\
+ def test_simple_failure():
+ assert 1 + 1 == 3
+ """
+ }
+ )
+ pytester.syspathinsert("tests")
+ with mock.patch.object(hook, "fnpats", ["tests/**.py"]):
+ assert hook.find_spec("file") is not None
+ assert self.find_spec_calls == ["file"]
+
+ @pytest.mark.skipif(
+ sys.platform.startswith("win32"), reason="cannot remove cwd on Windows"
+ )
+ @pytest.mark.skipif(
+ sys.platform.startswith("sunos5"), reason="cannot remove cwd on Solaris"
+ )
+ def test_cwd_changed(self, pytester: Pytester, monkeypatch) -> None:
+ # Setup conditions for py's fspath trying to import pathlib on py34
+ # always (previously triggered via xdist only).
+ # Ref: https://github.com/pytest-dev/py/pull/207
+ monkeypatch.syspath_prepend("")
+ monkeypatch.delitem(sys.modules, "pathlib", raising=False)
+
+ pytester.makepyfile(
+ **{
+ "test_setup_nonexisting_cwd.py": """\
+ import os
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as newpath:
+ os.chdir(newpath)
+ """,
+ "test_test.py": """\
+ def test():
+ pass
+ """,
+ }
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["* 1 passed in *"])
+
+
+class TestAssertionPass:
+ def test_option_default(self, pytester: Pytester) -> None:
+ config = pytester.parseconfig()
+ assert config.getini("enable_assertion_pass_hook") is False
+
+ @pytest.fixture
+ def flag_on(self, pytester: Pytester):
+ pytester.makeini("[pytest]\nenable_assertion_pass_hook = True\n")
+
+ @pytest.fixture
+ def hook_on(self, pytester: Pytester):
+ pytester.makeconftest(
+ """\
+ def pytest_assertion_pass(item, lineno, orig, expl):
+ raise Exception("Assertion Passed: {} {} at line {}".format(orig, expl, lineno))
+ """
+ )
+
+ def test_hook_call(self, pytester: Pytester, flag_on, hook_on) -> None:
+ pytester.makepyfile(
+ """\
+ def test_simple():
+ a=1
+ b=2
+ c=3
+ d=0
+
+ assert a+b == c+d
+
+ # cover failing assertions with a message
+ def test_fails():
+ assert False, "assert with message"
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ "*Assertion Passed: a+b == c+d (1 + 2) == (3 + 0) at line 7*"
+ )
+
+ def test_hook_call_with_parens(self, pytester: Pytester, flag_on, hook_on) -> None:
+ pytester.makepyfile(
+ """\
+ def f(): return 1
+ def test():
+ assert f()
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines("*Assertion Passed: f() 1")
+
+ def test_hook_not_called_without_hookimpl(
+ self, pytester: Pytester, monkeypatch, flag_on
+ ) -> None:
+ """Assertion pass should not be called (and hence formatting should
+ not occur) if there is no hook declared for pytest_assertion_pass"""
+
+ def raise_on_assertionpass(*_, **__):
+ raise Exception("Assertion passed called when it shouldn't!")
+
+ monkeypatch.setattr(
+ _pytest.assertion.rewrite, "_call_assertion_pass", raise_on_assertionpass
+ )
+
+ pytester.makepyfile(
+ """\
+ def test_simple():
+ a=1
+ b=2
+ c=3
+ d=0
+
+ assert a+b == c+d
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+
+ def test_hook_not_called_without_cmd_option(
+ self, pytester: Pytester, monkeypatch
+ ) -> None:
+ """Assertion pass should not be called (and hence formatting should
+ not occur) if there is no hook declared for pytest_assertion_pass"""
+
+ def raise_on_assertionpass(*_, **__):
+ raise Exception("Assertion passed called when it shouldn't!")
+
+ monkeypatch.setattr(
+ _pytest.assertion.rewrite, "_call_assertion_pass", raise_on_assertionpass
+ )
+
+ pytester.makeconftest(
+ """\
+ def pytest_assertion_pass(item, lineno, orig, expl):
+ raise Exception("Assertion Passed: {} {} at line {}".format(orig, expl, lineno))
+ """
+ )
+
+ pytester.makepyfile(
+ """\
+ def test_simple():
+ a=1
+ b=2
+ c=3
+ d=0
+
+ assert a+b == c+d
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+
+
+# fmt: off
+@pytest.mark.parametrize(
+ ("src", "expected"),
+ (
+ pytest.param(b"", {}, id="trivial"),
+ pytest.param(
+ b"def x(): assert 1\n",
+ {1: "1"},
+ id="assert statement not on own line",
+ ),
+ pytest.param(
+ b"def x():\n"
+ b" assert 1\n"
+ b" assert 1+2\n",
+ {2: "1", 3: "1+2"},
+ id="multiple assertions",
+ ),
+ pytest.param(
+ # changes in encoding cause the byte offsets to be different
+ "# -*- coding: latin1\n"
+ "def ÀÀÀÀÀ(): assert 1\n".encode("latin1"),
+ {2: "1"},
+ id="latin1 encoded on first line\n",
+ ),
+ pytest.param(
+ # using the default utf-8 encoding
+ "def ÀÀÀÀÀ(): assert 1\n".encode(),
+ {1: "1"},
+ id="utf-8 encoded on first line",
+ ),
+ pytest.param(
+ b"def x():\n"
+ b" assert (\n"
+ b" 1 + 2 # comment\n"
+ b" )\n",
+ {2: "(\n 1 + 2 # comment\n )"},
+ id="multi-line assertion",
+ ),
+ pytest.param(
+ b"def x():\n"
+ b" assert y == [\n"
+ b" 1, 2, 3\n"
+ b" ]\n",
+ {2: "y == [\n 1, 2, 3\n ]"},
+ id="multi line assert with list continuation",
+ ),
+ pytest.param(
+ b"def x():\n"
+ b" assert 1 + \\\n"
+ b" 2\n",
+ {2: "1 + \\\n 2"},
+ id="backslash continuation",
+ ),
+ pytest.param(
+ b"def x():\n"
+ b" assert x, y\n",
+ {2: "x"},
+ id="assertion with message",
+ ),
+ pytest.param(
+ b"def x():\n"
+ b" assert (\n"
+ b" f(1, 2, 3)\n"
+ b" ), 'f did not work!'\n",
+ {2: "(\n f(1, 2, 3)\n )"},
+ id="assertion with message, test spanning multiple lines",
+ ),
+ pytest.param(
+ b"def x():\n"
+ b" assert \\\n"
+ b" x\\\n"
+ b" , 'failure message'\n",
+ {2: "x"},
+ id="escaped newlines plus message",
+ ),
+ pytest.param(
+ b"def x(): assert 5",
+ {1: "5"},
+ id="no newline at end of file",
+ ),
+ ),
+)
+def test_get_assertion_exprs(src, expected) -> None:
+ assert _get_assertion_exprs(src) == expected
+# fmt: on
+
+
+def test_try_makedirs(monkeypatch, tmp_path: Path) -> None:
+ from _pytest.assertion.rewrite import try_makedirs
+
+ p = tmp_path / "foo"
+
+ # create
+ assert try_makedirs(p)
+ assert p.is_dir()
+
+ # already exist
+ assert try_makedirs(p)
+
+ # monkeypatch to simulate all error situations
+ def fake_mkdir(p, exist_ok=False, *, exc):
+ assert isinstance(p, Path)
+ raise exc
+
+ monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=FileNotFoundError()))
+ assert not try_makedirs(p)
+
+ monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=NotADirectoryError()))
+ assert not try_makedirs(p)
+
+ monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=PermissionError()))
+ assert not try_makedirs(p)
+
+ err = OSError()
+ err.errno = errno.EROFS
+ monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=err))
+ assert not try_makedirs(p)
+
+ err = OSError()
+ err.errno = errno.ENOSYS
+ monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=err))
+ assert not try_makedirs(p)
+
+ # unhandled OSError should raise
+ err = OSError()
+ err.errno = errno.ECHILD
+ monkeypatch.setattr(os, "makedirs", partial(fake_mkdir, exc=err))
+ with pytest.raises(OSError) as exc_info:
+ try_makedirs(p)
+ assert exc_info.value.errno == errno.ECHILD
+
+
+class TestPyCacheDir:
+ @pytest.mark.parametrize(
+ "prefix, source, expected",
+ [
+ ("c:/tmp/pycs", "d:/projects/src/foo.py", "c:/tmp/pycs/projects/src"),
+ (None, "d:/projects/src/foo.py", "d:/projects/src/__pycache__"),
+ ("/tmp/pycs", "/home/projects/src/foo.py", "/tmp/pycs/home/projects/src"),
+ (None, "/home/projects/src/foo.py", "/home/projects/src/__pycache__"),
+ ],
+ )
+ def test_get_cache_dir(self, monkeypatch, prefix, source, expected) -> None:
+ monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)
+ monkeypatch.setattr(sys, "pycache_prefix", prefix, raising=False)
+
+ assert get_cache_dir(Path(source)) == Path(expected)
+
+ def test_sys_pycache_prefix_integration(
+ self, tmp_path, monkeypatch, pytester: Pytester
+ ) -> None:
+ """Integration test for sys.pycache_prefix (#4730)."""
+ pycache_prefix = tmp_path / "my/pycs"
+ monkeypatch.setattr(sys, "pycache_prefix", str(pycache_prefix))
+ monkeypatch.setattr(sys, "dont_write_bytecode", False)
+
+ pytester.makepyfile(
+ **{
+ "src/test_foo.py": """
+ import bar
+ def test_foo():
+ pass
+ """,
+ "src/bar/__init__.py": "",
+ }
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+ test_foo = pytester.path.joinpath("src/test_foo.py")
+ bar_init = pytester.path.joinpath("src/bar/__init__.py")
+ assert test_foo.is_file()
+ assert bar_init.is_file()
+
+ # test file: rewritten, custom pytest cache tag
+ test_foo_pyc = get_cache_dir(test_foo) / ("test_foo" + PYC_TAIL)
+ assert test_foo_pyc.is_file()
+
+ # normal file: not touched by pytest, normal cache tag
+ bar_init_pyc = (
+ get_cache_dir(bar_init) / f"__init__.{sys.implementation.cache_tag}.pyc"
+ )
+ assert bar_init_pyc.is_file()
+
+
+class TestReprSizeVerbosity:
+ """
+ Check that verbosity also controls the string length threshold to shorten it using
+ ellipsis.
+ """
+
+ @pytest.mark.parametrize(
+ "verbose, expected_size",
+ [
+ (0, DEFAULT_REPR_MAX_SIZE),
+ (1, DEFAULT_REPR_MAX_SIZE * 10),
+ (2, None),
+ (3, None),
+ ],
+ )
+ def test_get_maxsize_for_saferepr(self, verbose: int, expected_size) -> None:
+ class FakeConfig:
+ def get_verbosity(self, verbosity_type: str | None = None) -> int:
+ return verbose
+
+ config = FakeConfig()
+ assert _get_maxsize_for_saferepr(cast(Config, config)) == expected_size
+
+ def test_get_maxsize_for_saferepr_no_config(self) -> None:
+ assert _get_maxsize_for_saferepr(None) == DEFAULT_REPR_MAX_SIZE
+
+ def create_test_file(self, pytester: Pytester, size: int) -> None:
+ pytester.makepyfile(
+ f"""
+ def test_very_long_string():
+ text = "x" * {size}
+ assert "hello world" in text
+ """
+ )
+
+ def test_default_verbosity(self, pytester: Pytester) -> None:
+ self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE)
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*xxx...xxx*"])
+
+ def test_increased_verbosity(self, pytester: Pytester) -> None:
+ self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE)
+ result = pytester.runpytest("-v")
+ result.stdout.no_fnmatch_line("*xxx...xxx*")
+
+ def test_max_increased_verbosity(self, pytester: Pytester) -> None:
+ self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE * 10)
+ result = pytester.runpytest("-vv")
+ result.stdout.no_fnmatch_line("*xxx...xxx*")
+
+
+class TestIssue11140:
+ def test_constant_not_picked_as_module_docstring(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """\
+ 0
+
+ def test_foo():
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+
+
+class TestSafereprUnbounded:
+ class Help:
+ def bound_method(self): # pragma: no cover
+ pass
+
+ def test_saferepr_bound_method(self):
+ """saferepr() of a bound method should show only the method name"""
+ assert _saferepr(self.Help().bound_method) == "bound_method"
+
+ def test_saferepr_unbounded(self):
+ """saferepr() of an unbound method should still show the full information"""
+ obj = self.Help()
+ # using id() to fetch memory address fails on different platforms
+ pattern = re.compile(
+ rf"<{Path(__file__).stem}.{self.__class__.__name__}.Help object at 0x[0-9a-fA-F]*>",
+ )
+ assert pattern.match(_saferepr(obj))
+ assert (
+ _saferepr(self.Help)
+ == f""
+ )
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_cacheprovider.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_cacheprovider.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ac3f38ab644d7b09977a23e48362d6587f33eab
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_cacheprovider.py
@@ -0,0 +1,1397 @@
+from __future__ import annotations
+
+from collections.abc import Generator
+from collections.abc import Sequence
+from enum import auto
+from enum import Enum
+import os
+from pathlib import Path
+import shutil
+from typing import Any
+
+from _pytest.compat import assert_never
+from _pytest.config import ExitCode
+from _pytest.monkeypatch import MonkeyPatch
+from _pytest.pytester import Pytester
+from _pytest.tmpdir import TempPathFactory
+import pytest
+
+
+pytest_plugins = ("pytester",)
+
+
+class TestNewAPI:
+ def test_config_cache_mkdir(self, pytester: Pytester) -> None:
+ pytester.makeini("[pytest]")
+ config = pytester.parseconfigure()
+ assert config.cache is not None
+ with pytest.raises(ValueError):
+ config.cache.mkdir("key/name")
+
+ p = config.cache.mkdir("name")
+ assert p.is_dir()
+
+ def test_cache_dir_permissions(self, pytester: Pytester) -> None:
+ """The .pytest_cache directory should have world-readable permissions
+ (depending on umask).
+
+ Regression test for #12308.
+ """
+ pytester.makeini("[pytest]")
+ config = pytester.parseconfigure()
+ assert config.cache is not None
+ p = config.cache.mkdir("name")
+ assert p.is_dir()
+ # Instead of messing with umask, make sure .pytest_cache has the same
+ # permissions as the default that `mkdir` gives `p`.
+ assert (p.parent.stat().st_mode & 0o777) == (p.stat().st_mode & 0o777)
+
+ def test_config_cache_dataerror(self, pytester: Pytester) -> None:
+ pytester.makeini("[pytest]")
+ config = pytester.parseconfigure()
+ assert config.cache is not None
+ cache = config.cache
+ with pytest.raises(TypeError):
+ cache.set("key/name", cache)
+ config.cache.set("key/name", 0)
+ config.cache._getvaluepath("key/name").write_bytes(b"123invalid")
+ val = config.cache.get("key/name", -2)
+ assert val == -2
+
+ @pytest.mark.filterwarnings("ignore:could not create cache path")
+ def test_cache_writefail_cachefile_silent(self, pytester: Pytester) -> None:
+ pytester.makeini("[pytest]")
+ pytester.path.joinpath(".pytest_cache").write_text(
+ "gone wrong", encoding="utf-8"
+ )
+ config = pytester.parseconfigure()
+ cache = config.cache
+ assert cache is not None
+ cache.set("test/broken", [])
+
+ @pytest.fixture
+ def unwritable_cache_dir(self, pytester: Pytester) -> Generator[Path]:
+ cache_dir = pytester.path.joinpath(".pytest_cache")
+ cache_dir.mkdir()
+ mode = cache_dir.stat().st_mode
+ cache_dir.chmod(0)
+ if os.access(cache_dir, os.W_OK):
+ pytest.skip("Failed to make cache dir unwritable")
+
+ yield cache_dir
+ cache_dir.chmod(mode)
+
+ @pytest.mark.filterwarnings(
+ "ignore:could not create cache path:pytest.PytestWarning"
+ )
+ def test_cache_writefail_permissions(
+ self, unwritable_cache_dir: Path, pytester: Pytester
+ ) -> None:
+ pytester.makeini("[pytest]")
+ config = pytester.parseconfigure()
+ cache = config.cache
+ assert cache is not None
+ cache.set("test/broken", [])
+
+ @pytest.mark.filterwarnings("default")
+ def test_cache_failure_warns(
+ self,
+ pytester: Pytester,
+ monkeypatch: MonkeyPatch,
+ unwritable_cache_dir: Path,
+ ) -> None:
+ monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")
+
+ pytester.makepyfile("def test_error(): raise Exception")
+ result = pytester.runpytest()
+ assert result.ret == 1
+ # warnings from nodeids and lastfailed
+ result.stdout.fnmatch_lines(
+ [
+ # Validate location/stacklevel of warning from cacheprovider.
+ "*= warnings summary =*",
+ "*/cacheprovider.py:*",
+ " */cacheprovider.py:*: PytestCacheWarning: could not create cache path "
+ f"{unwritable_cache_dir}/v/cache/nodeids: *",
+ ' config.cache.set("cache/nodeids", sorted(self.cached_nodeids))',
+ "*1 failed, 2 warnings in*",
+ ]
+ )
+
+ def test_config_cache(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ def pytest_configure(config):
+ # see that we get cache information early on
+ assert hasattr(config, "cache")
+ """
+ )
+ pytester.makepyfile(
+ """
+ def test_session(pytestconfig):
+ assert hasattr(pytestconfig, "cache")
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_cachefuncarg(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ def test_cachefuncarg(cache):
+ val = cache.get("some/thing", None)
+ assert val is None
+ cache.set("some/thing", [1])
+ with pytest.raises(TypeError):
+ cache.get("some/thing")
+ val = cache.get("some/thing", [])
+ assert val == [1]
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_custom_rel_cache_dir(self, pytester: Pytester) -> None:
+ rel_cache_dir = os.path.join("custom_cache_dir", "subdir")
+ pytester.makeini(
+ f"""
+ [pytest]
+ cache_dir = {rel_cache_dir}
+ """
+ )
+ pytester.makepyfile(test_errored="def test_error():\n assert False")
+ pytester.runpytest()
+ assert pytester.path.joinpath(rel_cache_dir).is_dir()
+
+ def test_custom_abs_cache_dir(
+ self, pytester: Pytester, tmp_path_factory: TempPathFactory
+ ) -> None:
+ tmp = tmp_path_factory.mktemp("tmp")
+ abs_cache_dir = tmp / "custom_cache_dir"
+ pytester.makeini(
+ f"""
+ [pytest]
+ cache_dir = {abs_cache_dir}
+ """
+ )
+ pytester.makepyfile(test_errored="def test_error():\n assert False")
+ pytester.runpytest()
+ assert abs_cache_dir.is_dir()
+
+ def test_custom_cache_dir_with_env_var(
+ self, pytester: Pytester, monkeypatch: MonkeyPatch
+ ) -> None:
+ monkeypatch.setenv("env_var", "custom_cache_dir")
+ pytester.makeini(
+ """
+ [pytest]
+ cache_dir = {cache_dir}
+ """.format(cache_dir="$env_var")
+ )
+ pytester.makepyfile(test_errored="def test_error():\n assert False")
+ pytester.runpytest()
+ assert pytester.path.joinpath("custom_cache_dir").is_dir()
+
+
+@pytest.mark.parametrize("env", ((), ("TOX_ENV_DIR", "mydir/tox-env")))
+def test_cache_reportheader(
+ env: Sequence[str], pytester: Pytester, monkeypatch: MonkeyPatch
+) -> None:
+ pytester.makepyfile("""def test_foo(): pass""")
+ if env:
+ monkeypatch.setenv(*env)
+ expected = os.path.join(env[1], ".pytest_cache")
+ else:
+ monkeypatch.delenv("TOX_ENV_DIR", raising=False)
+ expected = ".pytest_cache"
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines([f"cachedir: {expected}"])
+
+
+def test_cache_reportheader_external_abspath(
+ pytester: Pytester, tmp_path_factory: TempPathFactory
+) -> None:
+ external_cache = tmp_path_factory.mktemp(
+ "test_cache_reportheader_external_abspath_abs"
+ )
+
+ pytester.makepyfile("def test_hello(): pass")
+ pytester.makeini(
+ f"""
+ [pytest]
+ cache_dir = {external_cache}
+ """
+ )
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines([f"cachedir: {external_cache}"])
+
+
+def test_cache_show(pytester: Pytester) -> None:
+ result = pytester.runpytest("--cache-show")
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*cache is empty*"])
+ pytester.makeconftest(
+ """
+ def pytest_configure(config):
+ config.cache.set("my/name", [1,2,3])
+ config.cache.set("my/hello", "world")
+ config.cache.set("other/some", {1:2})
+ dp = config.cache.mkdir("mydb")
+ dp.joinpath("hello").touch()
+ dp.joinpath("world").touch()
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 5 # no tests executed
+
+ result = pytester.runpytest("--cache-show")
+ result.stdout.fnmatch_lines(
+ [
+ "*cachedir:*",
+ "*- cache values for '[*]' -*",
+ "cache/nodeids contains:",
+ "my/name contains:",
+ " [1, 2, 3]",
+ "other/some contains:",
+ " {*'1': 2}",
+ "*- cache directories for '[*]' -*",
+ "*mydb/hello*length 0*",
+ "*mydb/world*length 0*",
+ ]
+ )
+ assert result.ret == 0
+
+ result = pytester.runpytest("--cache-show", "*/hello")
+ result.stdout.fnmatch_lines(
+ [
+ "*cachedir:*",
+ "*- cache values for '[*]/hello' -*",
+ "my/hello contains:",
+ " *'world'",
+ "*- cache directories for '[*]/hello' -*",
+ "d/mydb/hello*length 0*",
+ ]
+ )
+ stdout = result.stdout.str()
+ assert "other/some" not in stdout
+ assert "d/mydb/world" not in stdout
+ assert result.ret == 0
+
+
+class TestLastFailed:
+ def test_lastfailed_usecase(
+ self, pytester: Pytester, monkeypatch: MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr("sys.dont_write_bytecode", True)
+ p = pytester.makepyfile(
+ """
+ def test_1(): assert 0
+ def test_2(): assert 0
+ def test_3(): assert 1
+ """
+ )
+ result = pytester.runpytest(str(p))
+ result.stdout.fnmatch_lines(["*2 failed*"])
+ p = pytester.makepyfile(
+ """
+ def test_1(): assert 1
+ def test_2(): assert 1
+ def test_3(): assert 0
+ """
+ )
+ result = pytester.runpytest(str(p), "--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 3 items / 1 deselected / 2 selected",
+ "run-last-failure: rerun previous 2 failures",
+ "*= 2 passed, 1 deselected in *",
+ ]
+ )
+ result = pytester.runpytest(str(p), "--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 3 items",
+ "run-last-failure: no previously failed tests, not deselecting items.",
+ "*1 failed*2 passed*",
+ ]
+ )
+ pytester.path.joinpath(".pytest_cache", ".git").mkdir(parents=True)
+ result = pytester.runpytest(str(p), "--lf", "--cache-clear")
+ result.stdout.fnmatch_lines(["*1 failed*2 passed*"])
+ assert pytester.path.joinpath(".pytest_cache", "README.md").is_file()
+ assert pytester.path.joinpath(".pytest_cache", ".git").is_dir()
+
+ # Run this again to make sure clear-cache is robust
+ if os.path.isdir(".pytest_cache"):
+ shutil.rmtree(".pytest_cache")
+ result = pytester.runpytest("--lf", "--cache-clear")
+ result.stdout.fnmatch_lines(["*1 failed*2 passed*"])
+
+ def test_failedfirst_order(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ test_a="def test_always_passes(): pass",
+ test_b="def test_always_fails(): assert 0",
+ )
+ result = pytester.runpytest()
+ # Test order will be collection order; alphabetical
+ result.stdout.fnmatch_lines(["test_a.py*", "test_b.py*"])
+ result = pytester.runpytest("--ff")
+ # Test order will be failing tests first
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "run-last-failure: rerun previous 1 failure first",
+ "test_b.py*",
+ "test_a.py*",
+ ]
+ )
+
+ def test_lastfailed_failedfirst_order(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ test_a="def test_always_passes(): assert 1",
+ test_b="def test_always_fails(): assert 0",
+ )
+ result = pytester.runpytest()
+ # Test order will be collection order; alphabetical
+ result.stdout.fnmatch_lines(["test_a.py*", "test_b.py*"])
+ result = pytester.runpytest("--lf", "--ff")
+ # Test order will be failing tests first
+ result.stdout.fnmatch_lines(["test_b.py*"])
+ result.stdout.no_fnmatch_line("*test_a.py*")
+
+ def test_lastfailed_difference_invocations(
+ self, pytester: Pytester, monkeypatch: MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr("sys.dont_write_bytecode", True)
+ pytester.makepyfile(
+ test_a="""
+ def test_a1(): assert 0
+ def test_a2(): assert 1
+ """,
+ test_b="def test_b1(): assert 0",
+ )
+ p = pytester.path.joinpath("test_a.py")
+ p2 = pytester.path.joinpath("test_b.py")
+
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*2 failed*"])
+ result = pytester.runpytest("--lf", p2)
+ result.stdout.fnmatch_lines(["*1 failed*"])
+
+ pytester.makepyfile(test_b="def test_b1(): assert 1")
+ result = pytester.runpytest("--lf", p2)
+ result.stdout.fnmatch_lines(["*1 passed*"])
+ result = pytester.runpytest("--lf", p)
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items / 1 deselected / 1 selected",
+ "run-last-failure: rerun previous 1 failure",
+ "*= 1 failed, 1 deselected in *",
+ ]
+ )
+
+ def test_lastfailed_usecase_splice(
+ self, pytester: Pytester, monkeypatch: MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr("sys.dont_write_bytecode", True)
+ pytester.makepyfile(
+ "def test_1(): assert 0", test_something="def test_2(): assert 0"
+ )
+ p2 = pytester.path.joinpath("test_something.py")
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*2 failed*"])
+ result = pytester.runpytest("--lf", p2)
+ result.stdout.fnmatch_lines(["*1 failed*"])
+ result = pytester.runpytest("--lf")
+ result.stdout.fnmatch_lines(["*2 failed*"])
+
+ def test_lastfailed_xpass(self, pytester: Pytester) -> None:
+ pytester.inline_runsource(
+ """
+ import pytest
+ @pytest.mark.xfail
+ def test_hello():
+ assert 1
+ """
+ )
+ config = pytester.parseconfigure()
+ assert config.cache is not None
+ lastfailed = config.cache.get("cache/lastfailed", -1)
+ assert lastfailed == -1
+
+ def test_non_serializable_parametrize(self, pytester: Pytester) -> None:
+ """Test that failed parametrized tests with unmarshable parameters
+ don't break pytest-cache.
+ """
+ pytester.makepyfile(
+ r"""
+ import pytest
+
+ @pytest.mark.parametrize('val', [
+ b'\xac\x10\x02G',
+ ])
+ def test_fail(val):
+ assert False
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 failed in*"])
+
+ @pytest.mark.parametrize("parent", ("directory", "package"))
+ def test_terminal_report_lastfailed(self, pytester: Pytester, parent: str) -> None:
+ if parent == "package":
+ pytester.makepyfile(
+ __init__="",
+ )
+
+ test_a = pytester.makepyfile(
+ test_a="""
+ def test_a1(): pass
+ def test_a2(): pass
+ """
+ )
+ test_b = pytester.makepyfile(
+ test_b="""
+ def test_b1(): assert 0
+ def test_b2(): assert 0
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 4 items", "*2 failed, 2 passed in*"])
+
+ result = pytester.runpytest("--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "run-last-failure: rerun previous 2 failures (skipped 1 file)",
+ "*2 failed in*",
+ ]
+ )
+
+ result = pytester.runpytest(test_a, "--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "run-last-failure: 2 known failures not in selected tests",
+ "*2 passed in*",
+ ]
+ )
+
+ result = pytester.runpytest(test_b, "--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "run-last-failure: rerun previous 2 failures",
+ "*2 failed in*",
+ ]
+ )
+
+ result = pytester.runpytest("test_b.py::test_b1", "--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "run-last-failure: rerun previous 1 failure",
+ "*1 failed in*",
+ ]
+ )
+
+ def test_terminal_report_failedfirst(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ test_a="""
+ def test_a1(): assert 0
+ def test_a2(): pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 2 items", "*1 failed, 1 passed in*"])
+
+ result = pytester.runpytest("--ff")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "run-last-failure: rerun previous 1 failure first",
+ "*1 failed, 1 passed in*",
+ ]
+ )
+
+ def test_lastfailed_collectfailure(
+ self, pytester: Pytester, monkeypatch: MonkeyPatch
+ ) -> None:
+ pytester.makepyfile(
+ test_maybe="""
+ import os
+ env = os.environ
+ if '1' == env['FAILIMPORT']:
+ raise ImportError('fail')
+ def test_hello():
+ assert '0' == env['FAILTEST']
+ """
+ )
+
+ def rlf(fail_import: int, fail_run: int) -> Any:
+ monkeypatch.setenv("FAILIMPORT", str(fail_import))
+ monkeypatch.setenv("FAILTEST", str(fail_run))
+
+ pytester.runpytest("-q")
+ config = pytester.parseconfigure()
+ assert config.cache is not None
+ lastfailed = config.cache.get("cache/lastfailed", -1)
+ return lastfailed
+
+ lastfailed = rlf(fail_import=0, fail_run=0)
+ assert lastfailed == -1
+
+ lastfailed = rlf(fail_import=1, fail_run=0)
+ assert list(lastfailed) == ["test_maybe.py"]
+
+ lastfailed = rlf(fail_import=0, fail_run=1)
+ assert list(lastfailed) == ["test_maybe.py::test_hello"]
+
+ def test_lastfailed_failure_subset(
+ self, pytester: Pytester, monkeypatch: MonkeyPatch
+ ) -> None:
+ pytester.makepyfile(
+ test_maybe="""
+ import os
+ env = os.environ
+ if '1' == env['FAILIMPORT']:
+ raise ImportError('fail')
+ def test_hello():
+ assert '0' == env['FAILTEST']
+ """
+ )
+
+ pytester.makepyfile(
+ test_maybe2="""
+ import os
+ env = os.environ
+ if '1' == env['FAILIMPORT']:
+ raise ImportError('fail')
+
+ def test_hello():
+ assert '0' == env['FAILTEST']
+
+ def test_pass():
+ pass
+ """
+ )
+
+ def rlf(
+ fail_import: int, fail_run: int, args: Sequence[str] = ()
+ ) -> tuple[Any, Any]:
+ monkeypatch.setenv("FAILIMPORT", str(fail_import))
+ monkeypatch.setenv("FAILTEST", str(fail_run))
+
+ result = pytester.runpytest("-q", "--lf", *args)
+ config = pytester.parseconfigure()
+ assert config.cache is not None
+ lastfailed = config.cache.get("cache/lastfailed", -1)
+ return result, lastfailed
+
+ result, lastfailed = rlf(fail_import=0, fail_run=0)
+ assert lastfailed == -1
+ result.stdout.fnmatch_lines(["*3 passed*"])
+
+ result, lastfailed = rlf(fail_import=1, fail_run=0)
+ assert sorted(list(lastfailed)) == ["test_maybe.py", "test_maybe2.py"]
+
+ result, lastfailed = rlf(fail_import=0, fail_run=0, args=("test_maybe2.py",))
+ assert list(lastfailed) == ["test_maybe.py"]
+
+ # edge case of test selection - even if we remember failures
+ # from other tests we still need to run all tests if no test
+ # matches the failures
+ result, lastfailed = rlf(fail_import=0, fail_run=0, args=("test_maybe2.py",))
+ assert list(lastfailed) == ["test_maybe.py"]
+ result.stdout.fnmatch_lines(["*2 passed*"])
+
+ def test_lastfailed_creates_cache_when_needed(self, pytester: Pytester) -> None:
+ # Issue #1342
+ pytester.makepyfile(test_empty="")
+ pytester.runpytest("-q", "--lf")
+ assert not os.path.exists(".pytest_cache/v/cache/lastfailed")
+
+ pytester.makepyfile(test_successful="def test_success():\n assert True")
+ pytester.runpytest("-q", "--lf")
+ assert not os.path.exists(".pytest_cache/v/cache/lastfailed")
+
+ pytester.makepyfile(test_errored="def test_error():\n assert False")
+ pytester.runpytest("-q", "--lf")
+ assert os.path.exists(".pytest_cache/v/cache/lastfailed")
+
+ def test_xfail_not_considered_failure(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.mark.xfail
+ def test(): assert 0
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 xfailed*"])
+ assert self.get_cached_last_failed(pytester) == []
+
+ def test_xfail_strict_considered_failure(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ @pytest.mark.xfail(strict=True)
+ def test(): pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 failed*"])
+ assert self.get_cached_last_failed(pytester) == [
+ "test_xfail_strict_considered_failure.py::test"
+ ]
+
+ @pytest.mark.parametrize("mark", ["mark.xfail", "mark.skip"])
+ def test_failed_changed_to_xfail_or_skip(
+ self, pytester: Pytester, mark: str
+ ) -> None:
+ pytester.makepyfile(
+ """
+ import pytest
+ def test(): assert 0
+ """
+ )
+ result = pytester.runpytest()
+ assert self.get_cached_last_failed(pytester) == [
+ "test_failed_changed_to_xfail_or_skip.py::test"
+ ]
+ assert result.ret == 1
+
+ pytester.makepyfile(
+ f"""
+ import pytest
+ @pytest.{mark}
+ def test(): assert 0
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+ assert self.get_cached_last_failed(pytester) == []
+ assert result.ret == 0
+
+ @pytest.mark.parametrize("quiet", [True, False])
+ @pytest.mark.parametrize("opt", ["--ff", "--lf"])
+ def test_lf_and_ff_prints_no_needless_message(
+ self, quiet: bool, opt: str, pytester: Pytester
+ ) -> None:
+ # Issue 3853
+ pytester.makepyfile("def test(): assert 0")
+ args = [opt]
+ if quiet:
+ args.append("-q")
+ result = pytester.runpytest(*args)
+ result.stdout.no_fnmatch_line("*run all*")
+
+ result = pytester.runpytest(*args)
+ if quiet:
+ result.stdout.no_fnmatch_line("*run all*")
+ else:
+ assert "rerun previous" in result.stdout.str()
+
+ def get_cached_last_failed(self, pytester: Pytester) -> list[str]:
+ config = pytester.parseconfigure()
+ assert config.cache is not None
+ return sorted(config.cache.get("cache/lastfailed", {}))
+
+ def test_cache_cumulative(self, pytester: Pytester) -> None:
+ """Test workflow where user fixes errors gradually file by file using --lf."""
+ # 1. initial run
+ test_bar = pytester.makepyfile(
+ test_bar="""
+ def test_bar_1(): pass
+ def test_bar_2(): assert 0
+ """
+ )
+ test_foo = pytester.makepyfile(
+ test_foo="""
+ def test_foo_3(): pass
+ def test_foo_4(): assert 0
+ """
+ )
+ pytester.runpytest()
+ assert self.get_cached_last_failed(pytester) == [
+ "test_bar.py::test_bar_2",
+ "test_foo.py::test_foo_4",
+ ]
+
+ # 2. fix test_bar_2, run only test_bar.py
+ pytester.makepyfile(
+ test_bar="""
+ def test_bar_1(): pass
+ def test_bar_2(): pass
+ """
+ )
+ result = pytester.runpytest(test_bar)
+ result.stdout.fnmatch_lines(["*2 passed*"])
+ # ensure cache does not forget that test_foo_4 failed once before
+ assert self.get_cached_last_failed(pytester) == ["test_foo.py::test_foo_4"]
+
+ result = pytester.runpytest("--last-failed")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "run-last-failure: rerun previous 1 failure (skipped 1 file)",
+ "*= 1 failed in *",
+ ]
+ )
+ assert self.get_cached_last_failed(pytester) == ["test_foo.py::test_foo_4"]
+
+ # 3. fix test_foo_4, run only test_foo.py
+ test_foo = pytester.makepyfile(
+ test_foo="""
+ def test_foo_3(): pass
+ def test_foo_4(): pass
+ """
+ )
+ result = pytester.runpytest(test_foo, "--last-failed")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items / 1 deselected / 1 selected",
+ "run-last-failure: rerun previous 1 failure",
+ "*= 1 passed, 1 deselected in *",
+ ]
+ )
+ assert self.get_cached_last_failed(pytester) == []
+
+ result = pytester.runpytest("--last-failed")
+ result.stdout.fnmatch_lines(["*4 passed*"])
+ assert self.get_cached_last_failed(pytester) == []
+
+ def test_lastfailed_no_failures_behavior_all_passed(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def test_1(): pass
+ def test_2(): pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*2 passed*"])
+ result = pytester.runpytest("--lf")
+ result.stdout.fnmatch_lines(["*2 passed*"])
+ result = pytester.runpytest("--lf", "--lfnf", "all")
+ result.stdout.fnmatch_lines(["*2 passed*"])
+
+ # Ensure the list passed to pytest_deselected is a copy,
+ # and not a reference which is cleared right after.
+ pytester.makeconftest(
+ """
+ deselected = []
+
+ def pytest_deselected(items):
+ global deselected
+ deselected = items
+
+ def pytest_sessionfinish():
+ print("\\ndeselected={}".format(len(deselected)))
+ """
+ )
+
+ result = pytester.runpytest("--lf", "--lfnf", "none")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items / 2 deselected / 0 selected",
+ "run-last-failure: no previously failed tests, deselecting all items.",
+ "deselected=2",
+ "* 2 deselected in *",
+ ]
+ )
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+
+ def test_lastfailed_no_failures_behavior_empty_cache(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ """
+ def test_1(): pass
+ def test_2(): assert 0
+ """
+ )
+ result = pytester.runpytest("--lf", "--cache-clear")
+ result.stdout.fnmatch_lines(["*1 failed*1 passed*"])
+ result = pytester.runpytest("--lf", "--cache-clear", "--lfnf", "all")
+ result.stdout.fnmatch_lines(["*1 failed*1 passed*"])
+ result = pytester.runpytest("--lf", "--cache-clear", "--lfnf", "none")
+ result.stdout.fnmatch_lines(["*2 desel*"])
+
+ def test_lastfailed_skip_collection(self, pytester: Pytester) -> None:
+ """
+ Test --lf behavior regarding skipping collection of files that are not marked as
+ failed in the cache (#5172).
+ """
+ pytester.makepyfile(
+ **{
+ "pkg1/test_1.py": """
+ import pytest
+
+ @pytest.mark.parametrize('i', range(3))
+ def test_1(i): pass
+ """,
+ "pkg2/test_2.py": """
+ import pytest
+
+ @pytest.mark.parametrize('i', range(5))
+ def test_1(i):
+ assert i not in (1, 3)
+ """,
+ }
+ )
+ # first run: collects 8 items (test_1: 3, test_2: 5)
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 8 items", "*2 failed*6 passed*"])
+ # second run: collects only 5 items from test_2, because all tests from test_1 have passed
+ result = pytester.runpytest("--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "run-last-failure: rerun previous 2 failures (skipped 1 file)",
+ "*= 2 failed in *",
+ ]
+ )
+
+ # add another file and check if message is correct when skipping more than 1 file
+ pytester.makepyfile(
+ **{
+ "pkg1/test_3.py": """
+ def test_3(): pass
+ """
+ }
+ )
+ result = pytester.runpytest("--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "run-last-failure: rerun previous 2 failures (skipped 2 files)",
+ "*= 2 failed in *",
+ ]
+ )
+
+ def test_lastfailed_skip_collection_with_nesting(self, pytester: Pytester) -> None:
+ """Check that file skipping works even when the file with failures is
+ nested at a different level of the collection tree."""
+ pytester.makepyfile(
+ **{
+ "test_1.py": """
+ def test_1(): pass
+ """,
+ "pkg/__init__.py": "",
+ "pkg/test_2.py": """
+ def test_2(): assert False
+ """,
+ }
+ )
+ # first run
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 2 items", "*1 failed*1 passed*"])
+ # second run - test_1.py is skipped.
+ result = pytester.runpytest("--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "run-last-failure: rerun previous 1 failure (skipped 1 file)",
+ "*= 1 failed in *",
+ ]
+ )
+
+ def test_lastfailed_with_known_failures_not_being_selected(
+ self, pytester: Pytester
+ ) -> None:
+ pytester.makepyfile(
+ **{
+ "pkg1/test_1.py": """def test_1(): assert 0""",
+ "pkg1/test_2.py": """def test_2(): pass""",
+ }
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 2 items", "* 1 failed, 1 passed in *"])
+
+ Path("pkg1/test_1.py").unlink()
+ result = pytester.runpytest("--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "run-last-failure: 1 known failures not in selected tests",
+ "* 1 passed in *",
+ ]
+ )
+
+ # Recreate file with known failure.
+ pytester.makepyfile(**{"pkg1/test_1.py": """def test_1(): assert 0"""})
+ result = pytester.runpytest("--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "run-last-failure: rerun previous 1 failure (skipped 1 file)",
+ "* 1 failed in *",
+ ]
+ )
+
+ # Remove/rename test: collects the file again.
+ pytester.makepyfile(**{"pkg1/test_1.py": """def test_renamed(): assert 0"""})
+ result = pytester.runpytest("--lf", "-rf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "run-last-failure: 1 known failures not in selected tests",
+ "pkg1/test_1.py F *",
+ "pkg1/test_2.py . *",
+ "FAILED pkg1/test_1.py::test_renamed - assert 0",
+ "* 1 failed, 1 passed in *",
+ ]
+ )
+
+ result = pytester.runpytest("--lf", "--co")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "run-last-failure: rerun previous 1 failure (skipped 1 file)",
+ "",
+ "",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+
+ def test_lastfailed_args_with_deselected(self, pytester: Pytester) -> None:
+ """Test regression with --lf running into NoMatch error.
+
+ This was caused by it not collecting (non-failed) nodes given as
+ arguments.
+ """
+ pytester.makepyfile(
+ **{
+ "pkg1/test_1.py": """
+ def test_pass(): pass
+ def test_fail(): assert 0
+ """,
+ }
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 2 items", "* 1 failed, 1 passed in *"])
+ assert result.ret == 1
+
+ result = pytester.runpytest("pkg1/test_1.py::test_pass", "--lf", "--co")
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(
+ [
+ "*collected 1 item",
+ "run-last-failure: 1 known failures not in selected tests",
+ "",
+ "",
+ " ",
+ " ",
+ " ",
+ ],
+ consecutive=True,
+ )
+
+ result = pytester.runpytest(
+ "pkg1/test_1.py::test_pass", "pkg1/test_1.py::test_fail", "--lf", "--co"
+ )
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items / 1 deselected / 1 selected",
+ "run-last-failure: rerun previous 1 failure",
+ "",
+ "",
+ " ",
+ " ",
+ " ",
+ "*= 1/2 tests collected (1 deselected) in *",
+ ],
+ )
+
+ def test_lastfailed_with_class_items(self, pytester: Pytester) -> None:
+ """Test regression with --lf deselecting whole classes."""
+ pytester.makepyfile(
+ **{
+ "pkg1/test_1.py": """
+ class TestFoo:
+ def test_pass(self): pass
+ def test_fail(self): assert 0
+
+ def test_other(): assert 0
+ """,
+ }
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 3 items", "* 2 failed, 1 passed in *"])
+ assert result.ret == 1
+
+ result = pytester.runpytest("--lf", "--co")
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(
+ [
+ "collected 3 items / 1 deselected / 2 selected",
+ "run-last-failure: rerun previous 2 failures",
+ "",
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ "*= 2/3 tests collected (1 deselected) in *",
+ ],
+ consecutive=True,
+ )
+
+ def test_lastfailed_with_all_filtered(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ **{
+ "pkg1/test_1.py": """
+ def test_fail(): assert 0
+ def test_pass(): pass
+ """,
+ }
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 2 items", "* 1 failed, 1 passed in *"])
+ assert result.ret == 1
+
+ # Remove known failure.
+ pytester.makepyfile(
+ **{
+ "pkg1/test_1.py": """
+ def test_pass(): pass
+ """,
+ }
+ )
+ result = pytester.runpytest("--lf", "--co")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "run-last-failure: 1 known failures not in selected tests",
+ "",
+ "",
+ " ",
+ " ",
+ " ",
+ "",
+ "*= 1 test collected in*",
+ ],
+ consecutive=True,
+ )
+ assert result.ret == 0
+
+ def test_packages(self, pytester: Pytester) -> None:
+ """Regression test for #7758.
+
+ The particular issue here was that Package nodes were included in the
+ filtering, being themselves Modules for the __init__.py, even if they
+ had failed Modules in them.
+
+ The tests includes a test in an __init__.py file just to make sure the
+ fix doesn't somehow regress that, it is not critical for the issue.
+ """
+ pytester.makepyfile(
+ **{
+ "__init__.py": "",
+ "a/__init__.py": "def test_a_init(): assert False",
+ "a/test_one.py": "def test_1(): assert False",
+ "b/__init__.py": "",
+ "b/test_two.py": "def test_2(): assert False",
+ },
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ python_files = *.py
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(failed=3)
+ result = pytester.runpytest("--lf")
+ result.assert_outcomes(failed=3)
+
+ def test_non_python_file_skipped(
+ self,
+ pytester: Pytester,
+ dummy_yaml_custom_test: None,
+ ) -> None:
+ pytester.makepyfile(
+ **{
+ "test_bad.py": """def test_bad(): assert False""",
+ },
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 2 items", "* 1 failed, 1 passed in *"])
+
+ result = pytester.runpytest("--lf")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "run-last-failure: rerun previous 1 failure (skipped 1 file)",
+ "* 1 failed in *",
+ ]
+ )
+
+
+class TestNewFirst:
+ def test_newfirst_usecase(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ **{
+ "test_1/test_1.py": """
+ def test_1(): assert 1
+ """,
+ "test_2/test_2.py": """
+ def test_1(): assert 1
+ """,
+ }
+ )
+
+ p1 = pytester.path.joinpath("test_1/test_1.py")
+ os.utime(p1, ns=(p1.stat().st_atime_ns, int(1e9)))
+
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines(
+ ["*test_1/test_1.py::test_1 PASSED*", "*test_2/test_2.py::test_1 PASSED*"]
+ )
+
+ result = pytester.runpytest("-v", "--nf")
+ result.stdout.fnmatch_lines(
+ ["*test_2/test_2.py::test_1 PASSED*", "*test_1/test_1.py::test_1 PASSED*"]
+ )
+
+ p1.write_text(
+ "def test_1(): assert 1\ndef test_2(): assert 1\n", encoding="utf-8"
+ )
+ os.utime(p1, ns=(p1.stat().st_atime_ns, int(1e9)))
+
+ result = pytester.runpytest("--nf", "--collect-only", "-q")
+ result.stdout.fnmatch_lines(
+ [
+ "test_1/test_1.py::test_2",
+ "test_2/test_2.py::test_1",
+ "test_1/test_1.py::test_1",
+ ]
+ )
+
+ # Newest first with (plugin) pytest_collection_modifyitems hook.
+ pytester.makepyfile(
+ myplugin="""
+ def pytest_collection_modifyitems(items):
+ items[:] = sorted(items, key=lambda item: item.nodeid)
+ print("new_items:", [x.nodeid for x in items])
+ """
+ )
+ pytester.syspathinsert()
+ result = pytester.runpytest("--nf", "-p", "myplugin", "--collect-only", "-q")
+ result.stdout.fnmatch_lines(
+ [
+ "new_items: *test_1.py*test_1.py*test_2.py*",
+ "test_1/test_1.py::test_2",
+ "test_2/test_2.py::test_1",
+ "test_1/test_1.py::test_1",
+ ]
+ )
+
+ def test_newfirst_parametrize(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ **{
+ "test_1/test_1.py": """
+ import pytest
+ @pytest.mark.parametrize('num', [1, 2])
+ def test_1(num): assert num
+ """,
+ "test_2/test_2.py": """
+ import pytest
+ @pytest.mark.parametrize('num', [1, 2])
+ def test_1(num): assert num
+ """,
+ }
+ )
+
+ p1 = pytester.path.joinpath("test_1/test_1.py")
+ os.utime(p1, ns=(p1.stat().st_atime_ns, int(1e9)))
+
+ result = pytester.runpytest("-v")
+ result.stdout.fnmatch_lines(
+ [
+ "*test_1/test_1.py::test_1[1*",
+ "*test_1/test_1.py::test_1[2*",
+ "*test_2/test_2.py::test_1[1*",
+ "*test_2/test_2.py::test_1[2*",
+ ]
+ )
+
+ result = pytester.runpytest("-v", "--nf")
+ result.stdout.fnmatch_lines(
+ [
+ "*test_2/test_2.py::test_1[1*",
+ "*test_2/test_2.py::test_1[2*",
+ "*test_1/test_1.py::test_1[1*",
+ "*test_1/test_1.py::test_1[2*",
+ ]
+ )
+
+ p1.write_text(
+ "import pytest\n"
+ "@pytest.mark.parametrize('num', [1, 2, 3])\n"
+ "def test_1(num): assert num\n",
+ encoding="utf-8",
+ )
+ os.utime(p1, ns=(p1.stat().st_atime_ns, int(1e9)))
+
+ # Running only a subset does not forget about existing ones.
+ result = pytester.runpytest("-v", "--nf", "test_2/test_2.py")
+ result.stdout.fnmatch_lines(
+ ["*test_2/test_2.py::test_1[1*", "*test_2/test_2.py::test_1[2*"]
+ )
+
+ result = pytester.runpytest("-v", "--nf")
+ result.stdout.fnmatch_lines(
+ [
+ "*test_1/test_1.py::test_1[3*",
+ "*test_2/test_2.py::test_1[1*",
+ "*test_2/test_2.py::test_1[2*",
+ "*test_1/test_1.py::test_1[1*",
+ "*test_1/test_1.py::test_1[2*",
+ ]
+ )
+
+
+class TestReadme:
+ def check_readme(self, pytester: Pytester) -> bool:
+ config = pytester.parseconfigure()
+ assert config.cache is not None
+ readme = config.cache._cachedir.joinpath("README.md")
+ return readme.is_file()
+
+ def test_readme_passed(self, pytester: Pytester) -> None:
+ pytester.makepyfile("def test_always_passes(): pass")
+ pytester.runpytest()
+ assert self.check_readme(pytester) is True
+
+ def test_readme_failed(self, pytester: Pytester) -> None:
+ pytester.makepyfile("def test_always_fails(): assert 0")
+ pytester.runpytest()
+ assert self.check_readme(pytester) is True
+
+
+class Action(Enum):
+ """Action to perform on the cache directory."""
+
+ MKDIR = auto()
+ SET = auto()
+
+
+@pytest.mark.parametrize("action", list(Action))
+def test_gitignore(
+ pytester: Pytester,
+ action: Action,
+) -> None:
+ """Ensure we automatically create .gitignore file in the pytest_cache directory (#3286)."""
+ from _pytest.cacheprovider import Cache
+
+ config = pytester.parseconfig()
+ cache = Cache.for_config(config, _ispytest=True)
+ if action == Action.MKDIR:
+ cache.mkdir("foo")
+ elif action == Action.SET:
+ cache.set("foo", "bar")
+ else:
+ assert_never(action)
+ msg = "# Created by pytest automatically.\n*\n"
+ gitignore_path = cache._cachedir.joinpath(".gitignore")
+ assert gitignore_path.read_text(encoding="UTF-8") == msg
+
+ # Does not overwrite existing/custom one.
+ gitignore_path.write_text("custom", encoding="utf-8")
+ if action == Action.MKDIR:
+ cache.mkdir("something")
+ elif action == Action.SET:
+ cache.set("something", "else")
+ else:
+ assert_never(action)
+ assert gitignore_path.read_text(encoding="UTF-8") == "custom"
+
+
+def test_preserve_keys_order(pytester: Pytester) -> None:
+ """Ensure keys order is preserved when saving dicts (#9205)."""
+ from _pytest.cacheprovider import Cache
+
+ config = pytester.parseconfig()
+ cache = Cache.for_config(config, _ispytest=True)
+ cache.set("foo", {"z": 1, "b": 2, "a": 3, "d": 10})
+ read_back = cache.get("foo", None)
+ assert list(read_back.items()) == [("z", 1), ("b", 2), ("a", 3), ("d", 10)]
+
+
+def test_does_not_create_boilerplate_in_existing_dirs(pytester: Pytester) -> None:
+ from _pytest.cacheprovider import Cache
+
+ pytester.makeini(
+ """
+ [pytest]
+ cache_dir = .
+ """
+ )
+ config = pytester.parseconfig()
+ cache = Cache.for_config(config, _ispytest=True)
+ cache.set("foo", "bar")
+
+ assert os.path.isdir("v") # cache contents
+ assert not os.path.exists(".gitignore")
+ assert not os.path.exists("README.md")
+
+
+def test_cachedir_tag(pytester: Pytester) -> None:
+ """Ensure we automatically create CACHEDIR.TAG file in the pytest_cache directory (#4278)."""
+ from _pytest.cacheprovider import Cache
+ from _pytest.cacheprovider import CACHEDIR_FILES
+
+ config = pytester.parseconfig()
+ cache = Cache.for_config(config, _ispytest=True)
+ cache.set("foo", "bar")
+ cachedir_tag_path = cache._cachedir.joinpath("CACHEDIR.TAG")
+ assert cachedir_tag_path.read_bytes() == CACHEDIR_FILES["CACHEDIR.TAG"]
+
+
+def test_clioption_with_cacheshow_and_help(pytester: Pytester) -> None:
+ result = pytester.runpytest("--cache-show", "--help")
+ assert result.ret == 0
+
+
+def test_make_cachedir_cleans_up_on_base_exception(
+ tmp_path: Path,
+ monkeypatch: MonkeyPatch,
+) -> None:
+ """Ensure _make_cachedir cleans up the temp directory on BaseException.
+
+ When a BaseException (like KeyboardInterrupt) is raised during cache
+ directory creation, the temporary directory should be cleaned up before
+ re-raising the exception.
+ """
+ from _pytest.cacheprovider import _make_cachedir
+
+ target = tmp_path / ".pytest_cache"
+
+ def raise_keyboard_interrupt(self: Path, target: Path) -> None:
+ raise KeyboardInterrupt("simulated interrupt")
+
+ # Patch Path.rename only for the duration of the _make_cachedir call
+ with monkeypatch.context() as m:
+ m.setattr(Path, "rename", raise_keyboard_interrupt)
+
+ # Verify the exception is re-raised
+ with pytest.raises(KeyboardInterrupt, match="simulated interrupt"):
+ _make_cachedir(target)
+
+ # Verify no temp directories were left behind
+ temp_dirs = list(tmp_path.glob("pytest-cache-files-*"))
+ assert temp_dirs == [], f"Temp directories not cleaned up: {temp_dirs}"
+
+ # Verify the target directory was not created
+ assert not target.exists()
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_capture.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_capture.py
new file mode 100644
index 0000000000000000000000000000000000000000..7aaba99fe433c9808b63fe232eb5753228cd4a36
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_capture.py
@@ -0,0 +1,1752 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from collections.abc import Generator
+import contextlib
+import io
+from io import UnsupportedOperation
+import os
+import re
+import subprocess
+import sys
+import textwrap
+from typing import BinaryIO
+from typing import cast
+from typing import TextIO
+
+from _pytest import capture
+from _pytest.capture import _get_multicapture
+from _pytest.capture import CaptureFixture
+from _pytest.capture import CaptureManager
+from _pytest.capture import CaptureResult
+from _pytest.capture import MultiCapture
+from _pytest.config import ExitCode
+from _pytest.monkeypatch import MonkeyPatch
+from _pytest.pytester import Pytester
+import pytest
+
+
+# note: py.io capture tests where copied from
+# pylib 1.4.20.dev2 (rev 13d9af95547e)
+
+
+def StdCaptureFD(
+ out: bool = True, err: bool = True, in_: bool = True
+) -> MultiCapture[str]:
+ return capture.MultiCapture(
+ in_=capture.FDCapture(0) if in_ else None,
+ out=capture.FDCapture(1) if out else None,
+ err=capture.FDCapture(2) if err else None,
+ )
+
+
+def StdCapture(
+ out: bool = True, err: bool = True, in_: bool = True
+) -> MultiCapture[str]:
+ return capture.MultiCapture(
+ in_=capture.SysCapture(0) if in_ else None,
+ out=capture.SysCapture(1) if out else None,
+ err=capture.SysCapture(2) if err else None,
+ )
+
+
+def TeeStdCapture(
+ out: bool = True, err: bool = True, in_: bool = True
+) -> MultiCapture[str]:
+ return capture.MultiCapture(
+ in_=capture.SysCapture(0, tee=True) if in_ else None,
+ out=capture.SysCapture(1, tee=True) if out else None,
+ err=capture.SysCapture(2, tee=True) if err else None,
+ )
+
+
+class TestCaptureManager:
+ @pytest.mark.parametrize("method", ["no", "sys", "fd"])
+ def test_capturing_basic_api(self, method) -> None:
+ capouter = StdCaptureFD()
+ old = sys.stdout, sys.stderr, sys.stdin
+ try:
+ capman = CaptureManager(method)
+ capman.start_global_capturing()
+ capman.suspend_global_capture()
+ outerr = capman.read_global_capture()
+ assert outerr == ("", "")
+ capman.suspend_global_capture()
+ outerr = capman.read_global_capture()
+ assert outerr == ("", "")
+ print("hello")
+ capman.suspend_global_capture()
+ out, _err = capman.read_global_capture()
+ if method == "no":
+ assert old == (sys.stdout, sys.stderr, sys.stdin)
+ else:
+ assert not out
+ capman.resume_global_capture()
+ print("hello")
+ capman.suspend_global_capture()
+ out, _err = capman.read_global_capture()
+ if method != "no":
+ assert out == "hello\n"
+ capman.stop_global_capturing()
+ finally:
+ capouter.stop_capturing()
+
+ def test_init_capturing(self):
+ capouter = StdCaptureFD()
+ try:
+ capman = CaptureManager("fd")
+ capman.start_global_capturing()
+ with pytest.raises(AssertionError):
+ capman.start_global_capturing()
+ capman.stop_global_capturing()
+ finally:
+ capouter.stop_capturing()
+
+
+@pytest.mark.parametrize("method", ["fd", "sys"])
+def test_capturing_unicode(pytester: Pytester, method: str) -> None:
+ obj = "'b\u00f6y'"
+ pytester.makepyfile(
+ f"""\
+ # taken from issue 227 from nosetests
+ def test_unicode():
+ import sys
+ print(sys.stdout)
+ print({obj})
+ """
+ )
+ result = pytester.runpytest(f"--capture={method}")
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+
+@pytest.mark.parametrize("method", ["fd", "sys"])
+def test_capturing_bytes_in_utf8_encoding(pytester: Pytester, method: str) -> None:
+ pytester.makepyfile(
+ """\
+ def test_unicode():
+ print('b\\u00f6y')
+ """
+ )
+ result = pytester.runpytest(f"--capture={method}")
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+
+def test_collect_capturing(pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ import sys
+
+ print("collect %s failure" % 13)
+ sys.stderr.write("collect %s_stderr failure" % 13)
+ import xyz42123
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(
+ [
+ "*Captured stdout*",
+ "collect 13 failure",
+ "*Captured stderr*",
+ "collect 13_stderr failure",
+ ]
+ )
+
+
+class TestPerTestCapturing:
+ def test_capture_and_fixtures(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def setup_module(mod):
+ print("setup module")
+ def setup_function(function):
+ print("setup " + function.__name__)
+ def test_func1():
+ print("in func1")
+ assert 0
+ def test_func2():
+ print("in func2")
+ assert 0
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(
+ [
+ "setup module*",
+ "setup test_func1*",
+ "in func1*",
+ "setup test_func2*",
+ "in func2*",
+ ]
+ )
+
+ @pytest.mark.xfail(reason="unimplemented feature")
+ def test_capture_scope_cache(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ import sys
+ def setup_module(func):
+ print("module-setup")
+ def setup_function(func):
+ print("function-setup")
+ def test_func():
+ print("in function")
+ assert 0
+ def teardown_function(func):
+ print("in teardown")
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(
+ [
+ "*test_func():*",
+ "*Captured stdout during setup*",
+ "module-setup*",
+ "function-setup*",
+ "*Captured stdout*",
+ "in teardown*",
+ ]
+ )
+
+ def test_no_carry_over(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def test_func1():
+ print("in func1")
+ def test_func2():
+ print("in func2")
+ assert 0
+ """
+ )
+ result = pytester.runpytest(p)
+ s = result.stdout.str()
+ assert "in func1" not in s
+ assert "in func2" in s
+
+ def test_teardown_capturing(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def setup_function(function):
+ print("setup func1")
+ def teardown_function(function):
+ print("teardown func1")
+ assert 0
+ def test_func1():
+ print("in func1")
+ pass
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(
+ [
+ "*teardown_function*",
+ "*Captured stdout*",
+ "setup func1*",
+ "in func1*",
+ "teardown func1*",
+ # "*1 fixture failure*"
+ ]
+ )
+
+ def test_teardown_capturing_final(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def teardown_module(mod):
+ print("teardown module")
+ assert 0
+ def test_func():
+ pass
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(
+ [
+ "*def teardown_module(mod):*",
+ "*Captured stdout*",
+ "*teardown module*",
+ "*1 error*",
+ ]
+ )
+
+ def test_capturing_outerr(self, pytester: Pytester) -> None:
+ p1 = pytester.makepyfile(
+ """\
+ import sys
+ def test_capturing():
+ print(42)
+ sys.stderr.write(str(23))
+ def test_capturing_error():
+ print(1)
+ sys.stderr.write(str(2))
+ raise ValueError
+ """
+ )
+ result = pytester.runpytest(p1)
+ result.stdout.fnmatch_lines(
+ [
+ "*test_capturing_outerr.py .F*",
+ "====* FAILURES *====",
+ "____*____",
+ "*test_capturing_outerr.py:8: ValueError",
+ "*--- Captured stdout *call*",
+ "1",
+ "*--- Captured stderr *call*",
+ "2",
+ ]
+ )
+
+
+class TestLoggingInteraction:
+ def test_logging_stream_ownership(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """\
+ def test_logging():
+ import logging
+ import pytest
+ stream = capture.CaptureIO()
+ logging.basicConfig(stream=stream)
+ stream.close() # to free memory/release resources
+ """
+ )
+ result = pytester.runpytest_subprocess(p)
+ assert result.stderr.str().find("atexit") == -1
+
+ def test_logging_and_immediate_setupteardown(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """\
+ import logging
+ def setup_function(function):
+ logging.warning("hello1")
+
+ def test_logging():
+ logging.warning("hello2")
+ assert 0
+
+ def teardown_function(function):
+ logging.warning("hello3")
+ assert 0
+ """
+ )
+ for optargs in (("--capture=sys",), ("--capture=fd",)):
+ print(optargs)
+ result = pytester.runpytest_subprocess(p, *optargs)
+ s = result.stdout.str()
+ result.stdout.fnmatch_lines(
+ ["*WARN*hello3", "*WARN*hello1", "*WARN*hello2"] # errors show first!
+ )
+ # verify proper termination
+ assert "closed" not in s
+
+ def test_logging_and_crossscope_fixtures(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """\
+ import logging
+ def setup_module(function):
+ logging.warning("hello1")
+
+ def test_logging():
+ logging.warning("hello2")
+ assert 0
+
+ def teardown_module(function):
+ logging.warning("hello3")
+ assert 0
+ """
+ )
+ for optargs in (("--capture=sys",), ("--capture=fd",)):
+ print(optargs)
+ result = pytester.runpytest_subprocess(p, *optargs)
+ s = result.stdout.str()
+ result.stdout.fnmatch_lines(
+ ["*WARN*hello3", "*WARN*hello1", "*WARN*hello2"] # errors come first
+ )
+ # verify proper termination
+ assert "closed" not in s
+
+ def test_conftestlogging_is_shown(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """\
+ import logging
+ logging.basicConfig()
+ logging.warning("hello435")
+ """
+ )
+ # make sure that logging is still captured in tests
+ result = pytester.runpytest_subprocess("-s", "-p", "no:capturelog")
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+ result.stderr.fnmatch_lines(["WARNING*hello435*"])
+ assert "operation on closed file" not in result.stderr.str()
+
+ def test_conftestlogging_and_test_logging(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """\
+ import logging
+ logging.basicConfig()
+ """
+ )
+ # make sure that logging is still captured in tests
+ p = pytester.makepyfile(
+ """\
+ def test_hello():
+ import logging
+ logging.warning("hello433")
+ assert 0
+ """
+ )
+ result = pytester.runpytest_subprocess(p, "-p", "no:capturelog")
+ assert result.ret != 0
+ result.stdout.fnmatch_lines(["WARNING*hello433*"])
+ assert "something" not in result.stderr.str()
+ assert "operation on closed file" not in result.stderr.str()
+
+ def test_logging_after_cap_stopped(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """\
+ import pytest
+ import logging
+
+ log = logging.getLogger(__name__)
+
+ @pytest.fixture
+ def log_on_teardown():
+ yield
+ log.warning('Logging on teardown')
+ """
+ )
+ # make sure that logging is still captured in tests
+ p = pytester.makepyfile(
+ """\
+ def test_hello(log_on_teardown):
+ import logging
+ logging.warning("hello433")
+ assert 1
+ raise KeyboardInterrupt()
+ """
+ )
+ result = pytester.runpytest_subprocess(p, "--log-cli-level", "info")
+ assert result.ret != 0
+ result.stdout.fnmatch_lines(
+ ["*WARNING*hello433*", "*WARNING*Logging on teardown*"]
+ )
+ assert (
+ "AttributeError: 'NoneType' object has no attribute 'resume_capturing'"
+ not in result.stderr.str()
+ )
+
+
+class TestCaptureFixture:
+ @pytest.mark.parametrize("opt", [[], ["-s"]])
+ def test_std_functional(self, pytester: Pytester, opt) -> None:
+ reprec = pytester.inline_runsource(
+ """\
+ def test_hello(capsys):
+ print(42)
+ out, err = capsys.readouterr()
+ assert out.startswith("42")
+ """,
+ *opt,
+ )
+ reprec.assertoutcome(passed=1)
+
+ def test_capteesys(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """\
+ import sys
+ def test_one(capteesys):
+ print("sTdoUt")
+ print("sTdeRr", file=sys.stderr)
+ out, err = capteesys.readouterr()
+ assert out == "sTdoUt\\n"
+ assert err == "sTdeRr\\n"
+ """
+ )
+ # -rN and --capture=tee-sys means we'll read them on stdout/stderr,
+ # as opposed to both being reported on stdout
+ result = pytester.runpytest(p, "--quiet", "--quiet", "-rN", "--capture=tee-sys")
+ assert result.ret == ExitCode.OK
+ result.stdout.fnmatch_lines(["sTdoUt"]) # tee'd out
+ result.stderr.fnmatch_lines(["sTdeRr"]) # tee'd out
+
+ result = pytester.runpytest(p, "--quiet", "--quiet", "-rA", "--capture=tee-sys")
+ assert result.ret == ExitCode.OK
+ result.stdout.fnmatch_lines(
+ ["sTdoUt", "sTdoUt", "sTdeRr"]
+ ) # tee'd out, the next two reported
+ result.stderr.fnmatch_lines(["sTdeRr"]) # tee'd out
+
+ # -rA and --capture=sys means we'll read them on stdout.
+ result = pytester.runpytest(p, "--quiet", "--quiet", "-rA", "--capture=sys")
+ assert result.ret == ExitCode.OK
+ result.stdout.fnmatch_lines(["sTdoUt", "sTdeRr"]) # no tee, just reported
+ assert not result.stderr.lines
+
+ def test_capsyscapfd(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """\
+ def test_one(capsys, capfd):
+ pass
+ def test_two(capfd, capsys):
+ pass
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(
+ [
+ "*ERROR*setup*test_one*",
+ "E*capfd*capsys*same*time*",
+ "*ERROR*setup*test_two*",
+ "E*capsys*capfd*same*time*",
+ "*2 errors*",
+ ]
+ )
+
+ def test_capturing_getfixturevalue(self, pytester: Pytester) -> None:
+ """Test that asking for "capfd" and "capsys" using request.getfixturevalue
+ in the same test is an error.
+ """
+ pytester.makepyfile(
+ """\
+ def test_one(capsys, request):
+ request.getfixturevalue("capfd")
+ def test_two(capfd, request):
+ request.getfixturevalue("capsys")
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*test_one*",
+ "E * cannot use capfd and capsys at the same time",
+ "*test_two*",
+ "E * cannot use capsys and capfd at the same time",
+ "*2 failed in*",
+ ]
+ )
+
+ def test_capsyscapfdbinary(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """\
+ def test_one(capsys, capfdbinary):
+ pass
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(
+ ["*ERROR*setup*test_one*", "E*capfdbinary*capsys*same*time*", "*1 error*"]
+ )
+
+ @pytest.mark.parametrize("method", ["sys", "fd"])
+ def test_capture_is_represented_on_failure_issue128(
+ self, pytester: Pytester, method
+ ) -> None:
+ p = pytester.makepyfile(
+ f"""\
+ def test_hello(cap{method}):
+ print("xxx42xxx")
+ assert 0
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(["xxx42xxx"])
+
+ def test_stdfd_functional(self, pytester: Pytester) -> None:
+ reprec = pytester.inline_runsource(
+ """\
+ def test_hello(capfd):
+ import os
+ os.write(1, b"42")
+ out, err = capfd.readouterr()
+ assert out.startswith("42")
+ capfd.close()
+ """
+ )
+ reprec.assertoutcome(passed=1)
+
+ @pytest.mark.parametrize("nl", ("\n", "\r\n", "\r"))
+ def test_cafd_preserves_newlines(self, capfd, nl) -> None:
+ print("test", end=nl)
+ out, _err = capfd.readouterr()
+ assert out.endswith(nl)
+
+ def test_capfdbinary(self, pytester: Pytester) -> None:
+ reprec = pytester.inline_runsource(
+ """\
+ def test_hello(capfdbinary):
+ import os
+ # some likely un-decodable bytes
+ os.write(1, b'\\xfe\\x98\\x20')
+ out, err = capfdbinary.readouterr()
+ assert out == b'\\xfe\\x98\\x20'
+ assert err == b''
+ """
+ )
+ reprec.assertoutcome(passed=1)
+
+ def test_capsysbinary(self, pytester: Pytester) -> None:
+ p1 = pytester.makepyfile(
+ r"""
+ def test_hello(capsysbinary):
+ import sys
+
+ sys.stdout.buffer.write(b'hello')
+
+ # Some likely un-decodable bytes.
+ sys.stdout.buffer.write(b'\xfe\x98\x20')
+
+ sys.stdout.buffer.flush()
+
+ # Ensure writing in text mode still works and is captured.
+ # https://github.com/pytest-dev/pytest/issues/6871
+ print("world", flush=True)
+
+ out, err = capsysbinary.readouterr()
+ assert out == b'hello\xfe\x98\x20world\n'
+ assert err == b''
+
+ print("stdout after")
+ print("stderr after", file=sys.stderr)
+ """
+ )
+ result = pytester.runpytest(str(p1), "-rA")
+ result.stdout.fnmatch_lines(
+ [
+ "*- Captured stdout call -*",
+ "stdout after",
+ "*- Captured stderr call -*",
+ "stderr after",
+ "*= 1 passed in *",
+ ]
+ )
+
+ def test_partial_setup_failure(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """\
+ def test_hello(capsys, missingarg):
+ pass
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(["*test_partial_setup_failure*", "*1 error*"])
+
+ def test_keyboardinterrupt_disables_capturing(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """\
+ def test_hello(capfd):
+ import os
+ os.write(1, b'42')
+ raise KeyboardInterrupt()
+ """
+ )
+ result = pytester.runpytest_subprocess(p)
+ result.stdout.fnmatch_lines(["*KeyboardInterrupt*"])
+ assert result.ret == 2
+
+ def test_capture_and_logging(self, pytester: Pytester) -> None:
+ """#14"""
+ p = pytester.makepyfile(
+ """\
+ import logging
+ def test_log(capsys):
+ logging.error('x')
+ """
+ )
+ result = pytester.runpytest_subprocess(p)
+ assert "closed" not in result.stderr.str()
+
+ @pytest.mark.parametrize("fixture", ["capsys", "capfd"])
+ @pytest.mark.parametrize("no_capture", [True, False])
+ def test_disabled_capture_fixture(
+ self, pytester: Pytester, fixture: str, no_capture: bool
+ ) -> None:
+ pytester.makepyfile(
+ f"""\
+ def test_disabled({fixture}):
+ print('captured before')
+ with {fixture}.disabled():
+ print('while capture is disabled')
+ print('captured after')
+ assert {fixture}.readouterr() == ('captured before\\ncaptured after\\n', '')
+
+ def test_normal():
+ print('test_normal executed')
+ """
+ )
+ args = ("-s",) if no_capture else ()
+ result = pytester.runpytest_subprocess(*args)
+ result.stdout.fnmatch_lines(["*while capture is disabled*", "*= 2 passed in *"])
+ result.stdout.no_fnmatch_line("*captured before*")
+ result.stdout.no_fnmatch_line("*captured after*")
+ if no_capture:
+ assert "test_normal executed" in result.stdout.str()
+ else:
+ result.stdout.no_fnmatch_line("*test_normal executed*")
+
+ def test_disabled_capture_fixture_twice(self, pytester: Pytester) -> None:
+ """Test that an inner disabled() exit doesn't undo an outer disabled().
+
+ Issue #7148.
+ """
+ pytester.makepyfile(
+ """
+ def test_disabled(capfd):
+ print('captured before')
+ with capfd.disabled():
+ print('while capture is disabled 1')
+ with capfd.disabled():
+ print('while capture is disabled 2')
+ print('while capture is disabled 1 after')
+ print('captured after')
+ assert capfd.readouterr() == ('captured before\\ncaptured after\\n', '')
+ """
+ )
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(
+ [
+ "*while capture is disabled 1",
+ "*while capture is disabled 2",
+ "*while capture is disabled 1 after",
+ ],
+ consecutive=True,
+ )
+
+ @pytest.mark.parametrize("fixture", ["capsys", "capfd"])
+ def test_fixture_use_by_other_fixtures(self, pytester: Pytester, fixture) -> None:
+ """Ensure that capsys and capfd can be used by other fixtures during
+ setup and teardown."""
+ pytester.makepyfile(
+ f"""\
+ import sys
+ import pytest
+
+ @pytest.fixture
+ def captured_print({fixture}):
+ print('stdout contents begin')
+ print('stderr contents begin', file=sys.stderr)
+ out, err = {fixture}.readouterr()
+
+ yield out, err
+
+ print('stdout contents end')
+ print('stderr contents end', file=sys.stderr)
+ out, err = {fixture}.readouterr()
+ assert out == 'stdout contents end\\n'
+ assert err == 'stderr contents end\\n'
+
+ def test_captured_print(captured_print):
+ out, err = captured_print
+ assert out == 'stdout contents begin\\n'
+ assert err == 'stderr contents begin\\n'
+ """
+ )
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(["*1 passed*"])
+ result.stdout.no_fnmatch_line("*stdout contents begin*")
+ result.stdout.no_fnmatch_line("*stderr contents begin*")
+
+ @pytest.mark.parametrize("cap", ["capsys", "capfd"])
+ def test_fixture_use_by_other_fixtures_teardown(
+ self, pytester: Pytester, cap
+ ) -> None:
+ """Ensure we can access setup and teardown buffers from teardown when using capsys/capfd (##3033)"""
+ pytester.makepyfile(
+ f"""\
+ import sys
+ import pytest
+ import os
+
+ @pytest.fixture()
+ def fix({cap}):
+ print("setup out")
+ sys.stderr.write("setup err\\n")
+ yield
+ out, err = {cap}.readouterr()
+ assert out == 'setup out\\ncall out\\n'
+ assert err == 'setup err\\ncall err\\n'
+
+ def test_a(fix):
+ print("call out")
+ sys.stderr.write("call err\\n")
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+
+def test_setup_failure_does_not_kill_capturing(pytester: Pytester) -> None:
+ sub1 = pytester.mkpydir("sub1")
+ sub1.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ def pytest_runtest_setup(item):
+ raise ValueError(42)
+ """
+ ),
+ encoding="utf-8",
+ )
+ sub1.joinpath("test_mod.py").write_text("def test_func1(): pass", encoding="utf-8")
+ result = pytester.runpytest(pytester.path, "--traceconfig")
+ result.stdout.fnmatch_lines(["*ValueError(42)*", "*1 error*"])
+
+
+def test_capture_conftest_runtest_setup(pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ def pytest_runtest_setup():
+ print("hello19")
+ """
+ )
+ pytester.makepyfile("def test_func(): pass")
+ result = pytester.runpytest()
+ assert result.ret == 0
+ result.stdout.no_fnmatch_line("*hello19*")
+
+
+def test_capture_badoutput_issue412(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import os
+
+ def test_func():
+ omg = bytearray([1,129,1])
+ os.write(1, omg)
+ assert 0
+ """
+ )
+ result = pytester.runpytest("--capture=fd")
+ result.stdout.fnmatch_lines(
+ """
+ *def test_func*
+ *assert 0*
+ *Captured*
+ *1 failed*
+ """
+ )
+
+
+def test_capture_early_option_parsing(pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ def pytest_runtest_setup():
+ print("hello19")
+ """
+ )
+ pytester.makepyfile("def test_func(): pass")
+ result = pytester.runpytest("-vs")
+ assert result.ret == 0
+ assert "hello19" in result.stdout.str()
+
+
+def test_capture_binary_output(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ r"""
+ import pytest
+
+ def test_a():
+ import sys
+ import subprocess
+ subprocess.call([sys.executable, __file__])
+
+ def test_foo():
+ import os;os.write(1, b'\xc3')
+
+ if __name__ == '__main__':
+ test_foo()
+ """
+ )
+ result = pytester.runpytest("--assert=plain")
+ result.assert_outcomes(passed=2)
+
+
+def test_error_during_readouterr(pytester: Pytester) -> None:
+ """Make sure we suspend capturing if errors occur during readouterr"""
+ pytester.makepyfile(
+ pytest_xyz="""
+ from _pytest.capture import FDCapture
+
+ def bad_snap(self):
+ raise Exception('boom')
+
+ assert FDCapture.snap
+ FDCapture.snap = bad_snap
+ """
+ )
+ result = pytester.runpytest_subprocess("-p", "pytest_xyz")
+ result.stderr.fnmatch_lines(
+ ["*in bad_snap", " raise Exception('boom')", "Exception: boom"]
+ )
+
+
+class TestCaptureIO:
+ def test_text(self) -> None:
+ f = capture.CaptureIO()
+ f.write("hello")
+ s = f.getvalue()
+ assert s == "hello"
+ f.close()
+
+ def test_unicode_and_str_mixture(self) -> None:
+ f = capture.CaptureIO()
+ f.write("\u00f6")
+ with pytest.raises(TypeError):
+ f.write(b"hello") # type: ignore[arg-type]
+
+ def test_write_bytes_to_buffer(self) -> None:
+ """In python3, stdout / stderr are text io wrappers (exposing a buffer
+ property of the underlying bytestream). See issue #1407
+ """
+ f = capture.CaptureIO()
+ f.buffer.write(b"foo\r\n")
+ assert f.getvalue() == "foo\r\n"
+
+
+class TestTeeCaptureIO(TestCaptureIO):
+ def test_text(self) -> None:
+ sio = io.StringIO()
+ f = capture.TeeCaptureIO(sio)
+ f.write("hello")
+ s1 = f.getvalue()
+ assert s1 == "hello"
+ s2 = sio.getvalue()
+ assert s2 == s1
+ f.close()
+ sio.close()
+
+ def test_unicode_and_str_mixture(self) -> None:
+ sio = io.StringIO()
+ f = capture.TeeCaptureIO(sio)
+ f.write("\u00f6")
+ with pytest.raises(TypeError):
+ f.write(b"hello") # type: ignore[arg-type]
+
+
+def test_dontreadfrominput() -> None:
+ from _pytest.capture import DontReadFromInput
+
+ f = DontReadFromInput()
+ assert f.buffer is f # type: ignore[comparison-overlap]
+ assert not f.isatty() # type: ignore[unreachable]
+ with pytest.raises(OSError):
+ f.read()
+ with pytest.raises(OSError):
+ f.readlines()
+ iter_f = iter(f)
+ with pytest.raises(OSError):
+ next(iter_f)
+ with pytest.raises(UnsupportedOperation):
+ f.fileno()
+ with pytest.raises(UnsupportedOperation):
+ f.flush()
+ assert not f.readable()
+ with pytest.raises(UnsupportedOperation):
+ f.seek(0)
+ assert not f.seekable()
+ with pytest.raises(UnsupportedOperation):
+ f.tell()
+ with pytest.raises(UnsupportedOperation):
+ f.truncate(0)
+ with pytest.raises(UnsupportedOperation):
+ f.write(b"")
+ with pytest.raises(UnsupportedOperation):
+ f.writelines([])
+ assert not f.writable()
+ assert isinstance(f.encoding, str)
+ f.close() # just for completeness
+ with f:
+ pass
+
+
+def test_captureresult() -> None:
+ cr = CaptureResult("out", "err")
+ assert len(cr) == 2
+ assert cr.out == "out"
+ assert cr.err == "err"
+ out, err = cr
+ assert out == "out"
+ assert err == "err"
+ assert cr[0] == "out"
+ assert cr[1] == "err"
+ assert cr == cr
+ assert cr == CaptureResult("out", "err")
+ assert cr != CaptureResult("wrong", "err")
+ assert cr == ("out", "err")
+ assert cr != ("out", "wrong")
+ assert hash(cr) == hash(CaptureResult("out", "err"))
+ assert hash(cr) == hash(("out", "err"))
+ assert hash(cr) != hash(("out", "wrong"))
+ assert cr < ("z",)
+ assert cr < ("z", "b")
+ assert cr < ("z", "b", "c")
+ assert cr.count("err") == 1
+ assert cr.count("wrong") == 0
+ assert cr.index("err") == 1
+ with pytest.raises(ValueError):
+ assert cr.index("wrong") == 0
+ assert next(iter(cr)) == "out"
+ assert cr._replace(err="replaced") == ("out", "replaced")
+
+
+@pytest.fixture
+def tmpfile(pytester: Pytester) -> Generator[BinaryIO]:
+ f = pytester.makepyfile("").open("wb+")
+ yield f
+ if not f.closed:
+ f.close()
+
+
+@contextlib.contextmanager
+def lsof_check():
+ pid = os.getpid()
+ try:
+ out = subprocess.check_output(("lsof", "-p", str(pid)), timeout=10).decode()
+ except (
+ OSError,
+ UnicodeDecodeError,
+ subprocess.CalledProcessError,
+ subprocess.TimeoutExpired,
+ ) as exc:
+ # about UnicodeDecodeError, see note on pytester
+ pytest.skip(f"could not run 'lsof' ({exc!r})")
+ yield
+ out2 = subprocess.check_output(("lsof", "-p", str(pid))).decode()
+ len1 = len([x for x in out.split("\n") if "REG" in x])
+ len2 = len([x for x in out2.split("\n") if "REG" in x])
+ assert len2 < len1 + 3, out2
+
+
+class TestFDCapture:
+ def test_simple(self, tmpfile: BinaryIO) -> None:
+ fd = tmpfile.fileno()
+ cap = capture.FDCapture(fd)
+ data = b"hello"
+ os.write(fd, data)
+ with pytest.raises(AssertionError):
+ cap.snap()
+ cap.done()
+ cap = capture.FDCapture(fd)
+ cap.start()
+ os.write(fd, data)
+ s = cap.snap()
+ cap.done()
+ assert s == "hello"
+
+ def test_simple_many(self, tmpfile: BinaryIO) -> None:
+ for i in range(10):
+ self.test_simple(tmpfile)
+
+ def test_simple_many_check_open_files(self, pytester: Pytester) -> None:
+ with lsof_check():
+ with pytester.makepyfile("").open("wb+") as tmpfile:
+ self.test_simple_many(tmpfile)
+
+ def test_simple_fail_second_start(self, tmpfile: BinaryIO) -> None:
+ fd = tmpfile.fileno()
+ cap = capture.FDCapture(fd)
+ cap.done()
+ with pytest.raises(AssertionError):
+ cap.start()
+
+ def test_stderr(self) -> None:
+ cap = capture.FDCapture(2)
+ cap.start()
+ print("hello", file=sys.stderr)
+ s = cap.snap()
+ cap.done()
+ assert s == "hello\n"
+
+ def test_stdin(self) -> None:
+ cap = capture.FDCapture(0)
+ cap.start()
+ x = os.read(0, 100).strip()
+ cap.done()
+ assert x == b""
+
+ def test_writeorg(self, tmpfile: BinaryIO) -> None:
+ data1, data2 = b"foo", b"bar"
+ cap = capture.FDCapture(tmpfile.fileno())
+ cap.start()
+ tmpfile.write(data1)
+ tmpfile.flush()
+ cap.writeorg(data2.decode("ascii"))
+ scap = cap.snap()
+ cap.done()
+ assert scap == data1.decode("ascii")
+ with open(tmpfile.name, "rb") as stmp_file:
+ stmp = stmp_file.read()
+ assert stmp == data2
+
+ def test_simple_resume_suspend(self) -> None:
+ with saved_fd(1):
+ cap = capture.FDCapture(1)
+ cap.start()
+ data = b"hello"
+ os.write(1, data)
+ sys.stdout.write("whatever")
+ s = cap.snap()
+ assert s == "hellowhatever"
+ cap.suspend()
+ os.write(1, b"world")
+ sys.stdout.write("qlwkej")
+ assert not cap.snap()
+ cap.resume()
+ os.write(1, b"but now")
+ sys.stdout.write(" yes\n")
+ s = cap.snap()
+ assert s == "but now yes\n"
+ cap.suspend()
+ cap.done()
+ with pytest.raises(AssertionError):
+ cap.suspend()
+
+ assert repr(cap) == (
+ f""
+ )
+ # Should not crash with missing "_old".
+ assert isinstance(cap.syscapture, capture.SysCapture)
+ assert repr(cap.syscapture) == (
+ f" _state='done' tmpfile={cap.syscapture.tmpfile!r}>"
+ )
+
+ def test_capfd_sys_stdout_mode(self, capfd) -> None:
+ assert "b" not in sys.stdout.mode
+
+
+@contextlib.contextmanager
+def saved_fd(fd):
+ new_fd = os.dup(fd)
+ try:
+ yield
+ finally:
+ os.dup2(new_fd, fd)
+ os.close(new_fd)
+
+
+class TestStdCapture:
+ captureclass = staticmethod(StdCapture)
+
+ @contextlib.contextmanager
+ def getcapture(self, **kw):
+ cap = self.__class__.captureclass(**kw)
+ cap.start_capturing()
+ try:
+ yield cap
+ finally:
+ cap.stop_capturing()
+
+ def test_capturing_done_simple(self) -> None:
+ with self.getcapture() as cap:
+ sys.stdout.write("hello")
+ sys.stderr.write("world")
+ out, err = cap.readouterr()
+ assert out == "hello"
+ assert err == "world"
+
+ def test_capturing_reset_simple(self) -> None:
+ with self.getcapture() as cap:
+ print("hello world")
+ sys.stderr.write("hello error\n")
+ out, err = cap.readouterr()
+ assert out == "hello world\n"
+ assert err == "hello error\n"
+
+ def test_capturing_readouterr(self) -> None:
+ with self.getcapture() as cap:
+ print("hello world")
+ sys.stderr.write("hello error\n")
+ out, err = cap.readouterr()
+ assert out == "hello world\n"
+ assert err == "hello error\n"
+ sys.stderr.write("error2")
+ out, err = cap.readouterr()
+ assert err == "error2"
+
+ def test_capture_results_accessible_by_attribute(self) -> None:
+ with self.getcapture() as cap:
+ sys.stdout.write("hello")
+ sys.stderr.write("world")
+ capture_result = cap.readouterr()
+ assert capture_result.out == "hello"
+ assert capture_result.err == "world"
+
+ def test_capturing_readouterr_unicode(self) -> None:
+ with self.getcapture() as cap:
+ print("hxąć")
+ out, _err = cap.readouterr()
+ assert out == "hxąć\n"
+
+ def test_reset_twice_error(self) -> None:
+ with self.getcapture() as cap:
+ print("hello")
+ out, err = cap.readouterr()
+ with pytest.raises(ValueError):
+ cap.stop_capturing()
+ assert out == "hello\n"
+ assert not err
+
+ def test_capturing_modify_sysouterr_in_between(self) -> None:
+ oldout = sys.stdout
+ olderr = sys.stderr
+ with self.getcapture() as cap:
+ sys.stdout.write("hello")
+ sys.stderr.write("world")
+ sys.stdout = capture.CaptureIO()
+ sys.stderr = capture.CaptureIO()
+ print("not seen")
+ sys.stderr.write("not seen\n")
+ out, err = cap.readouterr()
+ assert out == "hello"
+ assert err == "world"
+ assert sys.stdout == oldout
+ assert sys.stderr == olderr
+
+ def test_capturing_error_recursive(self) -> None:
+ with self.getcapture() as cap1:
+ print("cap1")
+ with self.getcapture() as cap2:
+ print("cap2")
+ out2, _err2 = cap2.readouterr()
+ out1, _err1 = cap1.readouterr()
+ assert out1 == "cap1\n"
+ assert out2 == "cap2\n"
+
+ def test_just_out_capture(self) -> None:
+ with self.getcapture(out=True, err=False) as cap:
+ sys.stdout.write("hello")
+ sys.stderr.write("world")
+ out, err = cap.readouterr()
+ assert out == "hello"
+ assert not err
+
+ def test_just_err_capture(self) -> None:
+ with self.getcapture(out=False, err=True) as cap:
+ sys.stdout.write("hello")
+ sys.stderr.write("world")
+ out, err = cap.readouterr()
+ assert err == "world"
+ assert not out
+
+ def test_stdin_restored(self) -> None:
+ old = sys.stdin
+ with self.getcapture(in_=True):
+ newstdin = sys.stdin
+ assert newstdin != sys.stdin
+ assert sys.stdin is old
+
+ def test_stdin_nulled_by_default(self) -> None:
+ print("XXX this test may well hang instead of crashing")
+ print("XXX which indicates an error in the underlying capturing")
+ print("XXX mechanisms")
+ with self.getcapture():
+ with pytest.raises(OSError):
+ sys.stdin.read()
+
+
+class TestTeeStdCapture(TestStdCapture):
+ captureclass = staticmethod(TeeStdCapture)
+
+ def test_capturing_error_recursive(self) -> None:
+ r"""For TeeStdCapture since we passthrough stderr/stdout, cap1
+ should get all output, while cap2 should only get "cap2\n"."""
+ with self.getcapture() as cap1:
+ print("cap1")
+ with self.getcapture() as cap2:
+ print("cap2")
+ out2, _err2 = cap2.readouterr()
+ out1, _err1 = cap1.readouterr()
+ assert out1 == "cap1\ncap2\n"
+ assert out2 == "cap2\n"
+
+
+class TestStdCaptureFD(TestStdCapture):
+ captureclass = staticmethod(StdCaptureFD)
+
+ def test_simple_only_fd(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """\
+ import os
+ def test_x():
+ os.write(1, b"hello\\n")
+ assert 0
+ """
+ )
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(
+ """
+ *test_x*
+ *assert 0*
+ *Captured stdout*
+ """
+ )
+
+ def test_intermingling(self):
+ with self.getcapture() as cap:
+ os.write(1, b"1")
+ sys.stdout.write(str(2))
+ sys.stdout.flush()
+ os.write(1, b"3")
+ os.write(2, b"a")
+ sys.stderr.write("b")
+ sys.stderr.flush()
+ os.write(2, b"c")
+ out, err = cap.readouterr()
+ assert out == "123"
+ assert err == "abc"
+
+ def test_many(self, capfd):
+ with lsof_check():
+ for i in range(10):
+ cap = StdCaptureFD()
+ cap.start_capturing()
+ cap.stop_capturing()
+
+
+class TestStdCaptureFDinvalidFD:
+ def test_stdcapture_fd_invalid_fd(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import os
+ from fnmatch import fnmatch
+ from _pytest import capture
+
+ def StdCaptureFD(out=True, err=True, in_=True):
+ return capture.MultiCapture(
+ in_=capture.FDCapture(0) if in_ else None,
+ out=capture.FDCapture(1) if out else None,
+ err=capture.FDCapture(2) if err else None,
+ )
+
+ def test_stdout():
+ os.close(1)
+ cap = StdCaptureFD(out=True, err=False, in_=False)
+ assert fnmatch(repr(cap.out), "")
+ cap.start_capturing()
+ os.write(1, b"stdout")
+ assert cap.readouterr() == ("stdout", "")
+ cap.stop_capturing()
+
+ def test_stderr():
+ os.close(2)
+ cap = StdCaptureFD(out=False, err=True, in_=False)
+ assert fnmatch(repr(cap.err), "")
+ cap.start_capturing()
+ os.write(2, b"stderr")
+ assert cap.readouterr() == ("", "stderr")
+ cap.stop_capturing()
+
+ def test_stdin():
+ os.close(0)
+ cap = StdCaptureFD(out=False, err=False, in_=True)
+ assert fnmatch(repr(cap.in_), "")
+ cap.stop_capturing()
+ """
+ )
+ result = pytester.runpytest_subprocess("--capture=fd")
+ assert result.ret == 0
+ assert result.parseoutcomes()["passed"] == 3
+
+ def test_fdcapture_invalid_fd_with_fd_reuse(self, pytester: Pytester) -> None:
+ with saved_fd(1):
+ os.close(1)
+ cap = capture.FDCaptureBinary(1)
+ cap.start()
+ os.write(1, b"started")
+ cap.suspend()
+ os.write(1, b" suspended")
+ cap.resume()
+ os.write(1, b" resumed")
+ assert cap.snap() == b"started resumed"
+ cap.done()
+ with pytest.raises(OSError):
+ os.write(1, b"done")
+
+ def test_fdcapture_invalid_fd_without_fd_reuse(self, pytester: Pytester) -> None:
+ with saved_fd(1), saved_fd(2):
+ os.close(1)
+ os.close(2)
+ cap = capture.FDCaptureBinary(2)
+ cap.start()
+ os.write(2, b"started")
+ cap.suspend()
+ os.write(2, b" suspended")
+ cap.resume()
+ os.write(2, b" resumed")
+ assert cap.snap() == b"started resumed"
+ cap.done()
+ with pytest.raises(OSError):
+ os.write(2, b"done")
+
+
+def test_capture_not_started_but_reset() -> None:
+ capsys = StdCapture()
+ capsys.stop_capturing()
+
+
+def test_using_capsys_fixture_works_with_sys_stdout_encoding(
+ capsys: CaptureFixture[str],
+) -> None:
+ test_text = "test text"
+
+ print(test_text.encode(sys.stdout.encoding, "replace"))
+ (out, err) = capsys.readouterr()
+ assert out
+ assert err == ""
+
+
+def test_capsys_results_accessible_by_attribute(capsys: CaptureFixture[str]) -> None:
+ sys.stdout.write("spam")
+ sys.stderr.write("eggs")
+ capture_result = capsys.readouterr()
+ assert capture_result.out == "spam"
+ assert capture_result.err == "eggs"
+
+
+def test_fdcapture_tmpfile_remains_the_same() -> None:
+ cap = StdCaptureFD(out=False, err=True)
+ assert isinstance(cap.err, capture.FDCapture)
+ try:
+ cap.start_capturing()
+ capfile = cap.err.tmpfile
+ cap.readouterr()
+ finally:
+ cap.stop_capturing()
+ capfile2 = cap.err.tmpfile
+ assert capfile2 == capfile
+
+
+def test_close_and_capture_again(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import os
+ def test_close():
+ os.close(1)
+ def test_capture_again():
+ os.write(1, b"hello\\n")
+ assert 0
+ """
+ )
+ result = pytester.runpytest_subprocess()
+ result.stdout.fnmatch_lines(
+ """
+ *test_capture_again*
+ *assert 0*
+ *stdout*
+ *hello*
+ """
+ )
+
+
+@pytest.mark.parametrize(
+ "method", ["SysCapture(2)", "SysCapture(2, tee=True)", "FDCapture(2)"]
+)
+def test_capturing_and_logging_fundamentals(pytester: Pytester, method: str) -> None:
+ # here we check a fundamental feature
+ p = pytester.makepyfile(
+ f"""
+ import sys, os, logging
+ from _pytest import capture
+ cap = capture.MultiCapture(
+ in_=None,
+ out=None,
+ err=capture.{method},
+ )
+ cap.start_capturing()
+
+ logging.warning("hello1")
+ outerr = cap.readouterr()
+ print("suspend, captured %s" %(outerr,))
+ logging.warning("hello2")
+
+ cap.pop_outerr_to_orig()
+ logging.warning("hello3")
+
+ outerr = cap.readouterr()
+ print("suspend2, captured %s" % (outerr,))
+ """
+ )
+ result = pytester.runpython(p)
+ result.stdout.fnmatch_lines(
+ """
+ suspend, captured*hello1*
+ suspend2, captured*WARNING:root:hello3*
+ """
+ )
+ result.stderr.fnmatch_lines(
+ """
+ WARNING:root:hello2
+ """
+ )
+ assert "atexit" not in result.stderr.str()
+
+
+def test_error_attribute_issue555(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import sys
+ def test_capattr():
+ assert sys.stdout.errors == "replace"
+ assert sys.stderr.errors == "replace"
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+
+@pytest.mark.skipif(
+ not sys.platform.startswith("win"),
+ reason="only on windows",
+)
+def test_windowsconsoleio_workaround_non_standard_streams() -> None:
+ """
+ Ensure _windowsconsoleio_workaround function works with objects that
+ do not implement the full ``io``-based stream protocol, for example execnet channels (#2666).
+ """
+ from _pytest.capture import _windowsconsoleio_workaround
+
+ class DummyStream:
+ def write(self, s):
+ pass
+
+ stream = cast(TextIO, DummyStream())
+ _windowsconsoleio_workaround(stream)
+
+
+def test_dontreadfrominput_has_encoding(pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ import sys
+ def test_capattr():
+ # should not raise AttributeError
+ assert sys.stdout.encoding
+ assert sys.stderr.encoding
+ """
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=1)
+
+
+def test_crash_on_closing_tmpfile_py27(
+ pytester: Pytester, monkeypatch: MonkeyPatch
+) -> None:
+ p = pytester.makepyfile(
+ """
+ import threading
+ import sys
+
+ printing = threading.Event()
+
+ def spam():
+ f = sys.stderr
+ print('SPAMBEFORE', end='', file=f)
+ printing.set()
+
+ while True:
+ try:
+ f.flush()
+ except (OSError, ValueError):
+ break
+
+ def test_spam_in_thread():
+ t = threading.Thread(target=spam)
+ t.daemon = True
+ t.start()
+
+ printing.wait()
+ """
+ )
+ # Do not consider plugins like hypothesis, which might output to stderr.
+ monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")
+ result = pytester.runpytest_subprocess(str(p))
+ assert result.ret == 0
+ assert result.stderr.str() == ""
+ result.stdout.no_fnmatch_line("*OSError*")
+
+
+def test_global_capture_with_live_logging(pytester: Pytester) -> None:
+ # Issue 3819
+ # capture should work with live cli logging
+
+ # Teardown report seems to have the capture for the whole process (setup, capture, teardown)
+ pytester.makeconftest(
+ """
+ def pytest_runtest_logreport(report):
+ if "test_global" in report.nodeid:
+ if report.when == "teardown":
+ with open("caplog", "w", encoding="utf-8") as f:
+ f.write(report.caplog)
+ with open("capstdout", "w", encoding="utf-8") as f:
+ f.write(report.capstdout)
+ """
+ )
+
+ pytester.makepyfile(
+ """
+ import logging
+ import sys
+ import pytest
+
+ logger = logging.getLogger(__name__)
+
+ @pytest.fixture
+ def fix1():
+ print("fix setup")
+ logging.info("fix setup")
+ yield
+ logging.info("fix teardown")
+ print("fix teardown")
+
+ def test_global(fix1):
+ print("begin test")
+ logging.info("something in test")
+ print("end test")
+ """
+ )
+ result = pytester.runpytest_subprocess("--log-cli-level=INFO")
+ assert result.ret == 0
+
+ with open("caplog", encoding="utf-8") as f:
+ caplog = f.read()
+
+ assert "fix setup" in caplog
+ assert "something in test" in caplog
+ assert "fix teardown" in caplog
+
+ with open("capstdout", encoding="utf-8") as f:
+ capstdout = f.read()
+
+ assert "fix setup" in capstdout
+ assert "begin test" in capstdout
+ assert "end test" in capstdout
+ assert "fix teardown" in capstdout
+
+
+@pytest.mark.parametrize("capture_fixture", ["capsys", "capfd"])
+def test_capture_with_live_logging(
+ pytester: Pytester, capture_fixture: CaptureFixture[str]
+) -> None:
+ # Issue 3819
+ # capture should work with live cli logging
+
+ pytester.makepyfile(
+ f"""
+ import logging
+ import sys
+
+ logger = logging.getLogger(__name__)
+
+ def test_capture({capture_fixture}):
+ print("hello")
+ sys.stderr.write("world\\n")
+ captured = {capture_fixture}.readouterr()
+ assert captured.out == "hello\\n"
+ assert captured.err == "world\\n"
+
+ logging.info("something")
+ print("next")
+ logging.info("something")
+
+ captured = {capture_fixture}.readouterr()
+ assert captured.out == "next\\n"
+ """
+ )
+
+ result = pytester.runpytest_subprocess("--log-cli-level=INFO")
+ assert result.ret == 0
+
+
+def test_typeerror_encodedfile_write(pytester: Pytester) -> None:
+ """It should behave the same with and without output capturing (#4861)."""
+ p = pytester.makepyfile(
+ """
+ def test_fails():
+ import sys
+ sys.stdout.write(b"foo")
+ """
+ )
+ result_without_capture = pytester.runpytest("-s", str(p))
+ result_with_capture = pytester.runpytest(str(p))
+
+ assert result_with_capture.ret == result_without_capture.ret
+ out = result_with_capture.stdout.str()
+ assert ("TypeError: write() argument must be str, not bytes" in out) or (
+ "TypeError: unicode argument expected, got 'bytes'" in out
+ )
+
+
+def test_stderr_write_returns_len(capsys: CaptureFixture[str]) -> None:
+ """Write on Encoded files, namely captured stderr, should return number of characters written."""
+ assert sys.stderr.write("Foo") == 3
+
+
+def test_encodedfile_writelines(tmpfile: BinaryIO) -> None:
+ ef = capture.EncodedFile(tmpfile, encoding="utf-8")
+ with pytest.raises(TypeError):
+ ef.writelines([b"line1", b"line2"]) # type: ignore[list-item]
+ assert ef.writelines(["line3", "line4"]) is None # type: ignore[func-returns-value]
+ ef.flush()
+ tmpfile.seek(0)
+ assert tmpfile.read() == b"line3line4"
+ tmpfile.close()
+ with pytest.raises(ValueError):
+ ef.read()
+
+
+def test__get_multicapture() -> None:
+ assert isinstance(_get_multicapture("no"), MultiCapture)
+ with pytest.raises(ValueError, match=r"^unknown capturing method: 'unknown'$"):
+ _get_multicapture("unknown") # type: ignore[arg-type]
+
+
+def test_logging_while_collecting(pytester: Pytester) -> None:
+ """Issue #6240: Calls to logging.xxx() during collection causes all logging calls to be duplicated to stderr"""
+ p = pytester.makepyfile(
+ """\
+ import logging
+
+ logging.warning("during collection")
+
+ def test_logging():
+ logging.warning("during call")
+ assert False
+ """
+ )
+ result = pytester.runpytest_subprocess(p)
+ assert result.ret == ExitCode.TESTS_FAILED
+ result.stdout.fnmatch_lines(
+ [
+ "*test_*.py F*",
+ "====* FAILURES *====",
+ "____*____",
+ "*--- Captured log call*",
+ "WARNING * during call",
+ "*1 failed*",
+ ]
+ )
+ result.stdout.no_fnmatch_line("*Captured stderr call*")
+ result.stdout.no_fnmatch_line("*during collection*")
+
+
+def test_libedit_workaround(pytester: Pytester) -> None:
+ pytester.makeconftest("""
+ import pytest
+
+
+ def pytest_terminal_summary(config):
+ capture = config.pluginmanager.getplugin("capturemanager")
+ capture.suspend_global_capture(in_=True)
+
+ print("Enter 'hi'")
+ value = input()
+ print(f"value: {value!r}")
+
+ capture.resume_global_capture()
+ """)
+ readline = pytest.importorskip("readline")
+ backend = getattr(readline, "backend", readline.__doc__) # added in Python 3.13
+ print(f"Readline backend: {backend}")
+
+ child = pytester.spawn_pytest("")
+ child.expect(r"Enter 'hi'")
+ child.sendline("hi")
+ rest = child.read().decode("utf8")
+ print(rest)
+ match = re.search(r"^value: '(.*)'\r?$", rest, re.MULTILINE)
+ assert match is not None
+ assert match.group(1) == "hi"
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_collect_imported_tests.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_collect_imported_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..28b92e17f6fe76d12a1654878fe4c50ec84b3a7d
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_collect_imported_tests.py
@@ -0,0 +1,102 @@
+"""Tests for the `collect_imported_tests` configuration value."""
+
+from __future__ import annotations
+
+import textwrap
+
+from _pytest.pytester import Pytester
+import pytest
+
+
+def setup_files(pytester: Pytester) -> None:
+ src_dir = pytester.mkdir("src")
+ tests_dir = pytester.mkdir("tests")
+ src_file = src_dir / "foo.py"
+
+ src_file.write_text(
+ textwrap.dedent("""\
+ class Testament:
+ def test_collections(self):
+ pass
+
+ def test_testament(): pass
+ """),
+ encoding="utf-8",
+ )
+
+ test_file = tests_dir / "foo_test.py"
+ test_file.write_text(
+ textwrap.dedent("""\
+ from foo import Testament, test_testament
+
+ class TestDomain:
+ def test(self):
+ testament = Testament()
+ assert testament
+ """),
+ encoding="utf-8",
+ )
+
+ pytester.syspathinsert(src_dir)
+
+
+def test_collect_imports_disabled(pytester: Pytester) -> None:
+ """
+ When collect_imported_tests is disabled, only objects in the
+ test modules are collected as tests, so the imported names (`Testament` and `test_testament`)
+ are not collected.
+ """
+ pytester.makeini(
+ """
+ [pytest]
+ collect_imported_tests = false
+ """
+ )
+
+ setup_files(pytester)
+ result = pytester.runpytest("-v", "tests")
+ result.stdout.fnmatch_lines(
+ [
+ "tests/foo_test.py::TestDomain::test PASSED*",
+ ]
+ )
+
+ # Ensure that the hooks were only called for the collected item.
+ reprec = result.reprec # type:ignore[attr-defined]
+ reports = reprec.getreports("pytest_collectreport")
+ [modified] = reprec.getcalls("pytest_collection_modifyitems")
+ [item_collected] = reprec.getcalls("pytest_itemcollected")
+
+ assert [x.nodeid for x in reports] == [
+ "",
+ "tests/foo_test.py::TestDomain",
+ "tests/foo_test.py",
+ "tests",
+ ]
+ assert [x.nodeid for x in modified.items] == ["tests/foo_test.py::TestDomain::test"]
+ assert item_collected.item.nodeid == "tests/foo_test.py::TestDomain::test"
+
+
+@pytest.mark.parametrize("configure_ini", [False, True])
+def test_collect_imports_enabled(pytester: Pytester, configure_ini: bool) -> None:
+ """
+ When collect_imported_tests is enabled (the default), all names in the
+ test modules are collected as tests.
+ """
+ if configure_ini:
+ pytester.makeini(
+ """
+ [pytest]
+ collect_imported_tests = true
+ """
+ )
+
+ setup_files(pytester)
+ result = pytester.runpytest("-v", "tests")
+ result.stdout.fnmatch_lines(
+ [
+ "tests/foo_test.py::Testament::test_collections PASSED*",
+ "tests/foo_test.py::test_testament PASSED*",
+ "tests/foo_test.py::TestDomain::test PASSED*",
+ ]
+ )
diff --git a/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_collection.py b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_collection.py
new file mode 100644
index 0000000000000000000000000000000000000000..093162ddec49df6e62508ba328a489d1e001f542
--- /dev/null
+++ b/tasks/tasksmith-5e916b3f6da1/tests/source/testing/test_collection.py
@@ -0,0 +1,2799 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+from collections.abc import Sequence
+import os
+from pathlib import Path
+from pathlib import PurePath
+import pprint
+import shutil
+import sys
+import tempfile
+import textwrap
+
+from _pytest.compat import running_on_ci
+from _pytest.config import ExitCode
+from _pytest.fixtures import FixtureRequest
+from _pytest.main import _in_venv
+from _pytest.main import Session
+from _pytest.monkeypatch import MonkeyPatch
+from _pytest.nodes import Item
+from _pytest.pathlib import symlink_or_skip
+from _pytest.pytester import HookRecorder
+from _pytest.pytester import Pytester
+import pytest
+
+
+def ensure_file(file_path: Path) -> Path:
+ """Ensure that file exists"""
+ file_path.parent.mkdir(parents=True, exist_ok=True)
+ file_path.touch(exist_ok=True)
+ return file_path
+
+
+class TestCollector:
+ def test_collect_versus_item(self) -> None:
+ from pytest import Collector
+ from pytest import Item
+
+ assert not issubclass(Collector, Item)
+ assert not issubclass(Item, Collector)
+
+ def test_check_equality(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ def test_pass(): pass
+ def test_fail(): assert 0
+ """
+ )
+ fn1 = pytester.collect_by_name(modcol, "test_pass")
+ assert isinstance(fn1, pytest.Function)
+ fn2 = pytester.collect_by_name(modcol, "test_pass")
+ assert isinstance(fn2, pytest.Function)
+
+ assert fn1 == fn2
+ assert fn1 != modcol
+ assert hash(fn1) == hash(fn2)
+
+ fn3 = pytester.collect_by_name(modcol, "test_fail")
+ assert isinstance(fn3, pytest.Function)
+ assert not (fn1 == fn3)
+ assert fn1 != fn3
+
+ for fn in fn1, fn2, fn3:
+ assert isinstance(fn, pytest.Function)
+ assert fn != 3 # type: ignore[comparison-overlap]
+ assert fn != modcol
+ assert fn != [1, 2, 3] # type: ignore[comparison-overlap]
+ assert [1, 2, 3] != fn # type: ignore[comparison-overlap]
+ assert modcol != fn
+
+ assert pytester.collect_by_name(modcol, "doesnotexist") is None
+
+ def test_getparent_and_accessors(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ class TestClass:
+ def test_foo(self):
+ pass
+ """
+ )
+ cls = pytester.collect_by_name(modcol, "TestClass")
+ assert isinstance(cls, pytest.Class)
+ fn = pytester.collect_by_name(cls, "test_foo")
+ assert isinstance(fn, pytest.Function)
+
+ assert fn.getparent(pytest.Module) is modcol
+ assert modcol is not None
+ assert modcol.module is not None
+ assert modcol.cls is None
+ assert modcol.instance is None
+
+ assert fn.getparent(pytest.Class) is cls
+ assert cls.module is not None
+ assert cls.cls is not None
+ assert cls.instance is None
+
+ assert fn.getparent(pytest.Function) is fn
+ assert fn.module is not None
+ assert fn.cls is not None
+ assert fn.instance is not None
+ assert fn.function is not None
+
+ def test_getcustomfile_roundtrip(self, pytester: Pytester) -> None:
+ hello = pytester.makefile(".xxx", hello="world")
+ pytester.makepyfile(
+ conftest="""
+ import pytest
+ class CustomFile(pytest.File):
+ def collect(self):
+ return []
+ def pytest_collect_file(file_path, parent):
+ if file_path.suffix == ".xxx":
+ return CustomFile.from_parent(path=file_path, parent=parent)
+ """
+ )
+ node = pytester.getpathnode(hello)
+ assert isinstance(node, pytest.File)
+ assert node.name == "hello.xxx"
+ nodes = node.session.perform_collect([node.nodeid], genitems=False)
+ assert len(nodes) == 1
+ assert isinstance(nodes[0], pytest.File)
+
+ def test_can_skip_class_with_test_attr(self, pytester: Pytester) -> None:
+ """Assure test class is skipped when using `__test__=False` (See #2007)."""
+ pytester.makepyfile(
+ """
+ class TestFoo(object):
+ __test__ = False
+ def __init__(self):
+ pass
+ def test_foo():
+ assert True
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["collected 0 items", "*no tests ran in*"])
+
+
+class TestCollectFS:
+ def test_ignored_certain_directories(self, pytester: Pytester) -> None:
+ tmp_path = pytester.path
+ ensure_file(tmp_path / "build" / "test_notfound.py")
+ ensure_file(tmp_path / "dist" / "test_notfound.py")
+ ensure_file(tmp_path / "_darcs" / "test_notfound.py")
+ ensure_file(tmp_path / "CVS" / "test_notfound.py")
+ ensure_file(tmp_path / "{arch}" / "test_notfound.py")
+ ensure_file(tmp_path / ".whatever" / "test_notfound.py")
+ ensure_file(tmp_path / ".bzr" / "test_notfound.py")
+ ensure_file(tmp_path / "normal" / "test_found.py")
+ for x in tmp_path.rglob("test_*.py"):
+ x.write_text("def test_hello(): pass", encoding="utf-8")
+
+ result = pytester.runpytest("--collect-only")
+ s = result.stdout.str()
+ assert "test_notfound" not in s
+ assert "test_found" in s
+
+ known_environment_types = pytest.mark.parametrize(
+ "env_path",
+ [
+ pytest.param(PurePath("pyvenv.cfg"), id="venv"),
+ pytest.param(PurePath("conda-meta", "history"), id="conda"),
+ ],
+ )
+
+ @known_environment_types
+ def test_ignored_virtualenvs(self, pytester: Pytester, env_path: PurePath) -> None:
+ ensure_file(pytester.path / "virtual" / env_path)
+ testfile = ensure_file(pytester.path / "virtual" / "test_invenv.py")
+ testfile.write_text("def test_hello(): pass", encoding="utf-8")
+
+ # by default, ignore tests inside a virtualenv
+ result = pytester.runpytest()
+ result.stdout.no_fnmatch_line("*test_invenv*")
+ # allow test collection if user insists
+ result = pytester.runpytest("--collect-in-virtualenv")
+ assert "test_invenv" in result.stdout.str()
+ # allow test collection if user directly passes in the directory
+ result = pytester.runpytest("virtual")
+ assert "test_invenv" in result.stdout.str()
+
+ @known_environment_types
+ def test_ignored_virtualenvs_norecursedirs_precedence(
+ self, pytester: Pytester, env_path
+ ) -> None:
+ # norecursedirs takes priority
+ ensure_file(pytester.path / ".virtual" / env_path)
+ testfile = ensure_file(pytester.path / ".virtual" / "test_invenv.py")
+ testfile.write_text("def test_hello(): pass", encoding="utf-8")
+ result = pytester.runpytest("--collect-in-virtualenv")
+ result.stdout.no_fnmatch_line("*test_invenv*")
+ # ...unless the virtualenv is explicitly given on the CLI
+ result = pytester.runpytest("--collect-in-virtualenv", ".virtual")
+ assert "test_invenv" in result.stdout.str()
+
+ @known_environment_types
+ def test__in_venv(self, pytester: Pytester, env_path: PurePath) -> None:
+ """Directly test the virtual env detection function"""
+ # no env path, not a env
+ base_path = pytester.mkdir("venv")
+ assert _in_venv(base_path) is False
+ # with env path, totally a env
+ ensure_file(base_path.joinpath(env_path))
+ assert _in_venv(base_path) is True
+
+ def test_custom_norecursedirs(self, pytester: Pytester) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ norecursedirs = mydir xyz*
+ """
+ )
+ tmp_path = pytester.path
+ ensure_file(tmp_path / "mydir" / "test_hello.py").write_text(
+ "def test_1(): pass", encoding="utf-8"
+ )
+ ensure_file(tmp_path / "xyz123" / "test_2.py").write_text(
+ "def test_2(): 0/0", encoding="utf-8"
+ )
+ ensure_file(tmp_path / "xy" / "test_ok.py").write_text(
+ "def test_3(): pass", encoding="utf-8"
+ )
+ rec = pytester.inline_run()
+ rec.assertoutcome(passed=1)
+ rec = pytester.inline_run("xyz123/test_2.py")
+ rec.assertoutcome(failed=1)
+
+ def test_testpaths_ini(self, pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
+ pytester.makeini(
+ """
+ [pytest]
+ testpaths = */tests
+ """
+ )
+ tmp_path = pytester.path
+ ensure_file(tmp_path / "a" / "test_1.py").write_text(
+ "def test_a(): pass", encoding="utf-8"
+ )
+ ensure_file(tmp_path / "b" / "tests" / "test_2.py").write_text(
+ "def test_b(): pass", encoding="utf-8"
+ )
+ ensure_file(tmp_path / "c" / "tests" / "test_3.py").write_text(
+ "def test_c(): pass", encoding="utf-8"
+ )
+
+ # executing from rootdir only tests from `testpaths` directories
+ # are collected
+ items, _reprec = pytester.inline_genitems("-v")
+ assert [x.name for x in items] == ["test_b", "test_c"]
+
+ # check that explicitly passing directories in the command-line
+ # collects the tests
+ for dirname in ("a", "b", "c"):
+ items, _reprec = pytester.inline_genitems(tmp_path.joinpath(dirname))
+ assert [x.name for x in items] == [f"test_{dirname}"]
+
+ # changing cwd to each subdirectory and running pytest without
+ # arguments collects the tests in that directory normally
+ for dirname in ("a", "b", "c"):
+ monkeypatch.chdir(pytester.path.joinpath(dirname))
+ items, _reprec = pytester.inline_genitems()
+ assert [x.name for x in items] == [f"test_{dirname}"]
+
+ def test_missing_permissions_on_unselected_directory_doesnt_crash(
+ self, pytester: Pytester
+ ) -> None:
+ """Regression test for #12120."""
+ test = pytester.makepyfile(test="def test(): pass")
+ bad = pytester.mkdir("bad")
+ try:
+ bad.chmod(0)
+
+ result = pytester.runpytest(test)
+ finally:
+ bad.chmod(750)
+ bad.rmdir()
+
+ assert result.ret == ExitCode.OK
+ result.assert_outcomes(passed=1)
+
+
+class TestCollectPluginHookRelay:
+ def test_pytest_collect_file(self, pytester: Pytester) -> None:
+ wascalled = []
+
+ class Plugin:
+ def pytest_collect_file(self, file_path: Path) -> None:
+ if not file_path.name.startswith("."):
+ # Ignore hidden files, e.g. .testmondata.
+ wascalled.append(file_path)
+
+ pytester.makefile(".abc", "xyz")
+ pytest.main(pytester.path, plugins=[Plugin()])
+ assert len(wascalled) == 1
+ assert wascalled[0].suffix == ".abc"
+
+
+class TestPrunetraceback:
+ def test_custom_repr_failure(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ import not_exists
+ """
+ )
+ pytester.makeconftest(
+ """
+ import pytest
+ def pytest_collect_file(file_path, parent):
+ return MyFile.from_parent(path=file_path, parent=parent)
+ class MyError(Exception):
+ pass
+ class MyFile(pytest.File):
+ def collect(self):
+ raise MyError()
+ def repr_failure(self, excinfo):
+ if isinstance(excinfo.value, MyError):
+ return "hello world"
+ return pytest.File.repr_failure(self, excinfo)
+ """
+ )
+
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(["*ERROR collecting*", "*hello world*"])
+
+ @pytest.mark.xfail(reason="other mechanism for adding to reporting needed")
+ def test_collect_report_postprocessing(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ import not_exists
+ """
+ )
+ pytester.makeconftest(
+ """
+ import pytest
+ @pytest.hookimpl(wrapper=True)
+ def pytest_make_collect_report():
+ rep = yield
+ rep.headerlines += ["header1"]
+ return rep
+ """
+ )
+ result = pytester.runpytest(p)
+ result.stdout.fnmatch_lines(["*ERROR collecting*", "*header1*"])
+
+ def test_collection_error_traceback_is_clean(self, pytester: Pytester) -> None:
+ """When a collection error occurs, the report traceback doesn't contain
+ internal pytest stack entries.
+
+ Issue #11710.
+ """
+ pytester.makepyfile(
+ """
+ raise Exception("LOUSY")
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ [
+ "*ERROR collecting*",
+ "test_*.py:1: in ",
+ ' raise Exception("LOUSY")',
+ "E Exception: LOUSY",
+ "*= short test summary info =*",
+ ],
+ consecutive=True,
+ )
+
+
+class TestCustomConftests:
+ def test_ignore_collect_path(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ def pytest_ignore_collect(collection_path, config):
+ return collection_path.name.startswith("x") or collection_path.name == "test_one.py"
+ """
+ )
+ sub = pytester.mkdir("xy123")
+ ensure_file(sub / "test_hello.py").write_text("syntax error", encoding="utf-8")
+ sub.joinpath("conftest.py").write_text("syntax error", encoding="utf-8")
+ pytester.makepyfile("def test_hello(): pass")
+ pytester.makepyfile(test_one="syntax error")
+ result = pytester.runpytest("--fulltrace")
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+ def test_ignore_collect_not_called_on_argument(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ def pytest_ignore_collect(collection_path, config):
+ return True
+ """
+ )
+ p = pytester.makepyfile("def test_hello(): pass")
+ result = pytester.runpytest(p)
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*1 passed*"])
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+ result.stdout.fnmatch_lines(["*collected 0 items*"])
+
+ def test_collectignore_exclude_on_option(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ from pathlib import Path
+
+ class MyPathLike:
+ def __init__(self, path):
+ self.path = path
+ def __fspath__(self):
+ return "path"
+
+ collect_ignore = [MyPathLike('hello'), 'test_world.py', Path('bye')]
+
+ def pytest_addoption(parser):
+ parser.addoption("--XX", action="store_true", default=False)
+
+ def pytest_configure(config):
+ if config.getvalue("XX"):
+ collect_ignore[:] = []
+ """
+ )
+ pytester.mkdir("hello")
+ pytester.makepyfile(test_world="def test_hello(): pass")
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+ result.stdout.no_fnmatch_line("*passed*")
+ result = pytester.runpytest("--XX")
+ assert result.ret == 0
+ assert "passed" in result.stdout.str()
+
+ def test_collectignoreglob_exclude_on_option(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ collect_ignore_glob = ['*w*l[dt]*']
+ def pytest_addoption(parser):
+ parser.addoption("--XX", action="store_true", default=False)
+ def pytest_configure(config):
+ if config.getvalue("XX"):
+ collect_ignore_glob[:] = []
+ """
+ )
+ pytester.makepyfile(test_world="def test_hello(): pass")
+ pytester.makepyfile(test_welt="def test_hallo(): pass")
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+ result.stdout.fnmatch_lines(["*collected 0 items*"])
+ result = pytester.runpytest("--XX")
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*2 passed*"])
+
+ def test_pytest_fs_collect_hooks_are_seen(self, pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ class MyModule(pytest.Module):
+ pass
+ def pytest_collect_file(file_path, parent):
+ if file_path.suffix == ".py":
+ return MyModule.from_parent(path=file_path, parent=parent)
+ """
+ )
+ pytester.mkdir("sub")
+ pytester.makepyfile("def test_x(): pass")
+ result = pytester.runpytest("--co")
+ result.stdout.fnmatch_lines(["*MyModule*", "*test_x*"])
+
+ def test_pytest_collect_file_from_sister_dir(self, pytester: Pytester) -> None:
+ sub1 = pytester.mkpydir("sub1")
+ sub2 = pytester.mkpydir("sub2")
+ conf1 = pytester.makeconftest(
+ """
+ import pytest
+ class MyModule1(pytest.Module):
+ pass
+ def pytest_collect_file(file_path, parent):
+ if file_path.suffix == ".py":
+ return MyModule1.from_parent(path=file_path, parent=parent)
+ """
+ )
+ conf1.replace(sub1.joinpath(conf1.name))
+ conf2 = pytester.makeconftest(
+ """
+ import pytest
+ class MyModule2(pytest.Module):
+ pass
+ def pytest_collect_file(file_path, parent):
+ if file_path.suffix == ".py":
+ return MyModule2.from_parent(path=file_path, parent=parent)
+ """
+ )
+ conf2.replace(sub2.joinpath(conf2.name))
+ p = pytester.makepyfile("def test_x(): pass")
+ shutil.copy(p, sub1.joinpath(p.name))
+ shutil.copy(p, sub2.joinpath(p.name))
+ result = pytester.runpytest("--co")
+ result.stdout.fnmatch_lines(["*MyModule1*", "*MyModule2*", "*test_x*"])
+
+
+class TestSession:
+ def test_collect_topdir(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile("def test_func(): pass")
+ id = "::".join([p.name, "test_func"])
+ # XXX migrate to collectonly? (see below)
+ config = pytester.parseconfig(id)
+ topdir = pytester.path
+ rcol = Session.from_config(config)
+ assert topdir == rcol.path
+ # rootid = rcol.nodeid
+ # root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]
+ # assert root2 == rcol, rootid
+ colitems = rcol.perform_collect([rcol.nodeid], genitems=False)
+ assert len(colitems) == 1
+ assert colitems[0].path == topdir
+
+ def get_reported_items(self, hookrec: HookRecorder) -> list[Item]:
+ """Return pytest.Item instances reported by the pytest_collectreport hook"""
+ calls = hookrec.getcalls("pytest_collectreport")
+ return [
+ x
+ for call in calls
+ for x in call.report.result
+ if isinstance(x, pytest.Item)
+ ]
+
+ def test_collect_protocol_single_function(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile("def test_func(): pass")
+ id = "::".join([p.name, "test_func"])
+ items, hookrec = pytester.inline_genitems(id)
+ (item,) = items
+ assert item.name == "test_func"
+ newid = item.nodeid
+ assert newid == id
+ pprint.pprint(hookrec.calls)
+ topdir = pytester.path # noqa: F841
+ hookrec.assert_contains(
+ [
+ ("pytest_collectstart", "collector.path == topdir"),
+ ("pytest_make_collect_report", "collector.path == topdir"),
+ ("pytest_collectstart", "collector.path == p"),
+ ("pytest_make_collect_report", "collector.path == p"),
+ ("pytest_pycollect_makeitem", "name == 'test_func'"),
+ ("pytest_collectreport", "report.result[0].name == 'test_func'"),
+ ]
+ )
+ # ensure we are reporting the collection of the single test item (#2464)
+ assert [x.name for x in self.get_reported_items(hookrec)] == ["test_func"]
+
+ def test_collect_protocol_method(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ class TestClass(object):
+ def test_method(self):
+ pass
+ """
+ )
+ normid = p.name + "::TestClass::test_method"
+ for id in [p.name, p.name + "::TestClass", normid]:
+ items, hookrec = pytester.inline_genitems(id)
+ assert len(items) == 1
+ assert items[0].name == "test_method"
+ newid = items[0].nodeid
+ assert newid == normid
+ # ensure we are reporting the collection of the single test item (#2464)
+ assert [x.name for x in self.get_reported_items(hookrec)] == ["test_method"]
+
+ def test_collect_custom_nodes_multi_id(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile("def test_func(): pass")
+ pytester.makeconftest(
+ f"""
+ import pytest
+ class SpecialItem(pytest.Item):
+ def runtest(self):
+ return # ok
+ class SpecialFile(pytest.File):
+ def collect(self):
+ return [SpecialItem.from_parent(name="check", parent=self)]
+ def pytest_collect_file(file_path, parent):
+ if file_path.name == {p.name!r}:
+ return SpecialFile.from_parent(path=file_path, parent=parent)
+ """
+ )
+ id = p.name
+
+ items, hookrec = pytester.inline_genitems(id)
+ pprint.pprint(hookrec.calls)
+ assert len(items) == 2
+ hookrec.assert_contains(
+ [
+ ("pytest_collectstart", "collector.path == collector.session.path"),
+ (
+ "pytest_collectstart",
+ "collector.__class__.__name__ == 'SpecialFile'",
+ ),
+ ("pytest_collectstart", "collector.__class__.__name__ == 'Module'"),
+ ("pytest_pycollect_makeitem", "name == 'test_func'"),
+ ("pytest_collectreport", "report.nodeid.startswith(p.name)"),
+ ]
+ )
+ assert len(self.get_reported_items(hookrec)) == 2
+
+ def test_collect_subdir_event_ordering(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile("def test_func(): pass")
+ aaa = pytester.mkpydir("aaa")
+ test_aaa = aaa.joinpath("test_aaa.py")
+ p.replace(test_aaa)
+
+ items, hookrec = pytester.inline_genitems()
+ assert len(items) == 1
+ pprint.pprint(hookrec.calls)
+ hookrec.assert_contains(
+ [
+ ("pytest_collectstart", "collector.path == test_aaa"),
+ ("pytest_pycollect_makeitem", "name == 'test_func'"),
+ ("pytest_collectreport", "report.nodeid.startswith('aaa/test_aaa.py')"),
+ ]
+ )
+
+ def test_collect_two_commandline_args(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile("def test_func(): pass")
+ aaa = pytester.mkpydir("aaa")
+ bbb = pytester.mkpydir("bbb")
+ test_aaa = aaa.joinpath("test_aaa.py")
+ shutil.copy(p, test_aaa)
+ test_bbb = bbb.joinpath("test_bbb.py")
+ p.replace(test_bbb)
+
+ id = "."
+
+ items, hookrec = pytester.inline_genitems(id)
+ assert len(items) == 2
+ pprint.pprint(hookrec.calls)
+ hookrec.assert_contains(
+ [
+ ("pytest_collectstart", "collector.path == test_aaa"),
+ ("pytest_pycollect_makeitem", "name == 'test_func'"),
+ ("pytest_collectreport", "report.nodeid == 'aaa/test_aaa.py'"),
+ ("pytest_collectstart", "collector.path == test_bbb"),
+ ("pytest_pycollect_makeitem", "name == 'test_func'"),
+ ("pytest_collectreport", "report.nodeid == 'bbb/test_bbb.py'"),
+ ]
+ )
+
+ def test_serialization_byid(self, pytester: Pytester) -> None:
+ pytester.makepyfile("def test_func(): pass")
+ items, _hookrec = pytester.inline_genitems()
+ assert len(items) == 1
+ (item,) = items
+ items2, _hookrec = pytester.inline_genitems(item.nodeid)
+ (item2,) = items2
+ assert item2.name == item.name
+ assert item2.path == item.path
+
+ def test_find_byid_without_instance_parents(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ class TestClass(object):
+ def test_method(self):
+ pass
+ """
+ )
+ arg = p.name + "::TestClass::test_method"
+ items, hookrec = pytester.inline_genitems(arg)
+ assert len(items) == 1
+ (item,) = items
+ assert item.nodeid.endswith("TestClass::test_method")
+ # ensure we are reporting the collection of the single test item (#2464)
+ assert [x.name for x in self.get_reported_items(hookrec)] == ["test_method"]
+
+ def test_collect_parametrized_order(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.parametrize('i', [0, 1, 2])
+ def test_param(i): ...
+ """
+ )
+ items, _hookrec = pytester.inline_genitems(f"{p}::test_param")
+ assert len(items) == 3
+ assert [item.nodeid for item in items] == [
+ "test_collect_parametrized_order.py::test_param[0]",
+ "test_collect_parametrized_order.py::test_param[1]",
+ "test_collect_parametrized_order.py::test_param[2]",
+ ]
+
+
+class Test_getinitialnodes:
+ def test_global_file(self, pytester: Pytester) -> None:
+ tmp_path = pytester.path
+ x = ensure_file(tmp_path / "x.py")
+ config = pytester.parseconfigure(x)
+ col = pytester.getnode(config, x)
+ assert isinstance(col, pytest.Module)
+ assert col.name == "x.py"
+ assert col.parent is not None
+ assert col.parent.parent is not None
+ assert col.parent.parent.parent is None
+ for parent in col.listchain():
+ assert parent.config is config
+
+ def test_pkgfile(self, pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
+ """Verify nesting when a module is within a package.
+ The parent chain should match: Module -> Package -> Session.
+ Session's parent should always be None.
+ """
+ tmp_path = pytester.path
+ subdir = tmp_path.joinpath("subdir")
+ x = ensure_file(subdir / "x.py")
+ ensure_file(subdir / "__init__.py")
+ with monkeypatch.context() as mp:
+ mp.chdir(subdir)
+ config = pytester.parseconfigure(x)
+ col = pytester.getnode(config, x)
+ assert col is not None
+ assert col.name == "x.py"
+ assert isinstance(col, pytest.Module)
+ assert isinstance(col.parent, pytest.Package)
+ assert isinstance(col.parent.parent, pytest.Session)
+ # session is batman (has no parents)
+ assert col.parent.parent.parent is None
+ for parent in col.listchain():
+ assert parent.config is config
+
+
+class Test_genitems:
+ def test_check_collect_hashes(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ def test_1():
+ pass
+
+ def test_2():
+ pass
+ """
+ )
+ shutil.copy(p, p.parent / (p.stem + "2" + ".py"))
+ items, _reprec = pytester.inline_genitems(p.parent)
+ assert len(items) == 4
+ for numi, i in enumerate(items):
+ for numj, j in enumerate(items):
+ if numj != numi:
+ assert hash(i) != hash(j)
+ assert i != j
+
+ def test_example_items1(self, pytester: Pytester) -> None:
+ p = pytester.makepyfile(
+ """
+ import pytest
+
+ def testone():
+ pass
+
+ class TestX(object):
+ def testmethod_one(self):
+ pass
+
+ class TestY(TestX):
+ @pytest.mark.parametrize("arg0", [".["])
+ def testmethod_two(self, arg0):
+ pass
+ """
+ )
+ items, _reprec = pytester.inline_genitems(p)
+ assert len(items) == 4
+ assert items[0].name == "testone"
+ assert items[1].name == "testmethod_one"
+ assert items[2].name == "testmethod_one"
+ assert items[3].name == "testmethod_two[.[]"
+
+ # let's also test getmodpath here
+ assert items[0].getmodpath() == "testone" # type: ignore[attr-defined]
+ assert items[1].getmodpath() == "TestX.testmethod_one" # type: ignore[attr-defined]
+ assert items[2].getmodpath() == "TestY.testmethod_one" # type: ignore[attr-defined]
+ # PR #6202: Fix incorrect result of getmodpath method. (Resolves issue #6189)
+ assert items[3].getmodpath() == "TestY.testmethod_two[.[]" # type: ignore[attr-defined]
+
+ s = items[0].getmodpath(stopatmodule=False) # type: ignore[attr-defined]
+ assert s.endswith("test_example_items1.testone")
+ print(s)
+
+ def test_classmethod_is_discovered(self, pytester: Pytester) -> None:
+ """Test that classmethods are discovered"""
+ p = pytester.makepyfile(
+ """
+ class TestCase:
+ @classmethod
+ def test_classmethod(cls) -> None:
+ pass
+ """
+ )
+ items, _reprec = pytester.inline_genitems(p)
+ ids = [x.getmodpath() for x in items] # type: ignore[attr-defined]
+ assert ids == ["TestCase.test_classmethod"]
+
+ def test_class_and_functions_discovery_using_glob(self, pytester: Pytester) -> None:
+ """Test that Python_classes and Python_functions config options work
+ as prefixes and glob-like patterns (#600)."""
+ pytester.makeini(
+ """
+ [pytest]
+ python_classes = *Suite Test
+ python_functions = *_test test
+ """
+ )
+ p = pytester.makepyfile(
+ """
+ class MyTestSuite(object):
+ def x_test(self):
+ pass
+
+ class TestCase(object):
+ def test_y(self):
+ pass
+ """
+ )
+ items, _reprec = pytester.inline_genitems(p)
+ ids = [x.getmodpath() for x in items] # type: ignore[attr-defined]
+ assert ids == ["MyTestSuite.x_test", "TestCase.test_y"]
+
+
+def test_matchnodes_two_collections_same_file(pytester: Pytester) -> None:
+ pytester.makeconftest(
+ """
+ import pytest
+ def pytest_configure(config):
+ config.pluginmanager.register(Plugin2())
+
+ class Plugin2(object):
+ def pytest_collect_file(self, file_path, parent):
+ if file_path.suffix == ".abc":
+ return MyFile2.from_parent(path=file_path, parent=parent)
+
+ def pytest_collect_file(file_path, parent):
+ if file_path.suffix == ".abc":
+ return MyFile1.from_parent(path=file_path, parent=parent)
+
+ class MyFile1(pytest.File):
+ def collect(self):
+ yield Item1.from_parent(name="item1", parent=self)
+
+ class MyFile2(pytest.File):
+ def collect(self):
+ yield Item2.from_parent(name="item2", parent=self)
+
+ class Item1(pytest.Item):
+ def runtest(self):
+ pass
+
+ class Item2(pytest.Item):
+ def runtest(self):
+ pass
+ """
+ )
+ p = pytester.makefile(".abc", "")
+ result = pytester.runpytest()
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*2 passed*"])
+ res = pytester.runpytest(f"{p.name}::item2")
+ res.stdout.fnmatch_lines(["*1 passed*"])
+
+
+class TestNodeKeywords:
+ def test_no_under(self, pytester: Pytester) -> None:
+ modcol = pytester.getmodulecol(
+ """
+ def test_pass(): pass
+ def test_fail(): assert 0
+ """
+ )
+ values = list(modcol.keywords)
+ assert modcol.name in values
+ for x in values:
+ assert not x.startswith("_")
+ assert modcol.name in repr(modcol.keywords)
+
+ def test_issue345(self, pytester: Pytester) -> None:
+ pytester.makepyfile(
+ """
+ def test_should_not_be_selected():
+ assert False, 'I should not have been selected to run'
+
+ def test___repr__():
+ pass
+ """
+ )
+ reprec = pytester.inline_run("-k repr")
+ reprec.assertoutcome(passed=1, failed=0)
+
+ def test_keyword_matching_is_case_insensitive_by_default(
+ self, pytester: Pytester
+ ) -> None:
+ """Check that selection via -k EXPRESSION is case-insensitive.
+
+ Since markers are also added to the node keywords, they too can
+ be matched without having to think about case sensitivity.
+
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ def test_sPeCiFiCToPiC_1():
+ assert True
+
+ class TestSpecificTopic_2:
+ def test(self):
+ assert True
+
+ @pytest.mark.sPeCiFiCToPic_3
+ def test():
+ assert True
+
+ @pytest.mark.sPeCiFiCToPic_4
+ class Test:
+ def test(self):
+ assert True
+
+ def test_failing_5():
+ assert False, "This should not match"
+
+ """
+ )
+ num_matching_tests = 4
+ for expression in ("specifictopic", "SPECIFICTOPIC", "SpecificTopic"):
+ reprec = pytester.inline_run("-k " + expression)
+ reprec.assertoutcome(passed=num_matching_tests, failed=0)
+
+ def test_duplicates_handled_correctly(self, pytester: Pytester) -> None:
+ item = pytester.getitem(
+ """
+ import pytest
+ pytestmark = pytest.mark.kw
+ class TestClass:
+ pytestmark = pytest.mark.kw
+ def test_method(self): pass
+ test_method.kw = 'method'
+ """,
+ "test_method",
+ )
+ assert item.parent is not None and item.parent.parent is not None
+ item.parent.parent.keywords["kw"] = "class"
+
+ assert item.keywords["kw"] == "method"
+ assert len(item.keywords) == len(set(item.keywords))
+
+ def test_unpacked_marks_added_to_keywords(self, pytester: Pytester) -> None:
+ item = pytester.getitem(
+ """
+ import pytest
+ pytestmark = pytest.mark.foo
+ class TestClass:
+ pytestmark = pytest.mark.bar
+ def test_method(self): pass
+ test_method.pytestmark = pytest.mark.baz
+ """,
+ "test_method",
+ )
+ assert isinstance(item, pytest.Function)
+ cls = item.getparent(pytest.Class)
+ assert cls is not None
+ mod = item.getparent(pytest.Module)
+ assert mod is not None
+
+ assert item.keywords["foo"] == pytest.mark.foo.mark
+ assert item.keywords["bar"] == pytest.mark.bar.mark
+ assert item.keywords["baz"] == pytest.mark.baz.mark
+
+ assert cls.keywords["foo"] == pytest.mark.foo.mark
+ assert cls.keywords["bar"] == pytest.mark.bar.mark
+ assert "baz" not in cls.keywords
+
+ assert mod.keywords["foo"] == pytest.mark.foo.mark
+ assert "bar" not in mod.keywords
+ assert "baz" not in mod.keywords
+
+
+class TestCollectDirectoryHook:
+ def test_custom_directory_example(self, pytester: Pytester) -> None:
+ """Verify the example from the customdirectory.rst doc."""
+ pytester.copy_example("customdirectory")
+
+ reprec = pytester.inline_run()
+
+ reprec.assertoutcome(passed=2, failed=0)
+ calls = reprec.getcalls("pytest_collect_directory")
+ assert len(calls) == 2
+ assert calls[0].path == pytester.path
+ assert isinstance(calls[0].parent, pytest.Session)
+ assert calls[1].path == pytester.path / "tests"
+ assert isinstance(calls[1].parent, pytest.Dir)
+
+ def test_directory_ignored_if_none(self, pytester: Pytester) -> None:
+ """If the (entire) hook returns None, it's OK, the directory is ignored."""
+ pytester.makeconftest(
+ """
+ import pytest
+
+ @pytest.hookimpl(wrapper=True)
+ def pytest_collect_directory():
+ yield
+ return None
+ """,
+ )
+ pytester.makepyfile(
+ **{
+ "tests/test_it.py": """
+ import pytest
+
+ def test_it(): pass
+ """,
+ },
+ )
+ reprec = pytester.inline_run()
+ reprec.assertoutcome(passed=0, failed=0)
+
+
+COLLECTION_ERROR_PY_FILES = dict(
+ test_01_failure="""
+ def test_1():
+ assert False
+ """,
+ test_02_import_error="""
+ import asdfasdfasdf
+ def test_2():
+ assert True
+ """,
+ test_03_import_error="""
+ import asdfasdfasdf
+ def test_3():
+ assert True
+ """,
+ test_04_success="""
+ def test_4():
+ assert True
+ """,
+)
+
+
+def test_exit_on_collection_error(pytester: Pytester) -> None:
+ """Verify that all collection errors are collected and no tests executed"""
+ pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)
+
+ res = pytester.runpytest()
+ assert res.ret == 2
+
+ res.stdout.fnmatch_lines(
+ [
+ "collected 2 items / 2 errors",
+ "*ERROR collecting test_02_import_error.py*",
+ "*No module named *asdfa*",
+ "*ERROR collecting test_03_import_error.py*",
+ "*No module named *asdfa*",
+ ]
+ )
+
+
+def test_exit_on_collection_with_maxfail_smaller_than_n_errors(
+ pytester: Pytester,
+) -> None:
+ """
+ Verify collection is aborted once maxfail errors are encountered ignoring
+ further modules which would cause more collection errors.
+ """
+ pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)
+
+ res = pytester.runpytest("--maxfail=1")
+ assert res.ret == 1
+ res.stdout.fnmatch_lines(
+ [
+ "collected 1 item / 1 error",
+ "*ERROR collecting test_02_import_error.py*",
+ "*No module named *asdfa*",
+ "*! stopping after 1 failures !*",
+ "*= 1 error in *",
+ ]
+ )
+ res.stdout.no_fnmatch_line("*test_03*")
+
+
+def test_exit_on_collection_with_maxfail_bigger_than_n_errors(
+ pytester: Pytester,
+) -> None:
+ """
+ Verify the test run aborts due to collection errors even if maxfail count of
+ errors was not reached.
+ """
+ pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)
+
+ res = pytester.runpytest("--maxfail=4")
+ assert res.ret == 2
+ res.stdout.fnmatch_lines(
+ [
+ "collected 2 items / 2 errors",
+ "*ERROR collecting test_02_import_error.py*",
+ "*No module named *asdfa*",
+ "*ERROR collecting test_03_import_error.py*",
+ "*No module named *asdfa*",
+ "*! Interrupted: 2 errors during collection !*",
+ "*= 2 errors in *",
+ ]
+ )
+
+
+def test_continue_on_collection_errors(pytester: Pytester) -> None:
+ """
+ Verify tests are executed even when collection errors occur when the
+ --continue-on-collection-errors flag is set
+ """
+ pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)
+
+ res = pytester.runpytest("--continue-on-collection-errors")
+ assert res.ret == 1
+
+ res.stdout.fnmatch_lines(
+ ["collected 2 items / 2 errors", "*1 failed, 1 passed, 2 errors*"]
+ )
+
+
+def test_continue_on_collection_errors_maxfail(pytester: Pytester) -> None:
+ """
+ Verify tests are executed even when collection errors occur and that maxfail
+ is honoured (including the collection error count).
+ 4 tests: 2 collection errors + 1 failure + 1 success
+ test_4 is never executed because the test run is with --maxfail=3 which
+ means it is interrupted after the 2 collection errors + 1 failure.
+ """
+ pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)
+
+ res = pytester.runpytest("--continue-on-collection-errors", "--maxfail=3")
+ assert res.ret == 1
+
+ res.stdout.fnmatch_lines(["collected 2 items / 2 errors", "*1 failed, 2 errors*"])
+
+
+def test_fixture_scope_sibling_conftests(pytester: Pytester) -> None:
+ """Regression test case for https://github.com/pytest-dev/pytest/issues/2836"""
+ foo_path = pytester.mkdir("foo")
+ foo_path.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """\
+ import pytest
+ @pytest.fixture
+ def fix():
+ return 1
+ """
+ ),
+ encoding="utf-8",
+ )
+ foo_path.joinpath("test_foo.py").write_text(
+ "def test_foo(fix): assert fix == 1", encoding="utf-8"
+ )
+
+ # Tests in `food/` should not see the conftest fixture from `foo/`
+ food_path = pytester.mkpydir("food")
+ food_path.joinpath("test_food.py").write_text(
+ "def test_food(fix): assert fix == 1", encoding="utf-8"
+ )
+
+ res = pytester.runpytest()
+ assert res.ret == 1
+
+ res.stdout.fnmatch_lines(
+ [
+ "*ERROR at setup of test_food*",
+ "E*fixture 'fix' not found",
+ "*1 passed, 1 error*",
+ ]
+ )
+
+
+def test_collect_init_tests(pytester: Pytester) -> None:
+ """Check that we collect files from __init__.py files when they patch the 'python_files' (#3773)"""
+ p = pytester.copy_example("collect/collect_init_tests")
+ result = pytester.runpytest(p, "--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+ result = pytester.runpytest("./tests", "--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+ # Ignores duplicates with "." and pkginit (#4310).
+ result = pytester.runpytest("./tests", ".", "--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+ # Same as before, but different order.
+ result = pytester.runpytest(".", "tests", "--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 2 items",
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+ result = pytester.runpytest("./tests/test_foo.py", "--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+ result.stdout.no_fnmatch_line("*test_init*")
+ result = pytester.runpytest("./tests/__init__.py", "--collect-only")
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+ result.stdout.no_fnmatch_line("*test_foo*")
+
+
+def test_collect_invalid_signature_message(pytester: Pytester) -> None:
+ """Check that we issue a proper message when we can't determine the signature of a test
+ function (#4026).
+ """
+ pytester.makepyfile(
+ """
+ import pytest
+
+ class TestCase:
+ @pytest.fixture
+ def fix():
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(
+ ["Could not determine arguments of *.fix *: invalid method signature"]
+ )
+
+
+def test_collect_handles_raising_on_dunder_class(pytester: Pytester) -> None:
+ """Handle proxy classes like Django's LazySettings that might raise on
+ ``isinstance`` (#4266).
+ """
+ pytester.makepyfile(
+ """
+ class ImproperlyConfigured(Exception):
+ pass
+
+ class RaisesOnGetAttr(object):
+ def raises(self):
+ raise ImproperlyConfigured
+
+ __class__ = property(raises)
+
+ raises = RaisesOnGetAttr()
+
+
+ def test_1():
+ pass
+ """
+ )
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=1)
+ assert result.ret == 0
+
+
+def test_collect_with_chdir_during_import(pytester: Pytester) -> None:
+ subdir = pytester.mkdir("sub")
+ pytester.path.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ f"""
+ import os
+ os.chdir({str(subdir)!r})
+ """
+ ),
+ encoding="utf-8",
+ )
+ pytester.makepyfile(
+ f"""
+ def test_1():
+ import os
+ assert os.getcwd() == {str(subdir)!r}
+ """
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines(["*1 passed in*"])
+ assert result.ret == 0
+
+ # Handles relative testpaths.
+ pytester.makeini(
+ """
+ [pytest]
+ testpaths = .
+ """
+ )
+ result = pytester.runpytest("--collect-only")
+ result.stdout.fnmatch_lines(["collected 1 item"])
+
+
+def test_collect_pyargs_with_testpaths(
+ pytester: Pytester, monkeypatch: MonkeyPatch
+) -> None:
+ testmod = pytester.mkdir("testmod")
+ # NOTE: __init__.py is not collected since it does not match python_files.
+ testmod.joinpath("__init__.py").write_text(
+ "def test_func(): pass", encoding="utf-8"
+ )
+ testmod.joinpath("test_file.py").write_text(
+ "def test_func(): pass", encoding="utf-8"
+ )
+
+ root = pytester.mkdir("root")
+ root.joinpath("pytest.ini").write_text(
+ textwrap.dedent(
+ """
+ [pytest]
+ addopts = --pyargs
+ testpaths = testmod
+ """
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("PYTHONPATH", str(pytester.path), prepend=os.pathsep)
+ with monkeypatch.context() as mp:
+ mp.chdir(root)
+ result = pytester.runpytest_subprocess()
+ result.assert_outcomes(passed=1)
+
+
+def test_initial_conftests_with_testpaths(pytester: Pytester) -> None:
+ """The testpaths config option should load conftests in those paths as 'initial' (#10987)."""
+ p = pytester.mkdir("some_path")
+ p.joinpath("conftest.py").write_text(
+ textwrap.dedent(
+ """
+ def pytest_sessionstart(session):
+ raise Exception("pytest_sessionstart hook successfully run")
+ """
+ ),
+ encoding="utf-8",
+ )
+ pytester.makeini(
+ """
+ [pytest]
+ testpaths = some_path
+ """
+ )
+
+ # No command line args - falls back to testpaths.
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.INTERNAL_ERROR
+ result.stdout.fnmatch_lines(
+ "INTERNALERROR* Exception: pytest_sessionstart hook successfully run"
+ )
+
+ # No fallback.
+ result = pytester.runpytest(".")
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+
+
+def test_large_option_breaks_initial_conftests(pytester: Pytester) -> None:
+ """Long option values do not break initial conftests handling (#10169)."""
+ option_value = "x" * 1024 * 1000
+ pytester.makeconftest(
+ """
+ def pytest_addoption(parser):
+ parser.addoption("--xx", default=None)
+ """
+ )
+ pytester.makepyfile(
+ f"""
+ def test_foo(request):
+ assert request.config.getoption("xx") == {option_value!r}
+ """
+ )
+ result = pytester.runpytest(f"--xx={option_value}")
+ assert result.ret == 0
+
+
+def test_collect_symlink_file_arg(pytester: Pytester) -> None:
+ """Collect a direct symlink works even if it does not match python_files (#4325)."""
+ real = pytester.makepyfile(
+ real="""
+ def test_nodeid(request):
+ assert request.node.nodeid == "symlink.py::test_nodeid"
+ """
+ )
+ symlink = pytester.path.joinpath("symlink.py")
+ symlink_or_skip(real, symlink)
+ result = pytester.runpytest("-v", symlink)
+ result.stdout.fnmatch_lines(["symlink.py::test_nodeid PASSED*", "*1 passed in*"])
+ assert result.ret == 0
+
+
+def test_collect_symlink_out_of_tree(pytester: Pytester) -> None:
+ """Test collection of symlink via out-of-tree rootdir."""
+ sub = pytester.mkdir("sub")
+ real = sub.joinpath("test_real.py")
+ real.write_text(
+ textwrap.dedent(
+ """
+ def test_nodeid(request):
+ # Should not contain sub/ prefix.
+ assert request.node.nodeid == "test_real.py::test_nodeid"
+ """
+ ),
+ encoding="utf-8",
+ )
+
+ out_of_tree = pytester.mkdir("out_of_tree")
+ symlink_to_sub = out_of_tree.joinpath("symlink_to_sub")
+ symlink_or_skip(sub, symlink_to_sub)
+ os.chdir(sub)
+ result = pytester.runpytest("-vs", f"--rootdir={sub}", symlink_to_sub)
+ result.stdout.fnmatch_lines(
+ [
+ # Should not contain "sub/"!
+ "test_real.py::test_nodeid PASSED"
+ ]
+ )
+ assert result.ret == 0
+
+
+def test_collect_symlink_dir(pytester: Pytester) -> None:
+ """A symlinked directory is collected."""
+ dir = pytester.mkdir("dir")
+ dir.joinpath("test_it.py").write_text("def test_it(): pass", "utf-8")
+ symlink_or_skip(pytester.path.joinpath("symlink_dir"), dir)
+ result = pytester.runpytest()
+ result.assert_outcomes(passed=2)
+
+
+def test_collectignore_via_conftest(pytester: Pytester) -> None:
+ """collect_ignore in parent conftest skips importing child (issue #4592)."""
+ tests = pytester.mkpydir("tests")
+ tests.joinpath("conftest.py").write_text(
+ "collect_ignore = ['ignore_me']", encoding="utf-8"
+ )
+
+ ignore_me = tests.joinpath("ignore_me")
+ ignore_me.mkdir()
+ ignore_me.joinpath("__init__.py").touch()
+ ignore_me.joinpath("conftest.py").write_text(
+ "assert 0, 'should_not_be_called'", encoding="utf-8"
+ )
+
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.NO_TESTS_COLLECTED
+
+
+def test_collect_pkg_init_and_file_in_args(pytester: Pytester) -> None:
+ subdir = pytester.mkdir("sub")
+ init = subdir.joinpath("__init__.py")
+ init.write_text("def test_init(): pass", encoding="utf-8")
+ p = subdir.joinpath("test_file.py")
+ p.write_text("def test_file(): pass", encoding="utf-8")
+
+ # Just the package directory, the __init__.py module is filtered out.
+ result = pytester.runpytest("-v", subdir)
+ result.stdout.fnmatch_lines(
+ [
+ "sub/test_file.py::test_file PASSED*",
+ "*1 passed in*",
+ ]
+ )
+
+ # But it's included if specified directly.
+ result = pytester.runpytest("-v", init, p)
+ result.stdout.fnmatch_lines(
+ [
+ "sub/__init__.py::test_init PASSED*",
+ "sub/test_file.py::test_file PASSED*",
+ "*2 passed in*",
+ ]
+ )
+
+ # Or if the pattern allows it.
+ result = pytester.runpytest("-v", "-o", "python_files=*.py", subdir)
+ result.stdout.fnmatch_lines(
+ [
+ "sub/__init__.py::test_init PASSED*",
+ "sub/test_file.py::test_file PASSED*",
+ "*2 passed in*",
+ ]
+ )
+
+
+def test_collect_pkg_init_only(pytester: Pytester) -> None:
+ subdir = pytester.mkdir("sub")
+ init = subdir.joinpath("__init__.py")
+ init.write_text("def test_init(): pass", encoding="utf-8")
+
+ result = pytester.runpytest(subdir)
+ result.stdout.fnmatch_lines(["*no tests ran in*"])
+
+ result = pytester.runpytest("-v", init)
+ result.stdout.fnmatch_lines(["sub/__init__.py::test_init PASSED*", "*1 passed in*"])
+
+ result = pytester.runpytest("-v", "-o", "python_files=*.py", subdir)
+ result.stdout.fnmatch_lines(["sub/__init__.py::test_init PASSED*", "*1 passed in*"])
+
+
+@pytest.mark.parametrize("use_pkg", (True, False))
+def test_collect_sub_with_symlinks(use_pkg: bool, pytester: Pytester) -> None:
+ """Collection works with symlinked files and broken symlinks"""
+ sub = pytester.mkdir("sub")
+ if use_pkg:
+ sub.joinpath("__init__.py").touch()
+ sub.joinpath("test_file.py").write_text("def test_file(): pass", encoding="utf-8")
+
+ # Create a broken symlink.
+ symlink_or_skip("test_doesnotexist.py", sub.joinpath("test_broken.py"))
+
+ # Symlink that gets collected.
+ symlink_or_skip("test_file.py", sub.joinpath("test_symlink.py"))
+
+ result = pytester.runpytest("-v", str(sub))
+ result.stdout.fnmatch_lines(
+ [
+ "sub/test_file.py::test_file PASSED*",
+ "sub/test_symlink.py::test_file PASSED*",
+ "*2 passed in*",
+ ]
+ )
+
+
+def test_collector_respects_tbstyle(pytester: Pytester) -> None:
+ p1 = pytester.makepyfile("assert 0")
+ result = pytester.runpytest(p1, "--tb=native")
+ assert result.ret == ExitCode.INTERRUPTED
+ result.stdout.fnmatch_lines(
+ [
+ "*_ ERROR collecting test_collector_respects_tbstyle.py _*",
+ "Traceback (most recent call last):",
+ ' File "*/test_collector_respects_tbstyle.py", line 1, in ',
+ " assert 0",
+ "AssertionError: assert 0",
+ "*! Interrupted: 1 error during collection !*",
+ "*= 1 error in *",
+ ]
+ )
+
+
+def test_does_not_eagerly_collect_packages(pytester: Pytester) -> None:
+ pytester.makepyfile("def test(): pass")
+ pydir = pytester.mkpydir("foopkg")
+ pydir.joinpath("__init__.py").write_text("assert False", encoding="utf-8")
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.OK
+
+
+def test_does_not_put_src_on_path(pytester: Pytester) -> None:
+ # `src` is not on sys.path so it should not be importable
+ ensure_file(pytester.path / "src/nope/__init__.py")
+ pytester.makepyfile(
+ "import pytest\n"
+ "def test():\n"
+ " with pytest.raises(ImportError):\n"
+ " import nope\n"
+ )
+ result = pytester.runpytest()
+ assert result.ret == ExitCode.OK
+
+
+def test_fscollector_from_parent(pytester: Pytester, request: FixtureRequest) -> None:
+ """Ensure File.from_parent can forward custom arguments to the constructor.
+
+ Context: https://github.com/pytest-dev/pytest-cpp/pull/47
+ """
+
+ class MyCollector(pytest.File):
+ def __init__(self, *k, x, **kw):
+ super().__init__(*k, **kw)
+ self.x = x
+
+ def collect(self):
+ raise NotImplementedError()
+
+ collector = MyCollector.from_parent(
+ parent=request.session, path=pytester.path / "foo", x=10
+ )
+ assert collector.x == 10
+
+
+def test_class_from_parent(request: FixtureRequest) -> None:
+ """Ensure Class.from_parent can forward custom arguments to the constructor."""
+
+ class MyCollector(pytest.Class):
+ def __init__(self, name, parent, x):
+ super().__init__(name, parent)
+ self.x = x
+
+ @classmethod
+ def from_parent(cls, parent, *, name, x): # type: ignore[override]
+ return super().from_parent(parent=parent, name=name, x=x)
+
+ collector = MyCollector.from_parent(parent=request.session, name="foo", x=10)
+ assert collector.x == 10
+
+
+class TestImportModeImportlib:
+ def test_collect_duplicate_names(self, pytester: Pytester) -> None:
+ """--import-mode=importlib can import modules with same names that are not in packages."""
+ pytester.makepyfile(
+ **{
+ "tests_a/test_foo.py": "def test_foo1(): pass",
+ "tests_b/test_foo.py": "def test_foo2(): pass",
+ }
+ )
+ result = pytester.runpytest("-v", "--import-mode=importlib")
+ result.stdout.fnmatch_lines(
+ [
+ "tests_a/test_foo.py::test_foo1 *",
+ "tests_b/test_foo.py::test_foo2 *",
+ "* 2 passed in *",
+ ]
+ )
+
+ def test_conftest(self, pytester: Pytester) -> None:
+ """Directory containing conftest modules are not put in sys.path as a side-effect of
+ importing them."""
+ tests_dir = pytester.path.joinpath("tests")
+ pytester.makepyfile(
+ **{
+ "tests/conftest.py": "",
+ "tests/test_foo.py": f"""
+ import sys
+ def test_check():
+ assert r"{tests_dir}" not in sys.path
+ """,
+ }
+ )
+ result = pytester.runpytest("-v", "--import-mode=importlib")
+ result.stdout.fnmatch_lines(["* 1 passed in *"])
+
+ def setup_conftest_and_foo(self, pytester: Pytester) -> None:
+ """Setup a tests directory to be used to test if modules in that directory can be imported
+ due to side-effects of --import-mode or not."""
+ pytester.makepyfile(
+ **{
+ "tests/conftest.py": "",
+ "tests/foo.py": """
+ def foo(): return 42
+ """,
+ "tests/test_foo.py": """
+ def test_check():
+ from foo import foo
+ assert foo() == 42
+ """,
+ }
+ )
+
+ def test_modules_importable_as_side_effect(self, pytester: Pytester) -> None:
+ """In import-modes `prepend` and `append`, we are able to import modules from directories
+ containing conftest.py files due to the side effect of changing sys.path."""
+ self.setup_conftest_and_foo(pytester)
+ result = pytester.runpytest("-v", "--import-mode=prepend")
+ result.stdout.fnmatch_lines(["* 1 passed in *"])
+
+ def test_modules_not_importable_as_side_effect(self, pytester: Pytester) -> None:
+ """In import-mode `importlib`, modules in directories containing conftest.py are not
+ importable, as don't change sys.path or sys.modules as side effect of importing
+ the conftest.py file.
+ """
+ self.setup_conftest_and_foo(pytester)
+ result = pytester.runpytest("-v", "--import-mode=importlib")
+ result.stdout.fnmatch_lines(
+ [
+ "*ModuleNotFoundError: No module named 'foo'",
+ "tests?test_foo.py:2: ModuleNotFoundError",
+ "* 1 failed in *",
+ ]
+ )
+
+ def test_using_python_path(self, pytester: Pytester) -> None:
+ """
+ Dummy modules created by insert_missing_modules should not get in
+ the way of modules that could be imported via python path (#9645).
+ """
+ pytester.makeini(
+ """
+ [pytest]
+ pythonpath = .
+ addopts = --import-mode importlib
+ """
+ )
+ pytester.makepyfile(
+ **{
+ "tests/__init__.py": "",
+ "tests/conftest.py": "",
+ "tests/subpath/__init__.py": "",
+ "tests/subpath/helper.py": "",
+ "tests/subpath/test_something.py": """
+ import tests.subpath.helper
+
+ def test_something():
+ assert True
+ """,
+ }
+ )
+ result = pytester.runpytest()
+ result.stdout.fnmatch_lines("*1 passed in*")
+
+
+def test_does_not_crash_on_error_from_decorated_function(pytester: Pytester) -> None:
+ """Regression test for an issue around bad exception formatting due to
+ assertion rewriting mangling lineno's (#4984)."""
+ pytester.makepyfile(
+ """
+ @pytest.fixture
+ def a(): return 4
+ """
+ )
+ result = pytester.runpytest()
+ # Not INTERNAL_ERROR
+ assert result.ret == ExitCode.INTERRUPTED
+
+
+def test_does_not_crash_on_recursive_symlink(pytester: Pytester) -> None:
+ """Regression test for an issue around recursive symlinks (#7951)."""
+ symlink_or_skip("recursive", pytester.path.joinpath("recursive"))
+ pytester.makepyfile(
+ """
+ def test_foo(): assert True
+ """
+ )
+ result = pytester.runpytest()
+
+ assert result.ret == ExitCode.OK
+ assert result.parseoutcomes() == {"passed": 1}
+
+
+@pytest.mark.skipif(not sys.platform.startswith("win"), reason="Windows only")
+def test_collect_short_file_windows(pytester: Pytester) -> None:
+ """Reproducer for #11895: short paths not collected on Windows."""
+ short_path = tempfile.mkdtemp()
+ if "~" not in short_path: # pragma: no cover
+ if running_on_ci():
+ # On CI, we are expecting that under the current GitHub actions configuration,
+ # tempfile.mkdtemp() is producing short paths, so we want to fail to prevent
+ # this from silently changing without us noticing.
+ pytest.fail(
+ f"tempfile.mkdtemp() failed to produce a short path on CI: {short_path}"
+ )
+ else:
+ # We want to skip failing this test locally in this situation because
+ # depending on the local configuration tempfile.mkdtemp() might not produce a short path:
+ # For example, user might have configured %TEMP% exactly to avoid generating short paths.
+ pytest.skip(
+ f"tempfile.mkdtemp() failed to produce a short path: {short_path}, skipping"
+ )
+
+ test_file = Path(short_path).joinpath("test_collect_short_file_windows.py")
+ test_file.write_text("def test(): pass", encoding="UTF-8")
+ result = pytester.runpytest(short_path)
+ assert result.parseoutcomes() == {"passed": 1}
+
+
+def test_collect_short_file_windows_multi_level_symlink(
+ pytester: Pytester,
+ request: FixtureRequest,
+) -> None:
+ """Regression test for multi-level Windows short-path comparison with
+ symlinks.
+
+ Previously, when matching collection arguments against collected nodes on
+ Windows, the short path fallback resolved symlinks. With a chain a -> b ->
+ target, comparing 'a' against 'b' would incorrectly succeed because both
+ resolved to 'target', which could cause incorrect matching or duplicate
+ collection.
+ """
+ # Prepare target directory with a test file.
+ short_path = Path(tempfile.mkdtemp())
+ request.addfinalizer(lambda: shutil.rmtree(short_path, ignore_errors=True))
+ target = short_path / "target"
+ target.mkdir()
+ (target / "test_chain.py").write_text("def test_chain(): pass", encoding="UTF-8")
+
+ # Create multi-level symlink chain: a -> b -> target.
+ b = short_path / "b"
+ a = short_path / "a"
+ symlink_or_skip(target, b, target_is_directory=True)
+ symlink_or_skip(b, a, target_is_directory=True)
+
+ # Collect via the first symlink; should find exactly one test.
+ result = pytester.runpytest(a)
+ result.assert_outcomes(passed=1)
+
+ # Collect via the intermediate symlink; also exactly one test.
+ result = pytester.runpytest(b)
+ result.assert_outcomes(passed=1)
+
+
+def test_pyargs_collection_tree(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
+ """When using `--pyargs`, the collection tree of a pyargs collection
+ argument should only include parents in the import path, not up to confcutdir.
+
+ Regression test for #11904.
+ """
+ site_packages = pytester.path / "venv/lib/site-packages"
+ site_packages.mkdir(parents=True)
+ monkeypatch.syspath_prepend(site_packages)
+ pytester.makepyfile(
+ **{
+ "venv/lib/site-packages/pkg/__init__.py": "",
+ "venv/lib/site-packages/pkg/sub/__init__.py": "",
+ "venv/lib/site-packages/pkg/sub/test_it.py": "def test(): pass",
+ }
+ )
+
+ result = pytester.runpytest("--pyargs", "--collect-only", "pkg.sub.test_it")
+ assert result.ret == ExitCode.OK
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ ],
+ consecutive=True,
+ )
+
+ # Now with an unrelated rootdir with unrelated files.
+ monkeypatch.chdir(tempfile.gettempdir())
+
+ result = pytester.runpytest("--pyargs", "--collect-only", "pkg.sub.test_it")
+ assert result.ret == ExitCode.OK
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ ],
+ consecutive=True,
+ )
+
+
+def test_do_not_collect_symlink_siblings(
+ pytester: Pytester, tmp_path: Path, request: pytest.FixtureRequest
+) -> None:
+ """
+ Regression test for #12039: Do not collect from directories that are symlinks to other directories in the same path.
+
+ The check for short paths under Windows via os.path.samefile, introduced in #11936, also finds the symlinked
+ directory created by tmp_path/tmpdir.
+ """
+ # Use tmp_path because it creates a symlink with the name "current" next to the directory it creates.
+ symlink_path = tmp_path.parent / (tmp_path.name[:-1] + "current")
+ if not symlink_path.is_symlink(): # pragma: no cover
+ pytest.skip("Symlinks not supported in this environment")
+
+ # Create test file.
+ tmp_path.joinpath("test_foo.py").write_text("def test(): pass", encoding="UTF-8")
+
+ # Ensure we collect it only once if we pass the tmp_path.
+ result = pytester.runpytest(tmp_path, "-sv")
+ result.assert_outcomes(passed=1)
+
+ # Ensure we collect it only once if we pass the symlinked directory.
+ result = pytester.runpytest(symlink_path, "-sv")
+ result.assert_outcomes(passed=1)
+
+
+@pytest.mark.parametrize(
+ "exception_class, msg",
+ [
+ (KeyboardInterrupt, "*!!! KeyboardInterrupt !!!*"),
+ (SystemExit, "INTERNALERROR> SystemExit"),
+ ],
+)
+def test_respect_system_exceptions(
+ pytester: Pytester,
+ exception_class: type[BaseException],
+ msg: str,
+):
+ head = "Before exception"
+ tail = "After exception"
+ ensure_file(pytester.path / "test_eggs.py").write_text(
+ f"print('{head}')", encoding="UTF-8"
+ )
+ ensure_file(pytester.path / "test_ham.py").write_text(
+ f"raise {exception_class.__name__}()", encoding="UTF-8"
+ )
+ ensure_file(pytester.path / "test_spam.py").write_text(
+ f"print('{tail}')", encoding="UTF-8"
+ )
+
+ result = pytester.runpytest_subprocess("-s")
+ result.stdout.fnmatch_lines([f"*{head}*"])
+ result.stdout.fnmatch_lines([msg])
+ result.stdout.no_fnmatch_line(f"*{tail}*")
+
+
+def test_yield_disallowed_in_tests(pytester: Pytester):
+ """Ensure generator test functions with 'yield' fail collection (#12960)."""
+ pytester.makepyfile(
+ """
+ def test_with_yield():
+ yield 1
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 2
+ result.stdout.fnmatch_lines(
+ ["*'yield' keyword is allowed in fixtures, but not in tests (test_with_yield)*"]
+ )
+ # Assert that no tests were collected
+ result.stdout.fnmatch_lines(["*collected 0 items*"])
+
+
+def test_annotations_deferred_future(pytester: Pytester):
+ """Ensure stringified annotations don't raise any errors."""
+ pytester.makepyfile(
+ """
+ from __future__ import annotations
+ import pytest
+
+ @pytest.fixture
+ def func() -> X: ... # X is undefined
+
+ def test_func():
+ assert True
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+
+@pytest.mark.skipif(
+ sys.version_info < (3, 14), reason="Annotations are only skipped on 3.14+"
+)
+def test_annotations_deferred_314(pytester: Pytester):
+ """Ensure annotation eval is deferred."""
+ pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.fixture
+ def func() -> X: ... # X is undefined
+
+ def test_func():
+ assert True
+ """
+ )
+ result = pytester.runpytest()
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["*1 passed*"])
+
+
+@pytest.mark.parametrize("import_mode", ["prepend", "importlib", "append"])
+def test_namespace_packages(pytester: Pytester, import_mode: str):
+ pytester.makeini(
+ f"""
+ [pytest]
+ consider_namespace_packages = true
+ pythonpath = .
+ python_files = *.py
+ addopts = --import-mode {import_mode}
+ """
+ )
+ pytester.makepyfile(
+ **{
+ "pkg/module1.py": "def test_module1(): pass",
+ "pkg/subpkg_namespace/module2.py": "def test_module1(): pass",
+ "pkg/subpkg_regular/__init__.py": "",
+ "pkg/subpkg_regular/module3": "def test_module3(): pass",
+ }
+ )
+
+ # should collect when called with top-level package correctly
+ result = pytester.runpytest("--collect-only", "--pyargs", "pkg")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 3 items",
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+
+ # should also work when called against a more specific subpackage/module
+ result = pytester.runpytest("--collect-only", "--pyargs", "pkg.subpkg_namespace")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+
+ result = pytester.runpytest("--collect-only", "--pyargs", "pkg.subpkg_regular")
+ result.stdout.fnmatch_lines(
+ [
+ "collected 1 item",
+ "",
+ " ",
+ " ",
+ " ",
+ ]
+ )
+
+
+class TestOverlappingCollectionArguments:
+ """Test that overlapping collection arguments (e.g. `pytest a/b a
+ a/c::TestIt) are handled correctly (#12083)."""
+
+ @pytest.mark.parametrize("args", [("a", "a/b"), ("a/b", "a")])
+ def test_parent_child(self, pytester: Pytester, args: tuple[str, ...]) -> None:
+ """Test that 'pytest a a/b' and `pytest a/b a` collects all tests from 'a'."""
+ pytester.makepyfile(
+ **{
+ "a/test_a.py": """
+ def test_a1(): pass
+ def test_a2(): pass
+ """,
+ "a/b/test_b.py": """
+ def test_b1(): pass
+ def test_b2(): pass
+ """,
+ }
+ )
+
+ result = pytester.runpytest("--collect-only", *args)
+
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ def test_multiple_nested_paths(self, pytester: Pytester) -> None:
+ """Test that 'pytest a/b a a/b/c' collects all tests from 'a'."""
+ pytester.makepyfile(
+ **{
+ "a/test_a.py": """
+ def test_a(): pass
+ """,
+ "a/b/test_b.py": """
+ def test_b(): pass
+ """,
+ "a/b/c/test_c.py": """
+ def test_c(): pass
+ """,
+ }
+ )
+
+ result = pytester.runpytest("--collect-only", "a/b", "a", "a/b/c")
+
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ def test_same_path_twice(self, pytester: Pytester) -> None:
+ """Test that 'pytest a a' doesn't duplicate tests."""
+ pytester.makepyfile(
+ **{
+ "a/test_a.py": """
+ def test_a(): pass
+ """,
+ }
+ )
+
+ result = pytester.runpytest("--collect-only", "a", "a")
+
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ def test_keep_duplicates_flag(self, pytester: Pytester) -> None:
+ """Test that --keep-duplicates allows duplication."""
+ pytester.makepyfile(
+ **{
+ "a/test_a.py": """
+ def test_a(): pass
+ """,
+ "a/b/test_b.py": """
+ def test_b(): pass
+ """,
+ }
+ )
+
+ result = pytester.runpytest("--collect-only", "--keep-duplicates", "a", "a/b")
+
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ def test_specific_file_then_parent_dir(self, pytester: Pytester) -> None:
+ """Test that 'pytest a/test_a.py a' collects all tests from 'a'."""
+ pytester.makepyfile(
+ **{
+ "a/test_a.py": """
+ def test_a(): pass
+ """,
+ "a/test_other.py": """
+ def test_other(): pass
+ """,
+ }
+ )
+
+ result = pytester.runpytest("--collect-only", "a/test_a.py", "a")
+
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ def test_package_scope_fixture_with_overlapping_paths(
+ self, pytester: Pytester
+ ) -> None:
+ """Test that package-scoped fixtures work correctly with overlapping paths."""
+ pytester.makepyfile(
+ **{
+ "pkg/__init__.py": "",
+ "pkg/test_pkg.py": """
+ import pytest
+
+ counter = {"value": 0}
+
+ @pytest.fixture(scope="package")
+ def pkg_fixture():
+ counter["value"] += 1
+ return counter["value"]
+
+ def test_pkg1(pkg_fixture):
+ assert pkg_fixture == 1
+
+ def test_pkg2(pkg_fixture):
+ assert pkg_fixture == 1
+ """,
+ "pkg/sub/__init__.py": "",
+ "pkg/sub/test_sub.py": """
+ def test_sub(): pass
+ """,
+ }
+ )
+
+ # Package fixture should run only once even with overlapping paths.
+ result = pytester.runpytest("pkg", "pkg/sub", "pkg", "-v")
+ result.assert_outcomes(passed=3)
+
+ def test_execution_order_preserved(self, pytester: Pytester) -> None:
+ """Test that test execution order follows argument order."""
+ pytester.makepyfile(
+ **{
+ "a/test_a.py": """
+ def test_a(): pass
+ """,
+ "b/test_b.py": """
+ def test_b(): pass
+ """,
+ }
+ )
+
+ result = pytester.runpytest("--collect-only", "b", "a", "b/test_b.py::test_b")
+
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ def test_overlapping_node_ids_class_and_method(self, pytester: Pytester) -> None:
+ """Test that overlapping node IDs are handled correctly."""
+ pytester.makepyfile(
+ test_nodeids="""
+ class TestClass:
+ def test_method1(self): pass
+ def test_method2(self): pass
+ def test_method3(self): pass
+
+ def test_function(): pass
+ """
+ )
+
+ # Class then specific method.
+ result = pytester.runpytest(
+ "--collect-only",
+ "test_nodeids.py::TestClass",
+ "test_nodeids.py::TestClass::test_method2",
+ )
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ # Specific method then class.
+ result = pytester.runpytest(
+ "--collect-only",
+ "test_nodeids.py::TestClass::test_method3",
+ "test_nodeids.py::TestClass",
+ )
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ def test_overlapping_node_ids_file_and_class(self, pytester: Pytester) -> None:
+ """Test that file-level and class-level selections work correctly."""
+ pytester.makepyfile(
+ test_file="""
+ class TestClass:
+ def test_method(self): pass
+
+ class TestOther:
+ def test_other(self): pass
+
+ def test_function(): pass
+ """
+ )
+
+ # File then class.
+ result = pytester.runpytest(
+ "--collect-only", "test_file.py", "test_file.py::TestClass"
+ )
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ # Class then file.
+ result = pytester.runpytest(
+ "--collect-only", "test_file.py::TestClass", "test_file.py"
+ )
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ def test_same_node_id_twice(self, pytester: Pytester) -> None:
+ """Test that the same node ID specified twice is collected only once."""
+ pytester.makepyfile(
+ test_dup="""
+ def test_one(): pass
+ def test_two(): pass
+ """
+ )
+
+ result = pytester.runpytest(
+ "--collect-only",
+ "test_dup.py::test_one",
+ "test_dup.py::test_one",
+ )
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ "",
+ ],
+ consecutive=True,
+ )
+
+ def test_overlapping_with_parametrization(self, pytester: Pytester) -> None:
+ """Test overlapping with parametrized tests."""
+ pytester.makepyfile(
+ test_param="""
+ import pytest
+
+ @pytest.mark.parametrize("n", [1, 2])
+ def test_param(n): pass
+
+ class TestClass:
+ @pytest.mark.parametrize("x", ["a", "b"])
+ def test_method(self, x): pass
+ """
+ )
+
+ result = pytester.runpytest(
+ "--collect-only",
+ "test_param.py::test_param[2]",
+ "test_param.py::TestClass::test_method[a]",
+ "test_param.py",
+ )
+ result.stdout.fnmatch_lines(
+ [
+ "",
+ " ",
+ " ",
+ "