Debian Codegraph @

doc/en/how-to/fixtures.rst

raw
1 .. _how-to-fixtures:
2
3 How to use fixtures
4 ====================
5
6 .. seealso:: :ref:`about-fixtures`
7 .. seealso:: :ref:`Fixtures reference <reference-fixtures>`
8
9
10 "Requesting" fixtures
11 ---------------------
12
13 At a basic level, test functions request fixtures they require by declaring
14 them as arguments.
15
16 When pytest goes to run a test, it looks at the parameters in that test
17 function's signature, and then searches for fixtures that have the same names as
18 those parameters. Once pytest finds them, it runs those fixtures, captures what
19 they returned (if anything), and passes those objects into the test function as
20 arguments.
21
22
23 Quick example
24 ^^^^^^^^^^^^^
25
26 .. code-block:: python
27
28 import pytest
29
30
31 class Fruit:
32 def __init__(self, name):
33 self.name = name
34 self.cubed = False
35
36 def cube(self):
37 self.cubed = True
38
39
40 class FruitSalad:
41 def __init__(self, *fruit_bowl):
42 self.fruit = fruit_bowl
43 self._cube_fruit()
44
45 def _cube_fruit(self):
46 for fruit in self.fruit:
47 fruit.cube()
48
49
50 # Arrange
51 @pytest.fixture
52 def fruit_bowl():
53 return [Fruit("apple"), Fruit("banana")]
54
55
56 def test_fruit_salad(fruit_bowl):
57 # Act
58 fruit_salad = FruitSalad(*fruit_bowl)
59
60 # Assert
61 assert all(fruit.cubed for fruit in fruit_salad.fruit)
62
63 In this example, ``test_fruit_salad`` "**requests**" ``fruit_bowl`` (i.e.
64 ``def test_fruit_salad(fruit_bowl):``), and when pytest sees this, it will
65 execute the ``fruit_bowl`` fixture function and pass the object it returns into
66 ``test_fruit_salad`` as the ``fruit_bowl`` argument.
67
68 Here's roughly
69 what's happening if we were to do it by hand:
70
71 .. code-block:: python
72
73 def fruit_bowl():
74 return [Fruit("apple"), Fruit("banana")]
75
76
77 def test_fruit_salad(fruit_bowl):
78 # Act
79 fruit_salad = FruitSalad(*fruit_bowl)
80
81 # Assert
82 assert all(fruit.cubed for fruit in fruit_salad.fruit)
83
84
85 # Arrange
86 bowl = fruit_bowl()
87 test_fruit_salad(fruit_bowl=bowl)
88
89
90 Fixtures can **request** other fixtures
91 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
92
93 One of pytest's greatest strengths is its extremely flexible fixture system. It
94 allows us to boil down complex requirements for tests into more simple and
95 organized functions, where we only need to have each one describe the things
96 they are dependent on. We'll get more into this further down, but for now,
97 here's a quick example to demonstrate how fixtures can use other fixtures:
98
99 .. code-block:: python
100
101 # contents of test_append.py
102 import pytest
103
104
105 # Arrange
106 @pytest.fixture
107 def first_entry():
108 return "a"
109
110
111 # Arrange
112 @pytest.fixture
113 def order(first_entry):
114 return [first_entry]
115
116
117 def test_string(order):
118 # Act
119 order.append("b")
120
121 # Assert
122 assert order == ["a", "b"]
123
124
125 Notice that this is the same example from above, but very little changed. The
126 fixtures in pytest **request** fixtures just like tests. All the same
127 **requesting** rules apply to fixtures that do for tests. Here's how this
128 example would work if we did it by hand:
129
130 .. code-block:: python
131
132 def first_entry():
133 return "a"
134
135
136 def order(first_entry):
137 return [first_entry]
138
139
140 def test_string(order):
141 # Act
142 order.append("b")
143
144 # Assert
145 assert order == ["a", "b"]
146
147
148 entry = first_entry()
149 the_list = order(first_entry=entry)
150 test_string(order=the_list)
151
152 Fixtures are reusable
153 ^^^^^^^^^^^^^^^^^^^^^
154
155 One of the things that makes pytest's fixture system so powerful, is that it
156 gives us the ability to define a generic setup step that can be reused over and
157 over, just like a normal function would be used. Two different tests can request
158 the same fixture and have pytest give each test their own result from that
159 fixture.
160
161 This is extremely useful for making sure tests aren't affected by each other. We
162 can use this system to make sure each test gets its own fresh batch of data and
163 is starting from a clean state so it can provide consistent, repeatable results.
164
165 Here's an example of how this can come in handy:
166
167 .. code-block:: python
168
169 # contents of test_append.py
170 import pytest
171
172
173 # Arrange
174 @pytest.fixture
175 def first_entry():
176 return "a"
177
178
179 # Arrange
180 @pytest.fixture
181 def order(first_entry):
182 return [first_entry]
183
184
185 def test_string(order):
186 # Act
187 order.append("b")
188
189 # Assert
190 assert order == ["a", "b"]
191
192
193 def test_int(order):
194 # Act
195 order.append(2)
196
197 # Assert
198 assert order == ["a", 2]
199
200
201 Each test here is being given its own copy of that ``list`` object,
202 which means the ``order`` fixture is getting executed twice (the same
203 is true for the ``first_entry`` fixture). If we were to do this by hand as
204 well, it would look something like this:
205
206 .. code-block:: python
207
208 def first_entry():
209 return "a"
210
211
212 def order(first_entry):
213 return [first_entry]
214
215
216 def test_string(order):
217 # Act
218 order.append("b")
219
220 # Assert
221 assert order == ["a", "b"]
222
223
224 def test_int(order):
225 # Act
226 order.append(2)
227
228 # Assert
229 assert order == ["a", 2]
230
231
232 entry = first_entry()
233 the_list = order(first_entry=entry)
234 test_string(order=the_list)
235
236 entry = first_entry()
237 the_list = order(first_entry=entry)
238 test_int(order=the_list)
239
240 A test/fixture can **request** more than one fixture at a time
241 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
242
243 Tests and fixtures aren't limited to **requesting** a single fixture at a time.
244 They can request as many as they like. Here's another quick example to
245 demonstrate:
246
247 .. code-block:: python
248
249 # contents of test_append.py
250 import pytest
251
252
253 # Arrange
254 @pytest.fixture
255 def first_entry():
256 return "a"
257
258
259 # Arrange
260 @pytest.fixture
261 def second_entry():
262 return 2
263
264
265 # Arrange
266 @pytest.fixture
267 def order(first_entry, second_entry):
268 return [first_entry, second_entry]
269
270
271 # Arrange
272 @pytest.fixture
273 def expected_list():
274 return ["a", 2, 3.0]
275
276
277 def test_string(order, expected_list):
278 # Act
279 order.append(3.0)
280
281 # Assert
282 assert order == expected_list
283
284 Fixtures can be **requested** more than once per test (return values are cached)
285 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
286
287 Fixtures can also be **requested** more than once during the same test, and
288 pytest won't execute them again for that test. This means we can **request**
289 fixtures in multiple fixtures that are dependent on them (and even again in the
290 test itself) without those fixtures being executed more than once.
291
292 .. code-block:: python
293
294 # contents of test_append.py
295 import pytest
296
297
298 # Arrange
299 @pytest.fixture
300 def first_entry():
301 return "a"
302
303
304 # Arrange
305 @pytest.fixture
306 def order():
307 return []
308
309
310 # Act
311 @pytest.fixture
312 def append_first(order, first_entry):
313 return order.append(first_entry)
314
315
316 def test_string_only(append_first, order, first_entry):
317 # Assert
318 assert order == [first_entry]
319
320 If a **requested** fixture was executed once for every time it was **requested**
321 during a test, then this test would fail because both ``append_first`` and
322 ``test_string_only`` would see ``order`` as an empty list (i.e. ``[]``), but
323 since the return value of ``order`` was cached (along with any side effects
324 executing it may have had) after the first time it was called, both the test and
325 ``append_first`` were referencing the same object, and the test saw the effect
326 ``append_first`` had on that object.
327
328 .. _`autouse`:
329 .. _`autouse fixtures`:
330
331 Autouse fixtures (fixtures you don't have to request)
332 -----------------------------------------------------
333
334 Sometimes you may want to have a fixture (or even several) that you know all
335 your tests will depend on. "Autouse" fixtures are a convenient way to make all
336 tests automatically **request** them. This can cut out a
337 lot of redundant **requests**, and can even provide more advanced fixture usage
338 (more on that further down).
339
340 We can make a fixture an autouse fixture by passing in ``autouse=True`` to the
341 fixture's decorator. Here's a simple example for how they can be used:
342
343 .. code-block:: python
344
345 # contents of test_append.py
346 import pytest
347
348
349 @pytest.fixture
350 def first_entry():
351 return "a"
352
353
354 @pytest.fixture
355 def order(first_entry):
356 return []
357
358
359 @pytest.fixture(autouse=True)
360 def append_first(order, first_entry):
361 return order.append(first_entry)
362
363
364 def test_string_only(order, first_entry):
365 assert order == [first_entry]
366
367
368 def test_string_and_int(order, first_entry):
369 order.append(2)
370 assert order == [first_entry, 2]
371
372 In this example, the ``append_first`` fixture is an autouse fixture. Because it
373 happens automatically, both tests are affected by it, even though neither test
374 **requested** it. That doesn't mean they *can't* be **requested** though; just
375 that it isn't *necessary*.
376
377 .. _smtpshared:
378
379 Scope: sharing fixtures across classes, modules, packages or session
380 --------------------------------------------------------------------
381
382 .. regendoc:wipe
383
384 Fixtures requiring network access depend on connectivity and are
385 usually time-expensive to create. Extending the previous example, we
386 can add a ``scope="module"`` parameter to the
387 :py:func:`@pytest.fixture <pytest.fixture>` invocation
388 to cause a ``smtp_connection`` fixture function, responsible to create a connection to a preexisting SMTP server, to only be invoked
389 once per test *module* (the default is to invoke once per test *function*).
390 Multiple test functions in a test module will thus
391 each receive the same ``smtp_connection`` fixture instance, thus saving time.
392 Possible values for ``scope`` are: ``function``, ``class``, ``module``, ``package`` or ``session``.
393
394 The next example puts the fixture function into a separate ``conftest.py`` file
395 so that tests from multiple test modules in the directory can
396 access the fixture function:
397
398 .. code-block:: python
399
400 # content of conftest.py
401 import smtplib
402
403 import pytest
404
405
406 @pytest.fixture(scope="module")
407 def smtp_connection():
408 return smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
409
410
411 .. code-block:: python
412
413 # content of test_module.py
414
415
416 def test_ehlo(smtp_connection):
417 response, msg = smtp_connection.ehlo()
418 assert response == 250
419 assert b"smtp.gmail.com" in msg
420 assert 0 # for demo purposes
421
422
423 def test_noop(smtp_connection):
424 response, msg = smtp_connection.noop()
425 assert response == 250
426 assert 0 # for demo purposes
427
428 Here, the ``test_ehlo`` needs the ``smtp_connection`` fixture value. pytest
429 will discover and call the :py:func:`@pytest.fixture <pytest.fixture>`
430 marked ``smtp_connection`` fixture function. Running the test looks like this:
431
432 .. code-block:: pytest
433
434 $ pytest test_module.py
435 =========================== test session starts ============================
436 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
437 rootdir: /home/sweet/project
438 collected 2 items
439
440 test_module.py FF [100%]
441
442 ================================= FAILURES =================================
443 ________________________________ test_ehlo _________________________________
444
445 smtp_connection = <smtplib.SMTP object at 0xdeadbeef0001>
446
447 def test_ehlo(smtp_connection):
448 response, msg = smtp_connection.ehlo()
449 assert response == 250
450 assert b"smtp.gmail.com" in msg
451 > assert 0 # for demo purposes
452 ^^^^^^^^
453 E assert 0
454
455 test_module.py:7: AssertionError
456 ________________________________ test_noop _________________________________
457
458 smtp_connection = <smtplib.SMTP object at 0xdeadbeef0001>
459
460 def test_noop(smtp_connection):
461 response, msg = smtp_connection.noop()
462 assert response == 250
463 > assert 0 # for demo purposes
464 ^^^^^^^^
465 E assert 0
466
467 test_module.py:13: AssertionError
468 ========================= short test summary info ==========================
469 FAILED test_module.py::test_ehlo - assert 0
470 FAILED test_module.py::test_noop - assert 0
471 ============================ 2 failed in 0.12s =============================
472
473 You see the two ``assert 0`` failing and more importantly you can also see
474 that the **exact same** ``smtp_connection`` object was passed into the
475 two test functions because pytest shows the incoming argument values in the
476 traceback. As a result, the two test functions using ``smtp_connection`` run
477 as quick as a single one because they reuse the same instance.
478
479 If you decide that you rather want to have a session-scoped ``smtp_connection``
480 instance, you can simply declare it:
481
482 .. code-block:: python
483
484 @pytest.fixture(scope="session")
485 def smtp_connection():
486 # the returned fixture value will be shared for
487 # all tests requesting it
488 ...
489
490
491 Fixture scopes
492 ^^^^^^^^^^^^^^
493
494 Fixtures are created when first requested by a test, and are destroyed based on their ``scope``:
495
496 * ``function``: the default scope, the fixture is destroyed at the end of the test.
497 * ``class``: the fixture is destroyed during teardown of the last test in the class.
498 * ``module``: the fixture is destroyed during teardown of the last test in the module.
499 * ``package``: the fixture is destroyed during teardown of the last test in the package where the fixture is defined, including sub-packages and sub-directories within it.
500 * ``session``: the fixture is destroyed at the end of the test session.
501
502 .. note::
503
504 Pytest only caches one instance of a fixture at a time, which
505 means that when using a parametrized fixture, pytest may invoke a fixture more than once in
506 the given scope.
507
508 .. _dynamic scope:
509
510 Dynamic scope
511 ^^^^^^^^^^^^^
512
513 .. versionadded:: 5.2
514
515 In some cases, you might want to change the scope of the fixture without changing the code.
516 To do that, pass a callable to ``scope``. The callable must return a string with a valid scope
517 and will be executed only once - during the fixture definition. It will be called with two
518 keyword arguments - ``fixture_name`` as a string and ``config`` with a configuration object.
519
520 This can be especially useful when dealing with fixtures that need time for setup, like spawning
521 a docker container. You can use the command-line argument to control the scope of the spawned
522 containers for different environments. See the example below.
523
524 .. code-block:: python
525
526 def determine_scope(fixture_name, config):
527 if config.getoption("--keep-containers", None):
528 return "session"
529 return "function"
530
531
532 @pytest.fixture(scope=determine_scope)
533 def docker_container():
534 yield spawn_container()
535
536
537
538 .. _`finalization`:
539
540 Teardown/Cleanup (AKA Fixture finalization)
541 -------------------------------------------
542
543 When we run our tests, we'll want to make sure they clean up after themselves so
544 they don't mess with any other tests (and also so that we don't leave behind a
545 mountain of test data to bloat the system). Fixtures in pytest offer a very
546 useful teardown system, which allows us to define the specific steps necessary
547 for each fixture to clean up after itself.
548
549 This system can be leveraged in two ways.
550
551 .. _`yield fixtures`:
552
553 1. ``yield`` fixtures (recommended)
554 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
555
556 .. regendoc: wipe
557
558 "Yield" fixtures ``yield`` instead of ``return``. With these
559 fixtures, we can run some code and pass an object back to the requesting
560 fixture/test, just like with the other fixtures. The only differences are:
561
562 1. ``return`` is swapped out for ``yield``.
563 2. Any teardown code for that fixture is placed *after* the ``yield``.
564
565 Once pytest figures out a linear order for the fixtures, it will run each one up
566 until it returns or yields, and then move on to the next fixture in the list to
567 do the same thing.
568
569 Once the test is finished, pytest will go back down the list of fixtures, but in
570 the *reverse order*, taking each one that yielded, and running the code inside
571 it that was *after* the ``yield`` statement.
572
573 As a simple example, consider this basic email module:
574
575 .. code-block:: python
576
577 # content of emaillib.py
578 class MailAdminClient:
579 def create_user(self):
580 return MailUser()
581
582 def delete_user(self, user):
583 # do some cleanup
584 pass
585
586
587 class MailUser:
588 def __init__(self):
589 self.inbox = []
590
591 def send_email(self, email, other):
592 other.inbox.append(email)
593
594 def clear_mailbox(self):
595 self.inbox.clear()
596
597
598 class Email:
599 def __init__(self, subject, body):
600 self.subject = subject
601 self.body = body
602
603 Let's say we want to test sending email from one user to another. We'll have to
604 first make each user, then send the email from one user to the other, and
605 finally assert that the other user received that message in their inbox. If we
606 want to clean up after the test runs, we'll likely have to make sure the other
607 user's mailbox is emptied before deleting that user, otherwise the system may
608 complain.
609
610 Here's what that might look like:
611
612 .. code-block:: python
613
614 # content of test_emaillib.py
615 from emaillib import Email, MailAdminClient
616
617 import pytest
618
619
620 @pytest.fixture
621 def mail_admin():
622 return MailAdminClient()
623
624
625 @pytest.fixture
626 def sending_user(mail_admin):
627 user = mail_admin.create_user()
628 yield user
629 mail_admin.delete_user(user)
630
631
632 @pytest.fixture
633 def receiving_user(mail_admin):
634 user = mail_admin.create_user()
635 yield user
636 user.clear_mailbox()
637 mail_admin.delete_user(user)
638
639
640 def test_email_received(sending_user, receiving_user):
641 email = Email(subject="Hey!", body="How's it going?")
642 sending_user.send_email(email, receiving_user)
643 assert email in receiving_user.inbox
644
645 Because ``receiving_user`` is the last fixture to run during setup, it's the first to run
646 during teardown.
647
648 There is a risk that even having the order right on the teardown side of things
649 doesn't guarantee a safe cleanup. That's covered in a bit more detail in
650 :ref:`safe teardowns`.
651
652 .. code-block:: pytest
653
654 $ pytest -q test_emaillib.py
655 . [100%]
656 1 passed in 0.12s
657
658 Handling errors for yield fixture
659 """""""""""""""""""""""""""""""""
660
661 If a yield fixture raises an exception before yielding, pytest won't try to run
662 the teardown code after that yield fixture's ``yield`` statement. But, for every
663 fixture that has already run successfully for that test, pytest will still
664 attempt to tear them down as it normally would.
665
666 2. Adding finalizers directly
667 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
668
669 While yield fixtures are considered to be the cleaner and more straightforward
670 option, there is another choice, and that is to add "finalizer" functions
671 directly to the test's `request-context`_ object. It brings a similar result as
672 yield fixtures, but requires a bit more verbosity.
673
674 In order to use this approach, we have to request the `request-context`_ object
675 (just like we would request another fixture) in the fixture we need to add
676 teardown code for, and then pass a callable, containing that teardown code, to
677 its ``addfinalizer`` method.
678
679 We have to be careful though, because pytest will run that finalizer once it's
680 been added, even if that fixture raises an exception after adding the finalizer.
681 So to make sure we don't run the finalizer code when we wouldn't need to, we
682 would only add the finalizer once the fixture would have done something that
683 we'd need to teardown.
684
685 Here's how the previous example would look using the ``addfinalizer`` method:
686
687 .. code-block:: python
688
689 # content of test_emaillib.py
690 from emaillib import Email, MailAdminClient
691
692 import pytest
693
694
695 @pytest.fixture
696 def mail_admin():
697 return MailAdminClient()
698
699
700 @pytest.fixture
701 def sending_user(mail_admin):
702 user = mail_admin.create_user()
703 yield user
704 mail_admin.delete_user(user)
705
706
707 @pytest.fixture
708 def receiving_user(mail_admin, request):
709 user = mail_admin.create_user()
710
711 def delete_user():
712 mail_admin.delete_user(user)
713
714 request.addfinalizer(delete_user)
715 return user
716
717
718 @pytest.fixture
719 def email(sending_user, receiving_user, request):
720 _email = Email(subject="Hey!", body="How's it going?")
721 sending_user.send_email(_email, receiving_user)
722
723 def empty_mailbox():
724 receiving_user.clear_mailbox()
725
726 request.addfinalizer(empty_mailbox)
727 return _email
728
729
730 def test_email_received(receiving_user, email):
731 assert email in receiving_user.inbox
732
733
734 It's a bit longer than yield fixtures and a bit more complex, but it
735 does offer some nuances for when you're in a pinch.
736
737 .. code-block:: pytest
738
739 $ pytest -q test_emaillib.py
740 . [100%]
741 1 passed in 0.12s
742
743 Note on finalizer order
744 """"""""""""""""""""""""
745
746 Finalizers are executed in a first-in-last-out order.
747 For yield fixtures, the first teardown code to run is from the right-most fixture, i.e. the last test parameter.
748
749
750 .. code-block:: python
751
752 # content of test_finalizers.py
753 import pytest
754
755
756 def test_bar(fix_w_yield1, fix_w_yield2):
757 print("test_bar")
758
759
760 @pytest.fixture
761 def fix_w_yield1():
762 yield
763 print("after_yield_1")
764
765
766 @pytest.fixture
767 def fix_w_yield2():
768 yield
769 print("after_yield_2")
770
771
772 .. code-block:: pytest
773
774 $ pytest -s test_finalizers.py
775 =========================== test session starts ============================
776 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
777 rootdir: /home/sweet/project
778 collected 1 item
779
780 test_finalizers.py test_bar
781 .after_yield_2
782 after_yield_1
783
784
785 ============================ 1 passed in 0.12s =============================
786
787 For finalizers, the first fixture to run is last call to `request.addfinalizer`.
788
789 .. code-block:: python
790
791 # content of test_finalizers.py
792 from functools import partial
793 import pytest
794
795
796 @pytest.fixture
797 def fix_w_finalizers(request):
798 request.addfinalizer(partial(print, "finalizer_2"))
799 request.addfinalizer(partial(print, "finalizer_1"))
800
801
802 def test_bar(fix_w_finalizers):
803 print("test_bar")
804
805
806 .. code-block:: pytest
807
808 $ pytest -s test_finalizers.py
809 =========================== test session starts ============================
810 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
811 rootdir: /home/sweet/project
812 collected 1 item
813
814 test_finalizers.py test_bar
815 .finalizer_1
816 finalizer_2
817
818
819 ============================ 1 passed in 0.12s =============================
820
821 This is so because yield fixtures use `addfinalizer` behind the scenes: when the fixture executes, `addfinalizer` registers a function that resumes the generator, which in turn calls the teardown code.
822
823
824 .. _`safe teardowns`:
825
826 Safe teardowns
827 --------------
828
829 The fixture system of pytest is *very* powerful, but it's still being run by a
830 computer, so it isn't able to figure out how to safely teardown everything we
831 throw at it. If we aren't careful, an error in the wrong spot might leave stuff
832 from our tests behind, and that can cause further issues pretty quickly.
833
834 For example, consider the following tests (based off of the mail example from
835 above):
836
837 .. code-block:: python
838
839 # content of test_emaillib.py
840 from emaillib import Email, MailAdminClient
841
842 import pytest
843
844
845 @pytest.fixture
846 def setup():
847 mail_admin = MailAdminClient()
848 sending_user = mail_admin.create_user()
849 receiving_user = mail_admin.create_user()
850 email = Email(subject="Hey!", body="How's it going?")
851 sending_user.send_email(email, receiving_user)
852 yield receiving_user, email
853 receiving_user.clear_mailbox()
854 mail_admin.delete_user(sending_user)
855 mail_admin.delete_user(receiving_user)
856
857
858 def test_email_received(setup):
859 receiving_user, email = setup
860 assert email in receiving_user.inbox
861
862 This version is a lot more compact, but it's also harder to read, doesn't have a
863 very descriptive fixture name, and none of the fixtures can be reused easily.
864
865 There's also a more serious issue, which is that if any of those steps in the
866 setup raise an exception, none of the teardown code will run.
867
868 One option might be to go with the ``addfinalizer`` method instead of yield
869 fixtures, but that might get pretty complex and difficult to maintain (and it
870 wouldn't be compact anymore).
871
872 .. code-block:: pytest
873
874 $ pytest -q test_emaillib.py
875 . [100%]
876 1 passed in 0.12s
877
878 .. _`safe fixture structure`:
879
880 Safe fixture structure
881 ^^^^^^^^^^^^^^^^^^^^^^
882
883 The safest and simplest fixture structure requires limiting fixtures to only
884 making one state-changing action each, and then bundling them together with
885 their teardown code, as :ref:`the email examples above <yield fixtures>` showed.
886
887 The chance that a state-changing operation can fail but still modify state is
888 negligible, as most of these operations tend to be `transaction
889 <https://en.wikipedia.org/wiki/Transaction_processing>`_-based (at least at the
890 level of testing where state could be left behind). So if we make sure that any
891 successful state-changing action gets torn down by moving it to a separate
892 fixture function and separating it from other, potentially failing
893 state-changing actions, then our tests will stand the best chance at leaving
894 the test environment the way they found it.
895
896 For an example, let's say we have a website with a login page, and we have
897 access to an admin API where we can generate users. For our test, we want to:
898
899 1. Create a user through that admin API
900 2. Launch a browser using Selenium
901 3. Go to the login page of our site
902 4. Log in as the user we created
903 5. Assert that their name is in the header of the landing page
904
905 We wouldn't want to leave that user in the system, nor would we want to leave
906 that browser session running, so we'll want to make sure the fixtures that
907 create those things clean up after themselves.
908
909 Here's what that might look like:
910
911 .. note::
912
913 For this example, certain fixtures (i.e. ``base_url`` and
914 ``admin_credentials``) are implied to exist elsewhere. So for now, let's
915 assume they exist, and we're just not looking at them.
916
917 .. code-block:: python
918
919 from uuid import uuid4
920 from urllib.parse import urljoin
921
922 from selenium.webdriver import Chrome
923 import pytest
924
925 from src.utils.pages import LoginPage, LandingPage
926 from src.utils import AdminApiClient
927 from src.utils.data_types import User
928
929
930 @pytest.fixture
931 def admin_client(base_url, admin_credentials):
932 return AdminApiClient(base_url, **admin_credentials)
933
934
935 @pytest.fixture
936 def user(admin_client):
937 _user = User(name="Susan", username=f"testuser-{uuid4()}", password="P4$$word")
938 admin_client.create_user(_user)
939 yield _user
940 admin_client.delete_user(_user)
941
942
943 @pytest.fixture
944 def driver():
945 _driver = Chrome()
946 yield _driver
947 _driver.quit()
948
949
950 @pytest.fixture
951 def login(driver, base_url, user):
952 driver.get(urljoin(base_url, "/login"))
953 page = LoginPage(driver)
954 page.login(user)
955
956
957 @pytest.fixture
958 def landing_page(driver, login):
959 return LandingPage(driver)
960
961
962 def test_name_on_landing_page_after_login(landing_page, user):
963 assert landing_page.header == f"Welcome, {user.name}!"
964
965 The way the dependencies are laid out means it's unclear if the ``user``
966 fixture would execute before the ``driver`` fixture. But that's ok, because
967 those are atomic operations, and so it doesn't matter which one runs first
968 because the sequence of events for the test is still `linearizable
969 <https://en.wikipedia.org/wiki/Linearizability>`_. But what *does* matter is
970 that, no matter which one runs first, if the one raises an exception while the
971 other would not have, neither will have left anything behind. If ``driver``
972 executes before ``user``, and ``user`` raises an exception, the driver will
973 still quit, and the user was never made. And if ``driver`` was the one to raise
974 the exception, then the driver would never have been started and the user would
975 never have been made.
976
977 .. note:
978
979 While the ``user`` fixture doesn't *actually* need to happen before the
980 ``driver`` fixture, if we made ``driver`` request ``user``, it might save
981 some time in the event that making the user raises an exception, since it
982 won't bother trying to start the driver, which is a fairly expensive
983 operation.
984
985
986 Running multiple ``assert`` statements safely
987 ---------------------------------------------
988
989 Sometimes you may want to run multiple asserts after doing all that setup, which
990 makes sense as, in more complex systems, a single action can kick off multiple
991 behaviors. pytest has a convenient way of handling this and it combines a bunch
992 of what we've gone over so far.
993
994 All that's needed is stepping up to a larger scope, then having the **act**
995 step defined as an autouse fixture, and finally, making sure all the fixtures
996 are targeting that higher level scope.
997
998 Let's pull :ref:`an example from above <safe fixture structure>`, and tweak it a
999 bit. Let's say that in addition to checking for a welcome message in the header,
1000 we also want to check for a sign out button, and a link to the user's profile.
1001
1002 Let's take a look at how we can structure that so we can run multiple asserts
1003 without having to repeat all those steps again.
1004
1005 .. note::
1006
1007 For this example, certain fixtures (i.e. ``base_url`` and
1008 ``admin_credentials``) are implied to exist elsewhere. So for now, let's
1009 assume they exist, and we're just not looking at them.
1010
1011 .. code-block:: python
1012
1013 # contents of tests/end_to_end/test_login.py
1014 from uuid import uuid4
1015 from urllib.parse import urljoin
1016
1017 from selenium.webdriver import Chrome
1018 import pytest
1019
1020 from src.utils.pages import LoginPage, LandingPage
1021 from src.utils import AdminApiClient
1022 from src.utils.data_types import User
1023
1024
1025 @pytest.fixture(scope="class")
1026 def admin_client(base_url, admin_credentials):
1027 return AdminApiClient(base_url, **admin_credentials)
1028
1029
1030 @pytest.fixture(scope="class")
1031 def user(admin_client):
1032 _user = User(name="Susan", username=f"testuser-{uuid4()}", password="P4$$word")
1033 admin_client.create_user(_user)
1034 yield _user
1035 admin_client.delete_user(_user)
1036
1037
1038 @pytest.fixture(scope="class")
1039 def driver():
1040 _driver = Chrome()
1041 yield _driver
1042 _driver.quit()
1043
1044
1045 @pytest.fixture(scope="class")
1046 def landing_page(driver, login):
1047 return LandingPage(driver)
1048
1049
1050 class TestLandingPageSuccess:
1051 @pytest.fixture(scope="class", autouse=True)
1052 @classmethod
1053 def login(cls, driver, base_url, user):
1054 driver.get(urljoin(base_url, "/login"))
1055 page = LoginPage(driver)
1056 page.login(user)
1057
1058 def test_name_in_header(self, landing_page, user):
1059 assert landing_page.header == f"Welcome, {user.name}!"
1060
1061 def test_sign_out_button(self, landing_page):
1062 assert landing_page.sign_out_button.is_displayed()
1063
1064 def test_profile_link(self, landing_page, user):
1065 profile_href = urljoin(base_url, f"/profile?id={user.profile_id}")
1066 assert landing_page.profile_link.get_attribute("href") == profile_href
1067
1068 Notice that the methods are only referencing ``self`` in the signature as a
1069 formality. No state is tied to the actual test class as it might be in the
1070 ``unittest.TestCase`` framework. Everything is managed by the pytest fixture
1071 system.
1072
1073 Each method only has to request the fixtures that it actually needs without
1074 worrying about order. This is because the **act** fixture is an autouse fixture,
1075 and it made sure all the other fixtures executed before it. There's no more
1076 changes of state that need to take place, so the tests are free to make as many
1077 non-state-changing queries as they want without risking stepping on the toes of
1078 the other tests.
1079
1080 The ``login`` fixture is defined inside the class as well, because not every one
1081 of the other tests in the module will be expecting a successful login, and the **act** may need to
1082 be handled a little differently for another test class. For example, if we
1083 wanted to write another test scenario around submitting bad credentials, we
1084 could handle it by adding something like this to the test file:
1085
1086 .. note:
1087
1088 It's assumed that the page object for this (i.e. ``LoginPage``) raises a
1089 custom exception, ``BadCredentialsException``, when it recognizes text
1090 signifying that on the login form after attempting to log in.
1091
1092 .. code-block:: python
1093
1094 class TestLandingPageBadCredentials:
1095 @pytest.fixture(scope="class")
1096 @classmethod
1097 def faux_user(cls, user):
1098 _user = deepcopy(user)
1099 _user.password = "badpass"
1100 return _user
1101
1102 def test_raises_bad_credentials_exception(self, login_page, faux_user):
1103 with pytest.raises(BadCredentialsException):
1104 login_page.login(faux_user)
1105
1106
1107 .. _`request-context`:
1108
1109 Fixtures can introspect the requesting test context
1110 -------------------------------------------------------------
1111
1112 Fixture functions can accept the :py:class:`request <_pytest.fixtures.FixtureRequest>` object
1113 to introspect the "requesting" test function, class or module context.
1114 Further extending the previous ``smtp_connection`` fixture example, let's
1115 read an optional server URL from the test module which uses our fixture:
1116
1117 .. code-block:: python
1118
1119 # content of conftest.py
1120 import smtplib
1121
1122 import pytest
1123
1124
1125 @pytest.fixture(scope="module")
1126 def smtp_connection(request):
1127 server = getattr(request.module, "smtpserver", "smtp.gmail.com")
1128 smtp_connection = smtplib.SMTP(server, 587, timeout=5)
1129 yield smtp_connection
1130 print(f"finalizing {smtp_connection} ({server})")
1131 smtp_connection.close()
1132
1133 We use the ``request.module`` attribute to optionally obtain an
1134 ``smtpserver`` attribute from the test module. If we just execute
1135 again, nothing much has changed:
1136
1137 .. code-block:: pytest
1138
1139 $ pytest -s -q --tb=no test_module.py
1140 FFfinalizing <smtplib.SMTP object at 0xdeadbeef0002> (smtp.gmail.com)
1141
1142 ========================= short test summary info ==========================
1143 FAILED test_module.py::test_ehlo - assert 0
1144 FAILED test_module.py::test_noop - assert 0
1145 2 failed in 0.12s
1146
1147 Let's quickly create another test module that actually sets the
1148 server URL in its module namespace:
1149
1150 .. code-block:: python
1151
1152 # content of test_anothersmtp.py
1153
1154 smtpserver = "mail.python.org" # will be read by smtp fixture
1155
1156
1157 def test_showhelo(smtp_connection):
1158 assert 0, smtp_connection.helo()
1159
1160 Running it:
1161
1162 .. code-block:: pytest
1163
1164 $ pytest -qq --tb=short test_anothersmtp.py
1165 F [100%]
1166 ================================= FAILURES =================================
1167 ______________________________ test_showhelo _______________________________
1168 test_anothersmtp.py:6: in test_showhelo
1169 assert 0, smtp_connection.helo()
1170 E AssertionError: (250, b'mail.python.org')
1171 E assert 0
1172 ------------------------- Captured stdout teardown -------------------------
1173 finalizing <smtplib.SMTP object at 0xdeadbeef0003> (mail.python.org)
1174 ========================= short test summary info ==========================
1175 FAILED test_anothersmtp.py::test_showhelo - AssertionError: (250, b'mail....
1176
1177 voila! The ``smtp_connection`` fixture function picked up our mail server name
1178 from the module namespace.
1179
1180 .. _`using-markers`:
1181
1182 Using markers to pass data to fixtures
1183 -------------------------------------------------------------
1184
1185 Using the :py:class:`request <_pytest.fixtures.FixtureRequest>` object, a fixture can also access
1186 markers which are applied to a test function. This can be useful to pass data
1187 into a fixture from a test:
1188
1189 .. code-block:: python
1190
1191 import pytest
1192
1193
1194 @pytest.fixture
1195 def fixt(request):
1196 marker = request.node.get_closest_marker("fixt_data")
1197 if marker is None:
1198 # Handle missing marker in some way...
1199 data = None
1200 else:
1201 data = marker.args[0]
1202
1203 # Do something with the data
1204 return data
1205
1206
1207 @pytest.mark.fixt_data(42)
1208 def test_fixt(fixt):
1209 assert fixt == 42
1210
1211 .. _`fixture-factory`:
1212
1213 Factories as fixtures
1214 -------------------------------------------------------------
1215
1216 The "factory as fixture" pattern can help in situations where the result
1217 of a fixture is needed multiple times in a single test. Instead of returning
1218 data directly, the fixture instead returns a function which generates the data.
1219 This function can then be called multiple times in the test.
1220
1221 Factories can have parameters as needed:
1222
1223 .. code-block:: python
1224
1225 @pytest.fixture
1226 def make_customer_record():
1227 def _make_customer_record(name):
1228 return {"name": name, "orders": []}
1229
1230 return _make_customer_record
1231
1232
1233 def test_customer_records(make_customer_record):
1234 customer_1 = make_customer_record("Lisa")
1235 customer_2 = make_customer_record("Mike")
1236 customer_3 = make_customer_record("Meredith")
1237
1238 If the data created by the factory requires managing, the fixture can take care of that:
1239
1240 .. code-block:: python
1241
1242 @pytest.fixture
1243 def make_customer_record():
1244 created_records = []
1245
1246 def _make_customer_record(name):
1247 record = models.Customer(name=name, orders=[])
1248 created_records.append(record)
1249 return record
1250
1251 yield _make_customer_record
1252
1253 for record in created_records:
1254 record.destroy()
1255
1256
1257 def test_customer_records(make_customer_record):
1258 customer_1 = make_customer_record("Lisa")
1259 customer_2 = make_customer_record("Mike")
1260 customer_3 = make_customer_record("Meredith")
1261
1262
1263 .. _`fixture-parametrize`:
1264
1265 Parametrizing fixtures
1266 -----------------------------------------------------------------
1267
1268 Fixture functions can be parametrized in which case they will be called
1269 multiple times, each time executing the set of dependent tests, i.e. the
1270 tests that depend on this fixture. Test functions usually do not need
1271 to be aware of their re-running. Fixture parametrization helps to
1272 write exhaustive functional tests for components which themselves can be
1273 configured in multiple ways.
1274
1275 Extending the previous example, we can flag the fixture to create two
1276 ``smtp_connection`` fixture instances which will cause all tests using the fixture
1277 to run twice. The fixture function gets access to each parameter
1278 through the special :py:class:`request <pytest.FixtureRequest>` object:
1279
1280 .. code-block:: python
1281
1282 # content of conftest.py
1283 import smtplib
1284
1285 import pytest
1286
1287
1288 @pytest.fixture(scope="module", params=["smtp.gmail.com", "mail.python.org"])
1289 def smtp_connection(request):
1290 smtp_connection = smtplib.SMTP(request.param, 587, timeout=5)
1291 yield smtp_connection
1292 print(f"finalizing {smtp_connection}")
1293 smtp_connection.close()
1294
1295 The main change is the declaration of ``params`` with
1296 :py:func:`@pytest.fixture <pytest.fixture>`, a list of values
1297 for each of which the fixture function will execute and can access
1298 a value via ``request.param``. No test function code needs to change.
1299 So let's just do another run:
1300
1301 .. code-block:: pytest
1302
1303 $ pytest -q test_module.py
1304 FFFF [100%]
1305 ================================= FAILURES =================================
1306 ________________________ test_ehlo[smtp.gmail.com] _________________________
1307
1308 smtp_connection = <smtplib.SMTP object at 0xdeadbeef0004>
1309
1310 def test_ehlo(smtp_connection):
1311 response, msg = smtp_connection.ehlo()
1312 assert response == 250
1313 assert b"smtp.gmail.com" in msg
1314 > assert 0 # for demo purposes
1315 ^^^^^^^^
1316 E assert 0
1317
1318 test_module.py:7: AssertionError
1319 ________________________ test_noop[smtp.gmail.com] _________________________
1320
1321 smtp_connection = <smtplib.SMTP object at 0xdeadbeef0004>
1322
1323 def test_noop(smtp_connection):
1324 response, msg = smtp_connection.noop()
1325 assert response == 250
1326 > assert 0 # for demo purposes
1327 ^^^^^^^^
1328 E assert 0
1329
1330 test_module.py:13: AssertionError
1331 ________________________ test_ehlo[mail.python.org] ________________________
1332
1333 smtp_connection = <smtplib.SMTP object at 0xdeadbeef0005>
1334
1335 def test_ehlo(smtp_connection):
1336 response, msg = smtp_connection.ehlo()
1337 assert response == 250
1338 > assert b"smtp.gmail.com" in msg
1339 E AssertionError: assert b'smtp.gmail.com' in b'mail.python.org\nPIPELINING\nSIZE 51200000\nETRN\nSTARTTLS\nAUTH DIGEST-MD5 NTLM CRAM-MD5\nENHANCEDSTATUSCODES\n8BITMIME\nDSN\nSMTPUTF8\nCHUNKING'
1340
1341 test_module.py:6: AssertionError
1342 -------------------------- Captured stdout setup ---------------------------
1343 finalizing <smtplib.SMTP object at 0xdeadbeef0004>
1344 ________________________ test_noop[mail.python.org] ________________________
1345
1346 smtp_connection = <smtplib.SMTP object at 0xdeadbeef0005>
1347
1348 def test_noop(smtp_connection):
1349 response, msg = smtp_connection.noop()
1350 assert response == 250
1351 > assert 0 # for demo purposes
1352 ^^^^^^^^
1353 E assert 0
1354
1355 test_module.py:13: AssertionError
1356 ------------------------- Captured stdout teardown -------------------------
1357 finalizing <smtplib.SMTP object at 0xdeadbeef0005>
1358 ========================= short test summary info ==========================
1359 FAILED test_module.py::test_ehlo[smtp.gmail.com] - assert 0
1360 FAILED test_module.py::test_noop[smtp.gmail.com] - assert 0
1361 FAILED test_module.py::test_ehlo[mail.python.org] - AssertionError: asser...
1362 FAILED test_module.py::test_noop[mail.python.org] - assert 0
1363 4 failed in 0.12s
1364
1365 We see that our two test functions each ran twice, against the different
1366 ``smtp_connection`` instances. Note also, that with the ``mail.python.org``
1367 connection the second test fails in ``test_ehlo`` because a
1368 different server string is expected than what arrived.
1369
1370 pytest will build a string that is the test ID for each fixture value
1371 in a parametrized fixture, e.g. ``test_ehlo[smtp.gmail.com]`` and
1372 ``test_ehlo[mail.python.org]`` in the above examples. These IDs can
1373 be used with :option:`-k` to select specific cases to run, and they will
1374 also identify the specific case when one is failing. Running pytest
1375 with :option:`--collect-only` will show the generated IDs.
1376
1377 Numbers, strings, booleans and ``None`` will have their usual string
1378 representation used in the test ID. For other objects, pytest will
1379 make a string based on the argument name. It is possible to customise
1380 the string used in a test ID for a certain fixture value by using the
1381 ``ids`` keyword argument:
1382
1383 .. code-block:: python
1384
1385 # content of test_ids.py
1386 import pytest
1387
1388
1389 @pytest.fixture(params=[0, 1], ids=["spam", "ham"])
1390 def a(request):
1391 return request.param
1392
1393
1394 def test_a(a):
1395 pass
1396
1397
1398 def idfn(fixture_value):
1399 if fixture_value == 0:
1400 return "eggs"
1401 else:
1402 return None
1403
1404
1405 @pytest.fixture(params=[0, 1], ids=idfn)
1406 def b(request):
1407 return request.param
1408
1409
1410 def test_b(b):
1411 pass
1412
1413 The above shows how ``ids`` can be either a list of strings to use or
1414 a function which will be called with the fixture value and then
1415 has to return a string to use. In the latter case if the function
1416 returns ``None`` then pytest's auto-generated ID will be used.
1417
1418 Running the above tests results in the following test IDs being used:
1419
1420 .. code-block:: pytest
1421
1422 $ pytest --collect-only
1423 =========================== test session starts ============================
1424 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
1425 rootdir: /home/sweet/project
1426 collected 12 items
1427
1428 <Dir fixtures.rst-236>
1429 <Module test_anothersmtp.py>
1430 <Function test_showhelo[smtp.gmail.com]>
1431 <Function test_showhelo[mail.python.org]>
1432 <Module test_emaillib.py>
1433 <Function test_email_received>
1434 <Module test_finalizers.py>
1435 <Function test_bar>
1436 <Module test_ids.py>
1437 <Function test_a[spam]>
1438 <Function test_a[ham]>
1439 <Function test_b[eggs]>
1440 <Function test_b[1]>
1441 <Module test_module.py>
1442 <Function test_ehlo[smtp.gmail.com]>
1443 <Function test_noop[smtp.gmail.com]>
1444 <Function test_ehlo[mail.python.org]>
1445 <Function test_noop[mail.python.org]>
1446
1447 ======================= 12 tests collected in 0.12s ========================
1448
1449 .. _`fixture-parametrize-marks`:
1450
1451 Using marks with parametrized fixtures
1452 --------------------------------------
1453
1454 :func:`pytest.param` can be used to apply marks in values sets of parametrized fixtures in the same way
1455 that they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`.
1456
1457 Example:
1458
1459 .. code-block:: python
1460
1461 # content of test_fixture_marks.py
1462 import pytest
1463
1464
1465 @pytest.fixture(params=[0, 1, pytest.param(2, marks=pytest.mark.skip)])
1466 def data_set(request):
1467 return request.param
1468
1469
1470 def test_data(data_set):
1471 pass
1472
1473 Running this test will *skip* the invocation of ``data_set`` with value ``2``:
1474
1475 .. code-block:: pytest
1476
1477 $ pytest test_fixture_marks.py -v
1478 =========================== test session starts ============================
1479 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
1480 cachedir: .pytest_cache
1481 rootdir: /home/sweet/project
1482 collecting ... collected 3 items
1483
1484 test_fixture_marks.py::test_data[0] PASSED [ 33%]
1485 test_fixture_marks.py::test_data[1] PASSED [ 66%]
1486 test_fixture_marks.py::test_data[2] SKIPPED (unconditional skip) [100%]
1487
1488 ======================= 2 passed, 1 skipped in 0.12s =======================
1489
1490 .. _`interdependent fixtures`:
1491
1492 Modularity: using fixtures from a fixture function
1493 ----------------------------------------------------------
1494
1495 In addition to using fixtures in test functions, fixture functions
1496 can use other fixtures themselves. This contributes to a modular design
1497 of your fixtures and allows reuse of framework-specific fixtures across
1498 many projects. As a simple example, we can extend the previous example
1499 and instantiate an object ``app`` where we stick the already defined
1500 ``smtp_connection`` resource into it:
1501
1502 .. code-block:: python
1503
1504 # content of test_appsetup.py
1505
1506 import pytest
1507
1508
1509 class App:
1510 def __init__(self, smtp_connection):
1511 self.smtp_connection = smtp_connection
1512
1513
1514 @pytest.fixture(scope="module")
1515 def app(smtp_connection):
1516 return App(smtp_connection)
1517
1518
1519 def test_smtp_connection_exists(app):
1520 assert app.smtp_connection
1521
1522 Here we declare an ``app`` fixture which receives the previously defined
1523 ``smtp_connection`` fixture and instantiates an ``App`` object with it. Let's run it:
1524
1525 .. code-block:: pytest
1526
1527 $ pytest -v test_appsetup.py
1528 =========================== test session starts ============================
1529 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
1530 cachedir: .pytest_cache
1531 rootdir: /home/sweet/project
1532 collecting ... collected 2 items
1533
1534 test_appsetup.py::test_smtp_connection_exists[smtp.gmail.com] PASSED [ 50%]
1535 test_appsetup.py::test_smtp_connection_exists[mail.python.org] PASSED [100%]
1536
1537 ============================ 2 passed in 0.12s =============================
1538
1539 Due to the parametrization of ``smtp_connection``, the test will run twice with two
1540 different ``App`` instances and respective smtp servers. There is no
1541 need for the ``app`` fixture to be aware of the ``smtp_connection``
1542 parametrization because pytest will fully analyse the fixture dependency graph.
1543
1544 Note that the ``app`` fixture has a scope of ``module`` and uses a
1545 module-scoped ``smtp_connection`` fixture. The example would still work if
1546 ``smtp_connection`` was cached on a ``session`` scope: it is fine for fixtures to use
1547 "broader" scoped fixtures but not the other way round:
1548 A session-scoped fixture could not use a module-scoped one in a
1549 meaningful way.
1550
1551
1552 .. _`automatic per-resource grouping`:
1553
1554 Automatic grouping of tests by fixture instances
1555 ----------------------------------------------------------
1556
1557 .. regendoc: wipe
1558
1559 pytest minimizes the number of active fixtures during test runs.
1560 If you have a parametrized fixture, then all the tests using it will
1561 first execute with one instance and then finalizers are called
1562 before the next fixture instance is created. Among other things,
1563 this eases testing of applications which create and use global state.
1564
1565 The following example uses two parametrized fixtures, one of which is
1566 scoped on a per-module basis, and all the functions perform ``print`` calls
1567 to show the setup/teardown flow:
1568
1569 .. code-block:: python
1570
1571 # content of test_module.py
1572 import pytest
1573
1574
1575 @pytest.fixture(scope="module", params=["mod1", "mod2"])
1576 def modarg(request):
1577 param = request.param
1578 print(" SETUP modarg", param)
1579 yield param
1580 print(" TEARDOWN modarg", param)
1581
1582
1583 @pytest.fixture(scope="function", params=[1, 2])
1584 def otherarg(request):
1585 param = request.param
1586 print(" SETUP otherarg", param)
1587 yield param
1588 print(" TEARDOWN otherarg", param)
1589
1590
1591 def test_0(otherarg):
1592 print(" RUN test0 with otherarg", otherarg)
1593
1594
1595 def test_1(modarg):
1596 print(" RUN test1 with modarg", modarg)
1597
1598
1599 def test_2(otherarg, modarg):
1600 print(f" RUN test2 with otherarg {otherarg} and modarg {modarg}")
1601
1602
1603 Let's run the tests in verbose mode and with looking at the print-output:
1604
1605 .. code-block:: pytest
1606
1607 $ pytest -v -s test_module.py
1608 =========================== test session starts ============================
1609 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
1610 cachedir: .pytest_cache
1611 rootdir: /home/sweet/project
1612 collecting ... collected 8 items
1613
1614 test_module.py::test_0[1] SETUP otherarg 1
1615 RUN test0 with otherarg 1
1616 PASSED TEARDOWN otherarg 1
1617
1618 test_module.py::test_0[2] SETUP otherarg 2
1619 RUN test0 with otherarg 2
1620 PASSED TEARDOWN otherarg 2
1621
1622 test_module.py::test_1[mod1] SETUP modarg mod1
1623 RUN test1 with modarg mod1
1624 PASSED
1625 test_module.py::test_2[mod1-1] SETUP otherarg 1
1626 RUN test2 with otherarg 1 and modarg mod1
1627 PASSED TEARDOWN otherarg 1
1628
1629 test_module.py::test_2[mod1-2] SETUP otherarg 2
1630 RUN test2 with otherarg 2 and modarg mod1
1631 PASSED TEARDOWN otherarg 2
1632
1633 test_module.py::test_1[mod2] TEARDOWN modarg mod1
1634 SETUP modarg mod2
1635 RUN test1 with modarg mod2
1636 PASSED
1637 test_module.py::test_2[mod2-1] SETUP otherarg 1
1638 RUN test2 with otherarg 1 and modarg mod2
1639 PASSED TEARDOWN otherarg 1
1640
1641 test_module.py::test_2[mod2-2] SETUP otherarg 2
1642 RUN test2 with otherarg 2 and modarg mod2
1643 PASSED TEARDOWN otherarg 2
1644 TEARDOWN modarg mod2
1645
1646
1647 ============================ 8 passed in 0.12s =============================
1648
1649 You can see that the parametrized module-scoped ``modarg`` resource caused an
1650 ordering of test execution that led to the fewest possible "active" resources.
1651 The finalizer for the ``mod1`` parametrized resource was executed before the
1652 ``mod2`` resource was setup.
1653
1654 In particular notice that test_0 is completely independent and finishes first.
1655 Then test_1 is executed with ``mod1``, then test_2 with ``mod1``, then test_1
1656 with ``mod2`` and finally test_2 with ``mod2``.
1657
1658 The ``otherarg`` parametrized resource (having function scope) was set up before
1659 and torn down after every test that used it.
1660
1661
1662 .. _`usefixtures`:
1663
1664 Use fixtures in classes and modules with ``usefixtures``
1665 --------------------------------------------------------
1666
1667 .. regendoc:wipe
1668
1669 Sometimes test functions do not directly need access to a fixture object.
1670 For example, tests may require to operate with an empty directory as the
1671 current working directory but otherwise do not care for the concrete
1672 directory. Here is how you can use the standard :mod:`tempfile`
1673 and pytest fixtures to
1674 achieve it. We separate the creation of the fixture into a :file:`conftest.py`
1675 file:
1676
1677 .. code-block:: python
1678
1679 # content of conftest.py
1680
1681 import os
1682 import tempfile
1683
1684 import pytest
1685
1686
1687 @pytest.fixture
1688 def cleandir():
1689 with tempfile.TemporaryDirectory() as newpath:
1690 old_cwd = os.getcwd()
1691 os.chdir(newpath)
1692 yield
1693 os.chdir(old_cwd)
1694
1695 and declare its use in a test module via a ``usefixtures`` marker:
1696
1697 .. code-block:: python
1698
1699 # content of test_setenv.py
1700 import os
1701
1702 import pytest
1703
1704
1705 @pytest.mark.usefixtures("cleandir")
1706 class TestDirectoryInit:
1707 def test_cwd_starts_empty(self):
1708 assert os.listdir(os.getcwd()) == []
1709 with open("myfile", "w", encoding="utf-8") as f:
1710 f.write("hello")
1711
1712 def test_cwd_again_starts_empty(self):
1713 assert os.listdir(os.getcwd()) == []
1714
1715 Due to the ``usefixtures`` marker, the ``cleandir`` fixture
1716 will be required for the execution of each test method, just as if
1717 you specified a "cleandir" function argument to each of them. Let's run it
1718 to verify our fixture is activated and the tests pass:
1719
1720 .. code-block:: pytest
1721
1722 $ pytest -q
1723 .. [100%]
1724 2 passed in 0.12s
1725
1726 You can specify multiple fixtures like this:
1727
1728 .. code-block:: python
1729
1730 @pytest.mark.usefixtures("cleandir", "anotherfixture")
1731 def test(): ...
1732
1733 and you may specify fixture usage at the test module level using :globalvar:`pytestmark`:
1734
1735 .. code-block:: python
1736
1737 pytestmark = pytest.mark.usefixtures("cleandir")
1738
1739
1740 It is also possible to put fixtures required by all tests in your project
1741 into a configuration file:
1742
1743 .. code-block:: toml
1744
1745 # content of pytest.toml
1746 [pytest]
1747 usefixtures = ["cleandir"]
1748
1749 .. warning::
1750
1751 ``@pytest.mark.usefixtures`` cannot be used on **fixture functions**. For example,
1752 this is an error:
1753
1754 .. code-block:: python
1755
1756 @pytest.mark.usefixtures("my_other_fixture")
1757 @pytest.fixture
1758 def my_fixture_that_sadly_wont_use_my_other_fixture(): ...
1759
1760 .. _`override fixtures`:
1761
1762 Overriding fixtures on various levels
1763 -------------------------------------
1764
1765 In a relatively large test suite, you may want to *override* a fixture, to augment
1766 or change its behavior inside of certain test modules or directories.
1767
1768 Override a fixture on a directory (conftest) level
1769 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1770
1771 Given the tests file structure is:
1772
1773 ::
1774
1775 tests/
1776 conftest.py
1777 # content of tests/conftest.py
1778 import pytest
1779
1780 @pytest.fixture
1781 def username():
1782 return 'username'
1783
1784 test_something.py
1785 # content of tests/test_something.py
1786 def test_username(username):
1787 assert username == 'username'
1788
1789 subdir/
1790 conftest.py
1791 # content of tests/subdir/conftest.py
1792 import pytest
1793
1794 @pytest.fixture
1795 def username(username):
1796 return 'overridden-' + username
1797
1798 test_something_else.py
1799 # content of tests/subdir/test_something_else.py
1800 def test_username(username):
1801 assert username == 'overridden-username'
1802
1803 As you can see, a fixture with the same name can be overridden for a certain test directory level.
1804 Note that the ``base`` or ``super`` fixture can be accessed from the ``overriding``
1805 fixture easily - used in the example above.
1806
1807 Override a fixture on a test module level
1808 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1809
1810 Given the tests file structure is:
1811
1812 ::
1813
1814 tests/
1815 conftest.py
1816 # content of tests/conftest.py
1817 import pytest
1818
1819 @pytest.fixture
1820 def username():
1821 return 'username'
1822
1823 test_something.py
1824 # content of tests/test_something.py
1825 import pytest
1826
1827 @pytest.fixture
1828 def username(username):
1829 return 'overridden-' + username
1830
1831 def test_username(username):
1832 assert username == 'overridden-username'
1833
1834 test_something_else.py
1835 # content of tests/test_something_else.py
1836 import pytest
1837
1838 @pytest.fixture
1839 def username(username):
1840 return 'overridden-else-' + username
1841
1842 def test_username(username):
1843 assert username == 'overridden-else-username'
1844
1845 In the example above, a fixture with the same name can be overridden for a certain test module.
1846
1847
1848 Override a fixture with direct test parametrization
1849 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1850
1851 Given the tests file structure is:
1852
1853 ::
1854
1855 tests/
1856 conftest.py
1857 # content of tests/conftest.py
1858 import pytest
1859
1860 @pytest.fixture
1861 def username():
1862 return 'username'
1863
1864 @pytest.fixture
1865 def other_username(username):
1866 return 'other-' + username
1867
1868 test_something.py
1869 # content of tests/test_something.py
1870 import pytest
1871
1872 @pytest.mark.parametrize('username', ['directly-overridden-username'])
1873 def test_username(username):
1874 assert username == 'directly-overridden-username'
1875
1876 @pytest.mark.parametrize('username', ['directly-overridden-username-other'])
1877 def test_username_other(other_username):
1878 assert other_username == 'other-directly-overridden-username-other'
1879
1880 In the example above, a fixture value is overridden by the test parameter value. Note that the value of the fixture
1881 can be overridden this way even if the test doesn't use it directly (doesn't mention it in the function prototype).
1882
1883
1884 Override a parametrized fixture with non-parametrized one and vice versa
1885 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1886
1887 Given the tests file structure is:
1888
1889 ::
1890
1891 tests/
1892 conftest.py
1893 # content of tests/conftest.py
1894 import pytest
1895
1896 @pytest.fixture(params=['one', 'two', 'three'])
1897 def parametrized_username(request):
1898 return request.param
1899
1900 @pytest.fixture
1901 def non_parametrized_username(request):
1902 return 'username'
1903
1904 test_something.py
1905 # content of tests/test_something.py
1906 import pytest
1907
1908 @pytest.fixture
1909 def parametrized_username():
1910 return 'overridden-username'
1911
1912 @pytest.fixture(params=['one', 'two', 'three'])
1913 def non_parametrized_username(request):
1914 return request.param
1915
1916 def test_username(parametrized_username):
1917 assert parametrized_username == 'overridden-username'
1918
1919 def test_parametrized_username(non_parametrized_username):
1920 assert non_parametrized_username in ['one', 'two', 'three']
1921
1922 test_something_else.py
1923 # content of tests/test_something_else.py
1924 def test_username(parametrized_username):
1925 assert parametrized_username in ['one', 'two', 'three']
1926
1927 def test_username(non_parametrized_username):
1928 assert non_parametrized_username == 'username'
1929
1930 In the example above, a parametrized fixture is overridden with a non-parametrized version, and
1931 a non-parametrized fixture is overridden with a parametrized version for certain test module.
1932 The same applies for the test directory level obviously.
1933
1934
1935 Using fixtures from other projects
1936 ----------------------------------
1937
1938 Usually projects that provide pytest support will use :ref:`entry points <pip-installable plugins>`,
1939 so just installing those projects into an environment will make those fixtures available for use.
1940
1941 In case you want to use fixtures from a project that does not use entry points, you can
1942 define :globalvar:`pytest_plugins` in your top ``conftest.py`` file to register that module
1943 as a plugin.
1944
1945 Suppose you have some fixtures in ``mylibrary.fixtures`` and you want to reuse them into your
1946 ``app/tests`` directory.
1947
1948 All you need to do is to define :globalvar:`pytest_plugins` in ``app/tests/conftest.py``
1949 pointing to that module.
1950
1951 .. code-block:: python
1952
1953 pytest_plugins = "mylibrary.fixtures"
1954
1955 This effectively registers ``mylibrary.fixtures`` as a plugin, making all its fixtures and
1956 hooks available to tests in ``app/tests``.
1957
1958 .. note::
1959
1960 Sometimes users will *import* fixtures from other projects for use, however this is not
1961 recommended: importing fixtures into a module will register them in pytest
1962 as *defined* in that module.
1963
1964 This has minor consequences, such as appearing multiple times in ``pytest --help``,
1965 but it is not **recommended** because this behavior might change/stop working
1966 in future versions.