Debian Codegraph @

doc/en/example/special.rst

raw
1 A session-fixture which can look at all collected tests
2 ----------------------------------------------------------------
3
4 A session-scoped fixture effectively has access to all
5 collected test items. Here is an example of a fixture
6 function which walks all collected tests and looks
7 if their test class defines a ``callme`` method and
8 calls it:
9
10 .. code-block:: python
11
12 # content of conftest.py
13
14 import pytest
15
16
17 @pytest.fixture(scope="session", autouse=True)
18 def callattr_ahead_of_alltests(request):
19 print("callattr_ahead_of_alltests called")
20 seen = {None}
21 session = request.node
22 for item in session.items:
23 cls = item.getparent(pytest.Class)
24 if cls not in seen:
25 if hasattr(cls.obj, "callme"):
26 cls.obj.callme()
27 seen.add(cls)
28
29 test classes may now define a ``callme`` method which
30 will be called ahead of running any tests:
31
32 .. code-block:: python
33
34 # content of test_module.py
35
36
37 class TestHello:
38 @classmethod
39 def callme(cls):
40 print("callme called!")
41
42 def test_method1(self):
43 print("test_method1 called")
44
45 def test_method2(self):
46 print("test_method2 called")
47
48
49 class TestOther:
50 @classmethod
51 def callme(cls):
52 print("callme other called")
53
54 def test_other(self):
55 print("test other")
56
57
58 # works with unittest as well ...
59 import unittest
60
61
62 class SomeTest(unittest.TestCase):
63 @classmethod
64 def callme(self):
65 print("SomeTest callme called")
66
67 def test_unit1(self):
68 print("test_unit1 method called")
69
70 If you run this without output capturing:
71
72 .. code-block:: pytest
73
74 $ pytest -q -s test_module.py
75 callattr_ahead_of_alltests called
76 callme called!
77 callme other called
78 SomeTest callme called
79 test_method1 called
80 .test_method2 called
81 .test other
82 .test_unit1 method called
83 .
84 4 passed in 0.12s