Debian Codegraph @

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