Skip to content

Commit 54ae27f

Browse files
Merge pull request #7252 from symonk/6900-class-per-instance-of-test-docs
document class instantiation for tests inside classes
2 parents 981b096 + 5061a47 commit 54ae27f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

doc/en/getting-started.rst

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,57 @@ Once you develop multiple tests, you may want to group them into a class. pytest
153153
154154
The first test passed and the second failed. You can easily see the intermediate values in the assertion to help you understand the reason for the failure.
155155

156+
Grouping tests in classes can be beneficial for the following reasons:
157+
158+
* Test organization
159+
* Sharing fixtures for tests only in that particular class
160+
* Applying marks at the class level and having them implicitly apply to all tests
161+
162+
Something to be aware of when grouping tests inside classes is that each test has a unique instance of the class.
163+
Having each test share the same class instance would be very detrimental to test isolation and would promote poor test practices.
164+
This is outlined below:
165+
166+
.. code-block:: python
167+
168+
class TestClassDemoInstance:
169+
def test_one(self):
170+
assert 0
171+
172+
def test_two(self):
173+
assert 0
174+
175+
176+
.. code-block:: pytest
177+
178+
$ pytest -k TestClassDemoInstance -q
179+
180+
FF [100%]
181+
================================== FAILURES ===================================
182+
_______________________ TestClassDemoInstance.test_one ________________________
183+
184+
self = <test_example.TestClassDemoInstance object at 0x0000019BBB9EEDA0>
185+
request = <FixtureRequest for <Function test_one>>
186+
187+
def test_one(self, request):
188+
> assert 0
189+
E assert 0
190+
191+
testing\test_example.py:4: AssertionError
192+
_______________________ TestClassDemoInstance.test_two ________________________
193+
194+
self = <test_example.TestClassDemoInstance object at 0x0000019BBB9F3D68>
195+
request = <FixtureRequest for <Function test_two>>
196+
197+
def test_two(self, request):
198+
> assert 0
199+
E assert 0
200+
201+
testing\test_example.py:7: AssertionError
202+
=========================== short test summary info ===========================
203+
FAILED testing/test_example.py::TestClassDemoInstance::test_one - assert 0
204+
FAILED testing/test_example.py::TestClassDemoInstance::test_two - assert 0
205+
2 failed in 0.11s
206+
156207
Request a unique temporary directory for functional tests
157208
--------------------------------------------------------------
158209

0 commit comments

Comments
 (0)