/usr/share/doc/python-pytest/html/fixture.html is in python-pytest-doc 3.3.2-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pytest fixtures: explicit, modular, scalable — pytest documentation</title>
<link rel="stylesheet" href="_static/flasky.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '3.3',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="shortcut icon" href="_static/pytest1favi.ico"/>
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Monkeypatching/mocking modules and environments" href="monkeypatch.html" />
<link rel="prev" title="Pytest API and builtin fixtures" href="builtin.html" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">
</head>
<body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="monkeypatch.html" title="Monkeypatching/mocking modules and environments"
accesskey="N">next</a></li>
<li class="right" >
<a href="builtin.html" title="Pytest API and builtin fixtures"
accesskey="P">previous</a> |</li>
<li class="nav-item nav-item-0"><a href="contents.html">pytest-3.3</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="pytest-fixtures-explicit-modular-scalable">
<span id="fixture-functions"></span><span id="fixtures"></span><span id="fixture"></span><h1>pytest fixtures: explicit, modular, scalable<a class="headerlink" href="#pytest-fixtures-explicit-modular-scalable" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0/2.3/2.4.</span></p>
</div>
<p>The <a class="reference external" href="http://en.wikipedia.org/wiki/Test_fixture#Software">purpose of test fixtures</a> is to provide a fixed baseline
upon which tests can reliably and repeatedly execute. pytest fixtures
offer dramatic improvements over the classic xUnit style of setup/teardown
functions:</p>
<ul class="simple">
<li>fixtures have explicit names and are activated by declaring their use
from test functions, modules, classes or whole projects.</li>
<li>fixtures are implemented in a modular manner, as each fixture name
triggers a <em>fixture function</em> which can itself use other fixtures.</li>
<li>fixture management scales from simple unit to complex
functional testing, allowing to parametrize fixtures and tests according
to configuration and component options, or to re-use fixtures
across function, class, module or whole test session scopes.</li>
</ul>
<p>In addition, pytest continues to support <a class="reference internal" href="xunit_setup.html#xunitsetup"><span class="std std-ref">classic xunit-style setup</span></a>. You can mix
both styles, moving incrementally from classic to new style, as you
prefer. You can also start out from existing <a class="reference internal" href="unittest.html#unittest-testcase"><span class="std std-ref">unittest.TestCase
style</span></a> or <a class="reference internal" href="nose.html#nosestyle"><span class="std std-ref">nose based</span></a> projects.</p>
<div class="section" id="fixtures-as-function-arguments">
<span id="id1"></span><span id="pytest-fixture"></span><span id="fixture-function"></span><span id="funcarg-mechanism"></span><span id="funcargs"></span><h2>Fixtures as Function arguments<a class="headerlink" href="#fixtures-as-function-arguments" title="Permalink to this headline">¶</a></h2>
<p>Test functions can receive fixture objects by naming them as an input
argument. For each argument name, a fixture function with that name provides
the fixture object. Fixture functions are registered by marking them with
<code class="xref py py-func docutils literal"><span class="pre">@pytest.fixture</span></code>. Let's look at a simple
self-contained test module containing a fixture and a test function
using it:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of ./test_smtpsimple.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">smtp</span><span class="p">():</span>
<span class="kn">import</span> <span class="nn">smtplib</span>
<span class="k">return</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s2">"smtp.gmail.com"</span><span class="p">,</span> <span class="mi">587</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_ehlo</span><span class="p">(</span><span class="n">smtp</span><span class="p">):</span>
<span class="n">response</span><span class="p">,</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">smtp</span><span class="o">.</span><span class="n">ehlo</span><span class="p">()</span>
<span class="k">assert</span> <span class="n">response</span> <span class="o">==</span> <span class="mi">250</span>
<span class="k">assert</span> <span class="mi">0</span> <span class="c1"># for demo purposes</span>
</pre></div>
</div>
<p>Here, the <code class="docutils literal"><span class="pre">test_ehlo</span></code> needs the <code class="docutils literal"><span class="pre">smtp</span></code> fixture value. pytest
will discover and call the <code class="xref py py-func docutils literal"><span class="pre">@pytest.fixture</span></code>
marked <code class="docutils literal"><span class="pre">smtp</span></code> fixture function. Running the test looks like this:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest test_smtpsimple.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR, inifile:
collected 1 item
test_smtpsimple.py F [100%]
================================= FAILURES =================================
________________________________ test_ehlo _________________________________
smtp = <smtplib.SMTP object at 0xdeadbeef>
def test_ehlo(smtp):
response, msg = smtp.ehlo()
assert response == 250
> assert 0 # for demo purposes
E assert 0
test_smtpsimple.py:11: AssertionError
========================= 1 failed in 0.12 seconds =========================
</pre></div>
</div>
<p>In the failure traceback we see that the test function was called with a
<code class="docutils literal"><span class="pre">smtp</span></code> argument, the <code class="docutils literal"><span class="pre">smtplib.SMTP()</span></code> instance created by the fixture
function. The test function fails on our deliberate <code class="docutils literal"><span class="pre">assert</span> <span class="pre">0</span></code>. Here is
the exact protocol used by <code class="docutils literal"><span class="pre">pytest</span></code> to call the test function this way:</p>
<ol class="arabic simple">
<li>pytest <a class="reference internal" href="goodpractices.html#test-discovery"><span class="std std-ref">finds</span></a> the <code class="docutils literal"><span class="pre">test_ehlo</span></code> because
of the <code class="docutils literal"><span class="pre">test_</span></code> prefix. The test function needs a function argument
named <code class="docutils literal"><span class="pre">smtp</span></code>. A matching fixture function is discovered by
looking for a fixture-marked function named <code class="docutils literal"><span class="pre">smtp</span></code>.</li>
<li><code class="docutils literal"><span class="pre">smtp()</span></code> is called to create an instance.</li>
<li><code class="docutils literal"><span class="pre">test_ehlo(<SMTP</span> <span class="pre">instance>)</span></code> is called and fails in the last
line of the test function.</li>
</ol>
<p>Note that if you misspell a function argument or want
to use one that isn't available, you'll see an error
with a list of available function arguments.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>You can always issue:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">pytest</span> <span class="o">--</span><span class="n">fixtures</span> <span class="n">test_simplefactory</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p class="last">to see available fixtures.</p>
</div>
</div>
<div class="section" id="fixtures-a-prime-example-of-dependency-injection">
<h2>Fixtures: a prime example of dependency injection<a class="headerlink" href="#fixtures-a-prime-example-of-dependency-injection" title="Permalink to this headline">¶</a></h2>
<p>Fixtures allow test functions to easily receive and work
against specific pre-initialized application objects without having
to care about import/setup/cleanup details.
It's a prime example of <a class="reference external" href="http://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a> where fixture
functions take the role of the <em>injector</em> and test functions are the
<em>consumers</em> of fixture objects.</p>
</div>
<div class="section" id="conftest-py-sharing-fixture-functions">
<span id="conftest"></span><span id="conftest-py"></span><h2><code class="docutils literal"><span class="pre">conftest.py</span></code>: sharing fixture functions<a class="headerlink" href="#conftest-py-sharing-fixture-functions" title="Permalink to this headline">¶</a></h2>
<p>If during implementing your tests you realize that you
want to use a fixture function from multiple test files you can move it
to a <code class="docutils literal"><span class="pre">conftest.py</span></code> file.
You don't need to import the fixture you want to use in a test, it
automatically gets discovered by pytest. The discovery of
fixture functions starts at test classes, then test modules, then
<code class="docutils literal"><span class="pre">conftest.py</span></code> files and finally builtin and third party plugins.</p>
<p>You can also use the <code class="docutils literal"><span class="pre">conftest.py</span></code> file to implement
<a class="reference internal" href="writing_plugins.html#conftest-py-plugins"><span class="std std-ref">local per-directory plugins</span></a>.</p>
</div>
<div class="section" id="sharing-test-data">
<h2>Sharing test data<a class="headerlink" href="#sharing-test-data" title="Permalink to this headline">¶</a></h2>
<p>If you want to make test data from files available to your tests, a good way
to do this is by loading these data in a fixture for use by your tests.
This makes use of the automatic caching mechanisms of pytest.</p>
<p>Another good approach is by adding the data files in the <code class="docutils literal"><span class="pre">tests</span></code> folder.
There are also community plugins available to help managing this aspect of
testing, e.g. <a class="reference external" href="https://github.com/gabrielcnr/pytest-datadir">pytest-datadir</a>
and <a class="reference external" href="https://pypi.python.org/pypi/pytest-datafiles">pytest-datafiles</a>.</p>
</div>
<div class="section" id="scope-sharing-a-fixture-instance-across-tests-in-a-class-module-or-session">
<span id="smtpshared"></span><h2>Scope: sharing a fixture instance across tests in a class, module or session<a class="headerlink" href="#scope-sharing-a-fixture-instance-across-tests-in-a-class-module-or-session" title="Permalink to this headline">¶</a></h2>
<p>Fixtures requiring network access depend on connectivity and are
usually time-expensive to create. Extending the previous example, we
can add a <code class="docutils literal"><span class="pre">scope='module'</span></code> parameter to the
<code class="xref py py-func docutils literal"><span class="pre">@pytest.fixture</span></code> invocation
to cause the decorated <code class="docutils literal"><span class="pre">smtp</span></code> fixture function to only be invoked once
per test <em>module</em> (the default is to invoke once per test <em>function</em>).
Multiple test functions in a test module will thus
each receive the same <code class="docutils literal"><span class="pre">smtp</span></code> fixture instance, thus saving time.</p>
<p>The next example puts the fixture function into a separate <code class="docutils literal"><span class="pre">conftest.py</span></code> file
so that tests from multiple test modules in the directory can
access the fixture function:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of conftest.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="kn">import</span> <span class="nn">smtplib</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"module"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">smtp</span><span class="p">():</span>
<span class="k">return</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s2">"smtp.gmail.com"</span><span class="p">,</span> <span class="mi">587</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
<p>The name of the fixture again is <code class="docutils literal"><span class="pre">smtp</span></code> and you can access its result by
listing the name <code class="docutils literal"><span class="pre">smtp</span></code> as an input parameter in any test or fixture
function (in or below the directory where <code class="docutils literal"><span class="pre">conftest.py</span></code> is located):</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of test_module.py</span>
<span class="k">def</span> <span class="nf">test_ehlo</span><span class="p">(</span><span class="n">smtp</span><span class="p">):</span>
<span class="n">response</span><span class="p">,</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">smtp</span><span class="o">.</span><span class="n">ehlo</span><span class="p">()</span>
<span class="k">assert</span> <span class="n">response</span> <span class="o">==</span> <span class="mi">250</span>
<span class="k">assert</span> <span class="sa">b</span><span class="s2">"smtp.gmail.com"</span> <span class="ow">in</span> <span class="n">msg</span>
<span class="k">assert</span> <span class="mi">0</span> <span class="c1"># for demo purposes</span>
<span class="k">def</span> <span class="nf">test_noop</span><span class="p">(</span><span class="n">smtp</span><span class="p">):</span>
<span class="n">response</span><span class="p">,</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">smtp</span><span class="o">.</span><span class="n">noop</span><span class="p">()</span>
<span class="k">assert</span> <span class="n">response</span> <span class="o">==</span> <span class="mi">250</span>
<span class="k">assert</span> <span class="mi">0</span> <span class="c1"># for demo purposes</span>
</pre></div>
</div>
<p>We deliberately insert failing <code class="docutils literal"><span class="pre">assert</span> <span class="pre">0</span></code> statements in order to
inspect what is going on and can now run the tests:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR, inifile:
collected 2 items
test_module.py FF [100%]
================================= FAILURES =================================
________________________________ test_ehlo _________________________________
smtp = <smtplib.SMTP object at 0xdeadbeef>
def test_ehlo(smtp):
response, msg = smtp.ehlo()
assert response == 250
assert b"smtp.gmail.com" in msg
> assert 0 # for demo purposes
E assert 0
test_module.py:6: AssertionError
________________________________ test_noop _________________________________
smtp = <smtplib.SMTP object at 0xdeadbeef>
def test_noop(smtp):
response, msg = smtp.noop()
assert response == 250
> assert 0 # for demo purposes
E assert 0
test_module.py:11: AssertionError
========================= 2 failed in 0.12 seconds =========================
</pre></div>
</div>
<p>You see the two <code class="docutils literal"><span class="pre">assert</span> <span class="pre">0</span></code> failing and more importantly you can also see
that the same (module-scoped) <code class="docutils literal"><span class="pre">smtp</span></code> object was passed into the two
test functions because pytest shows the incoming argument values in the
traceback. As a result, the two test functions using <code class="docutils literal"><span class="pre">smtp</span></code> run as
quick as a single one because they reuse the same instance.</p>
<p>If you decide that you rather want to have a session-scoped <code class="docutils literal"><span class="pre">smtp</span></code>
instance, you can simply declare it:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="nd">@pytest.fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"session"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">smtp</span><span class="p">(</span><span class="o">...</span><span class="p">):</span>
<span class="c1"># the returned fixture value will be shared for</span>
<span class="c1"># all tests needing it</span>
</pre></div>
</div>
<p>Finally, the <code class="docutils literal"><span class="pre">class</span></code> scope will invoke the fixture once per test <em>class</em>.</p>
</div>
<div class="section" id="fixture-finalization-executing-teardown-code">
<span id="finalization"></span><h2>Fixture finalization / executing teardown code<a class="headerlink" href="#fixture-finalization-executing-teardown-code" title="Permalink to this headline">¶</a></h2>
<p>pytest supports execution of fixture specific finalization code
when the fixture goes out of scope. By using a <code class="docutils literal"><span class="pre">yield</span></code> statement instead of <code class="docutils literal"><span class="pre">return</span></code>, all
the code after the <em>yield</em> statement serves as the teardown code:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="c1"># content of conftest.py</span>
<span class="kn">import</span> <span class="nn">smtplib</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest.fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"module"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">smtp</span><span class="p">():</span>
<span class="n">smtp</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s2">"smtp.gmail.com"</span><span class="p">,</span> <span class="mi">587</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="k">yield</span> <span class="n">smtp</span> <span class="c1"># provide the fixture value</span>
<span class="k">print</span><span class="p">(</span><span class="s2">"teardown smtp"</span><span class="p">)</span>
<span class="n">smtp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">print</span></code> and <code class="docutils literal"><span class="pre">smtp.close()</span></code> statements will execute when the last test in
the module has finished execution, regardless of the exception status of the
tests.</p>
<p>Let's execute it:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest -s -q --tb=no
FF [100%]teardown smtp
2 failed in 0.12 seconds
</pre></div>
</div>
<p>We see that the <code class="docutils literal"><span class="pre">smtp</span></code> instance is finalized after the two
tests finished execution. Note that if we decorated our fixture
function with <code class="docutils literal"><span class="pre">scope='function'</span></code> then fixture setup and cleanup would
occur around each single test. In either case the test
module itself does not need to change or know about these details
of fixture setup.</p>
<p>Note that we can also seamlessly use the <code class="docutils literal"><span class="pre">yield</span></code> syntax with <code class="docutils literal"><span class="pre">with</span></code> statements:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="c1"># content of test_yield2.py</span>
<span class="kn">import</span> <span class="nn">smtplib</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest.fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"module"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">smtp</span><span class="p">():</span>
<span class="k">with</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s2">"smtp.gmail.com"</span><span class="p">,</span> <span class="mi">587</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span> <span class="k">as</span> <span class="n">smtp</span><span class="p">:</span>
<span class="k">yield</span> <span class="n">smtp</span> <span class="c1"># provide the fixture value</span>
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">smtp</span></code> connection will be closed after the test finished execution
because the <code class="docutils literal"><span class="pre">smtp</span></code> object automatically closes when
the <code class="docutils literal"><span class="pre">with</span></code> statement ends.</p>
<p>Note that if an exception happens during the <em>setup</em> code (before the <code class="docutils literal"><span class="pre">yield</span></code> keyword), the
<em>teardown</em> code (after the <code class="docutils literal"><span class="pre">yield</span></code>) will not be called.</p>
<p>An alternative option for executing <em>teardown</em> code is to
make use of the <code class="docutils literal"><span class="pre">addfinalizer</span></code> method of the <a class="reference internal" href="#request-context">request-context</a> object to register
finalization functions.</p>
<p>Here's the <code class="docutils literal"><span class="pre">smtp</span></code> fixture changed to use <code class="docutils literal"><span class="pre">addfinalizer</span></code> for cleanup:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="c1"># content of conftest.py</span>
<span class="kn">import</span> <span class="nn">smtplib</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest.fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"module"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">smtp</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="n">smtp</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s2">"smtp.gmail.com"</span><span class="p">,</span> <span class="mi">587</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">fin</span><span class="p">():</span>
<span class="k">print</span> <span class="p">(</span><span class="s2">"teardown smtp"</span><span class="p">)</span>
<span class="n">smtp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">request</span><span class="o">.</span><span class="n">addfinalizer</span><span class="p">(</span><span class="n">fin</span><span class="p">)</span>
<span class="k">return</span> <span class="n">smtp</span> <span class="c1"># provide the fixture value</span>
</pre></div>
</div>
<p>Both <code class="docutils literal"><span class="pre">yield</span></code> and <code class="docutils literal"><span class="pre">addfinalizer</span></code> methods work similarly by calling their code after the test
ends, but <code class="docutils literal"><span class="pre">addfinalizer</span></code> has two key differences over <code class="docutils literal"><span class="pre">yield</span></code>:</p>
<ol class="arabic">
<li><p class="first">It is possible to register multiple finalizer functions.</p>
</li>
<li><p class="first">Finalizers will always be called regardless if the fixture <em>setup</em> code raises an exception.
This is handy to properly close all resources created by a fixture even if one of them
fails to be created/acquired:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">equipments</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="n">r</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">port</span> <span class="ow">in</span> <span class="p">(</span><span class="s1">'C1'</span><span class="p">,</span> <span class="s1">'C3'</span><span class="p">,</span> <span class="s1">'C28'</span><span class="p">):</span>
<span class="n">equip</span> <span class="o">=</span> <span class="n">connect</span><span class="p">(</span><span class="n">port</span><span class="p">)</span>
<span class="n">request</span><span class="o">.</span><span class="n">addfinalizer</span><span class="p">(</span><span class="n">equip</span><span class="o">.</span><span class="n">disconnect</span><span class="p">)</span>
<span class="n">r</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">equip</span><span class="p">)</span>
<span class="k">return</span> <span class="n">r</span>
</pre></div>
</div>
<p>In the example above, if <code class="docutils literal"><span class="pre">"C28"</span></code> fails with an exception, <code class="docutils literal"><span class="pre">"C1"</span></code> and <code class="docutils literal"><span class="pre">"C3"</span></code> will still
be properly closed. Of course, if an exception happens before the finalize function is
registered then it will not be executed.</p>
</li>
</ol>
</div>
<div class="section" id="fixtures-can-introspect-the-requesting-test-context">
<span id="request-context"></span><h2>Fixtures can introspect the requesting test context<a class="headerlink" href="#fixtures-can-introspect-the-requesting-test-context" title="Permalink to this headline">¶</a></h2>
<p>Fixture function can accept the <code class="xref py py-class docutils literal"><span class="pre">request</span></code> object
to introspect the "requesting" test function, class or module context.
Further extending the previous <code class="docutils literal"><span class="pre">smtp</span></code> fixture example, let's
read an optional server URL from the test module which uses our fixture:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of conftest.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="kn">import</span> <span class="nn">smtplib</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"module"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">smtp</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="n">server</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">request</span><span class="o">.</span><span class="n">module</span><span class="p">,</span> <span class="s2">"smtpserver"</span><span class="p">,</span> <span class="s2">"smtp.gmail.com"</span><span class="p">)</span>
<span class="n">smtp</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="n">server</span><span class="p">,</span> <span class="mi">587</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="k">yield</span> <span class="n">smtp</span>
<span class="nb">print</span> <span class="p">(</span><span class="s2">"finalizing </span><span class="si">%s</span><span class="s2"> (</span><span class="si">%s</span><span class="s2">)"</span> <span class="o">%</span> <span class="p">(</span><span class="n">smtp</span><span class="p">,</span> <span class="n">server</span><span class="p">))</span>
<span class="n">smtp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>We use the <code class="docutils literal"><span class="pre">request.module</span></code> attribute to optionally obtain an
<code class="docutils literal"><span class="pre">smtpserver</span></code> attribute from the test module. If we just execute
again, nothing much has changed:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest -s -q --tb=no
FF [100%]finalizing <smtplib.SMTP object at 0xdeadbeef> (smtp.gmail.com)
2 failed in 0.12 seconds
</pre></div>
</div>
<p>Let's quickly create another test module that actually sets the
server URL in its module namespace:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of test_anothersmtp.py</span>
<span class="n">smtpserver</span> <span class="o">=</span> <span class="s2">"mail.python.org"</span> <span class="c1"># will be read by smtp fixture</span>
<span class="k">def</span> <span class="nf">test_showhelo</span><span class="p">(</span><span class="n">smtp</span><span class="p">):</span>
<span class="k">assert</span> <span class="mi">0</span><span class="p">,</span> <span class="n">smtp</span><span class="o">.</span><span class="n">helo</span><span class="p">()</span>
</pre></div>
</div>
<p>Running it:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest -qq --tb=short test_anothersmtp.py
F [100%]
================================= FAILURES =================================
______________________________ test_showhelo _______________________________
test_anothersmtp.py:5: in test_showhelo
assert 0, smtp.helo()
E AssertionError: (250, b'mail.python.org')
E assert 0
------------------------- Captured stdout teardown -------------------------
finalizing <smtplib.SMTP object at 0xdeadbeef> (mail.python.org)
</pre></div>
</div>
<p>voila! The <code class="docutils literal"><span class="pre">smtp</span></code> fixture function picked up our mail server name
from the module namespace.</p>
</div>
<div class="section" id="parametrizing-fixtures">
<span id="fixture-parametrize"></span><h2>Parametrizing fixtures<a class="headerlink" href="#parametrizing-fixtures" title="Permalink to this headline">¶</a></h2>
<p>Fixture functions can be parametrized in which case they will be called
multiple times, each time executing the set of dependent tests, i. e. the
tests that depend on this fixture. Test functions do usually not need
to be aware of their re-running. Fixture parametrization helps to
write exhaustive functional tests for components which themselves can be
configured in multiple ways.</p>
<p>Extending the previous example, we can flag the fixture to create two
<code class="docutils literal"><span class="pre">smtp</span></code> fixture instances which will cause all tests using the fixture
to run twice. The fixture function gets access to each parameter
through the special <code class="xref py py-class docutils literal"><span class="pre">request</span></code> object:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of conftest.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="kn">import</span> <span class="nn">smtplib</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"module"</span><span class="p">,</span>
<span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="s2">"smtp.gmail.com"</span><span class="p">,</span> <span class="s2">"mail.python.org"</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">smtp</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="n">smtp</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="n">request</span><span class="o">.</span><span class="n">param</span><span class="p">,</span> <span class="mi">587</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="k">yield</span> <span class="n">smtp</span>
<span class="nb">print</span> <span class="p">(</span><span class="s2">"finalizing </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">smtp</span><span class="p">)</span>
<span class="n">smtp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The main change is the declaration of <code class="docutils literal"><span class="pre">params</span></code> with
<code class="xref py py-func docutils literal"><span class="pre">@pytest.fixture</span></code>, a list of values
for each of which the fixture function will execute and can access
a value via <code class="docutils literal"><span class="pre">request.param</span></code>. No test function code needs to change.
So let's just do another run:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest -q test_module.py
FFFF [100%]
================================= FAILURES =================================
________________________ test_ehlo[smtp.gmail.com] _________________________
smtp = <smtplib.SMTP object at 0xdeadbeef>
def test_ehlo(smtp):
response, msg = smtp.ehlo()
assert response == 250
assert b"smtp.gmail.com" in msg
> assert 0 # for demo purposes
E assert 0
test_module.py:6: AssertionError
________________________ test_noop[smtp.gmail.com] _________________________
smtp = <smtplib.SMTP object at 0xdeadbeef>
def test_noop(smtp):
response, msg = smtp.noop()
assert response == 250
> assert 0 # for demo purposes
E assert 0
test_module.py:11: AssertionError
________________________ test_ehlo[mail.python.org] ________________________
smtp = <smtplib.SMTP object at 0xdeadbeef>
def test_ehlo(smtp):
response, msg = smtp.ehlo()
assert response == 250
> assert b"smtp.gmail.com" in msg
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'
test_module.py:5: AssertionError
-------------------------- Captured stdout setup ---------------------------
finalizing <smtplib.SMTP object at 0xdeadbeef>
________________________ test_noop[mail.python.org] ________________________
smtp = <smtplib.SMTP object at 0xdeadbeef>
def test_noop(smtp):
response, msg = smtp.noop()
assert response == 250
> assert 0 # for demo purposes
E assert 0
test_module.py:11: AssertionError
------------------------- Captured stdout teardown -------------------------
finalizing <smtplib.SMTP object at 0xdeadbeef>
4 failed in 0.12 seconds
</pre></div>
</div>
<p>We see that our two test functions each ran twice, against the different
<code class="docutils literal"><span class="pre">smtp</span></code> instances. Note also, that with the <code class="docutils literal"><span class="pre">mail.python.org</span></code>
connection the second test fails in <code class="docutils literal"><span class="pre">test_ehlo</span></code> because a
different server string is expected than what arrived.</p>
<p>pytest will build a string that is the test ID for each fixture value
in a parametrized fixture, e.g. <code class="docutils literal"><span class="pre">test_ehlo[smtp.gmail.com]</span></code> and
<code class="docutils literal"><span class="pre">test_ehlo[mail.python.org]</span></code> in the above examples. These IDs can
be used with <code class="docutils literal"><span class="pre">-k</span></code> to select specific cases to run, and they will
also identify the specific case when one is failing. Running pytest
with <code class="docutils literal"><span class="pre">--collect-only</span></code> will show the generated IDs.</p>
<p>Numbers, strings, booleans and None will have their usual string
representation used in the test ID. For other objects, pytest will
make a string based on the argument name. It is possible to customise
the string used in a test ID for a certain fixture value by using the
<code class="docutils literal"><span class="pre">ids</span></code> keyword argument:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of test_ids.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">],</span> <span class="n">ids</span><span class="o">=</span><span class="p">[</span><span class="s2">"spam"</span><span class="p">,</span> <span class="s2">"ham"</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">a</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">request</span><span class="o">.</span><span class="n">param</span>
<span class="k">def</span> <span class="nf">test_a</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
<span class="k">pass</span>
<span class="k">def</span> <span class="nf">idfn</span><span class="p">(</span><span class="n">fixture_value</span><span class="p">):</span>
<span class="k">if</span> <span class="n">fixture_value</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="s2">"eggs"</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">None</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">],</span> <span class="n">ids</span><span class="o">=</span><span class="n">idfn</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">b</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">request</span><span class="o">.</span><span class="n">param</span>
<span class="k">def</span> <span class="nf">test_b</span><span class="p">(</span><span class="n">b</span><span class="p">):</span>
<span class="k">pass</span>
</pre></div>
</div>
<p>The above shows how <code class="docutils literal"><span class="pre">ids</span></code> can be either a list of strings to use or
a function which will be called with the fixture value and then
has to return a string to use. In the latter case if the function
return <code class="docutils literal"><span class="pre">None</span></code> then pytest's auto-generated ID will be used.</p>
<p>Running the above tests results in the following test IDs being used:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR, inifile:
collected 10 items
<Module 'test_anothersmtp.py'>
<Function 'test_showhelo[smtp.gmail.com]'>
<Function 'test_showhelo[mail.python.org]'>
<Module 'test_ids.py'>
<Function 'test_a[spam]'>
<Function 'test_a[ham]'>
<Function 'test_b[eggs]'>
<Function 'test_b[1]'>
<Module 'test_module.py'>
<Function 'test_ehlo[smtp.gmail.com]'>
<Function 'test_noop[smtp.gmail.com]'>
<Function 'test_ehlo[mail.python.org]'>
<Function 'test_noop[mail.python.org]'>
======================= no tests ran in 0.12 seconds =======================
</pre></div>
</div>
</div>
<div class="section" id="modularity-using-fixtures-from-a-fixture-function">
<span id="interdependent-fixtures"></span><h2>Modularity: using fixtures from a fixture function<a class="headerlink" href="#modularity-using-fixtures-from-a-fixture-function" title="Permalink to this headline">¶</a></h2>
<p>You can not only use fixtures in test functions but fixture functions
can use other fixtures themselves. This contributes to a modular design
of your fixtures and allows re-use of framework-specific fixtures across
many projects. As a simple example, we can extend the previous example
and instantiate an object <code class="docutils literal"><span class="pre">app</span></code> where we stick the already defined
<code class="docutils literal"><span class="pre">smtp</span></code> resource into it:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of test_appsetup.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="k">class</span> <span class="nc">App</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">smtp</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">smtp</span> <span class="o">=</span> <span class="n">smtp</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"module"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">app</span><span class="p">(</span><span class="n">smtp</span><span class="p">):</span>
<span class="k">return</span> <span class="n">App</span><span class="p">(</span><span class="n">smtp</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_smtp_exists</span><span class="p">(</span><span class="n">app</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">app</span><span class="o">.</span><span class="n">smtp</span>
</pre></div>
</div>
<p>Here we declare an <code class="docutils literal"><span class="pre">app</span></code> fixture which receives the previously defined
<code class="docutils literal"><span class="pre">smtp</span></code> fixture and instantiates an <code class="docutils literal"><span class="pre">App</span></code> object with it. Let's run it:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest -v test_appsetup.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
cachedir: .cache
rootdir: $REGENDOC_TMPDIR, inifile:
collecting ... collected 2 items
test_appsetup.py::test_smtp_exists[smtp.gmail.com] PASSED [ 50%]
test_appsetup.py::test_smtp_exists[mail.python.org] PASSED [100%]
========================= 2 passed in 0.12 seconds =========================
</pre></div>
</div>
<p>Due to the parametrization of <code class="docutils literal"><span class="pre">smtp</span></code> the test will run twice with two
different <code class="docutils literal"><span class="pre">App</span></code> instances and respective smtp servers. There is no
need for the <code class="docutils literal"><span class="pre">app</span></code> fixture to be aware of the <code class="docutils literal"><span class="pre">smtp</span></code> parametrization
as pytest will fully analyse the fixture dependency graph.</p>
<p>Note, that the <code class="docutils literal"><span class="pre">app</span></code> fixture has a scope of <code class="docutils literal"><span class="pre">module</span></code> and uses a
module-scoped <code class="docutils literal"><span class="pre">smtp</span></code> fixture. The example would still work if <code class="docutils literal"><span class="pre">smtp</span></code>
was cached on a <code class="docutils literal"><span class="pre">session</span></code> scope: it is fine for fixtures to use
"broader" scoped fixtures but not the other way round:
A session-scoped fixture could not use a module-scoped one in a
meaningful way.</p>
</div>
<div class="section" id="automatic-grouping-of-tests-by-fixture-instances">
<span id="automatic-per-resource-grouping"></span><h2>Automatic grouping of tests by fixture instances<a class="headerlink" href="#automatic-grouping-of-tests-by-fixture-instances" title="Permalink to this headline">¶</a></h2>
<p>pytest minimizes the number of active fixtures during test runs.
If you have a parametrized fixture, then all the tests using it will
first execute with one instance and then finalizers are called
before the next fixture instance is created. Among other things,
this eases testing of applications which create and use global state.</p>
<p>The following example uses two parametrized fixture, one of which is
scoped on a per-module basis, and all the functions perform <code class="docutils literal"><span class="pre">print</span></code> calls
to show the setup/teardown flow:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of test_module.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"module"</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="s2">"mod1"</span><span class="p">,</span> <span class="s2">"mod2"</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">modarg</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="n">param</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">param</span>
<span class="nb">print</span> <span class="p">(</span><span class="s2">" SETUP modarg </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">param</span><span class="p">)</span>
<span class="k">yield</span> <span class="n">param</span>
<span class="nb">print</span> <span class="p">(</span><span class="s2">" TEARDOWN modarg </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">param</span><span class="p">)</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"function"</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">otherarg</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="n">param</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">param</span>
<span class="nb">print</span> <span class="p">(</span><span class="s2">" SETUP otherarg </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">param</span><span class="p">)</span>
<span class="k">yield</span> <span class="n">param</span>
<span class="nb">print</span> <span class="p">(</span><span class="s2">" TEARDOWN otherarg </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">param</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_0</span><span class="p">(</span><span class="n">otherarg</span><span class="p">):</span>
<span class="nb">print</span> <span class="p">(</span><span class="s2">" RUN test0 with otherarg </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">otherarg</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_1</span><span class="p">(</span><span class="n">modarg</span><span class="p">):</span>
<span class="nb">print</span> <span class="p">(</span><span class="s2">" RUN test1 with modarg </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">modarg</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_2</span><span class="p">(</span><span class="n">otherarg</span><span class="p">,</span> <span class="n">modarg</span><span class="p">):</span>
<span class="nb">print</span> <span class="p">(</span><span class="s2">" RUN test2 with otherarg </span><span class="si">%s</span><span class="s2"> and modarg </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">otherarg</span><span class="p">,</span> <span class="n">modarg</span><span class="p">))</span>
</pre></div>
</div>
<p>Let's run the tests in verbose mode and with looking at the print-output:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest -v -s test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
cachedir: .cache
rootdir: $REGENDOC_TMPDIR, inifile:
collecting ... collected 8 items
test_module.py::test_0[1] SETUP otherarg 1
RUN test0 with otherarg 1
PASSED [ 12%] TEARDOWN otherarg 1
test_module.py::test_0[2] SETUP otherarg 2
RUN test0 with otherarg 2
PASSED [ 25%] TEARDOWN otherarg 2
test_module.py::test_1[mod1] SETUP modarg mod1
RUN test1 with modarg mod1
PASSED [ 37%]
test_module.py::test_2[1-mod1] SETUP otherarg 1
RUN test2 with otherarg 1 and modarg mod1
PASSED [ 50%] TEARDOWN otherarg 1
test_module.py::test_2[2-mod1] SETUP otherarg 2
RUN test2 with otherarg 2 and modarg mod1
PASSED [ 62%] TEARDOWN otherarg 2
test_module.py::test_1[mod2] TEARDOWN modarg mod1
SETUP modarg mod2
RUN test1 with modarg mod2
PASSED [ 75%]
test_module.py::test_2[1-mod2] SETUP otherarg 1
RUN test2 with otherarg 1 and modarg mod2
PASSED [ 87%] TEARDOWN otherarg 1
test_module.py::test_2[2-mod2] SETUP otherarg 2
RUN test2 with otherarg 2 and modarg mod2
PASSED [100%] TEARDOWN otherarg 2
TEARDOWN modarg mod2
========================= 8 passed in 0.12 seconds =========================
</pre></div>
</div>
<p>You can see that the parametrized module-scoped <code class="docutils literal"><span class="pre">modarg</span></code> resource caused an
ordering of test execution that lead to the fewest possible "active" resources.
The finalizer for the <code class="docutils literal"><span class="pre">mod1</span></code> parametrized resource was executed before the
<code class="docutils literal"><span class="pre">mod2</span></code> resource was setup.</p>
<p>In particular notice that test_0 is completely independent and finishes first.
Then test_1 is executed with <code class="docutils literal"><span class="pre">mod1</span></code>, then test_2 with <code class="docutils literal"><span class="pre">mod1</span></code>, then test_1
with <code class="docutils literal"><span class="pre">mod2</span></code> and finally test_2 with <code class="docutils literal"><span class="pre">mod2</span></code>.</p>
<p>The <code class="docutils literal"><span class="pre">otherarg</span></code> parametrized resource (having function scope) was set up before
and teared down after every test that used it.</p>
</div>
<div class="section" id="using-fixtures-from-classes-modules-or-projects">
<span id="usefixtures"></span><h2>Using fixtures from classes, modules or projects<a class="headerlink" href="#using-fixtures-from-classes-modules-or-projects" title="Permalink to this headline">¶</a></h2>
<p>Sometimes test functions do not directly need access to a fixture object.
For example, tests may require to operate with an empty directory as the
current working directory but otherwise do not care for the concrete
directory. Here is how you can use the standard <a class="reference external" href="http://docs.python.org/library/tempfile.html">tempfile</a> and pytest fixtures to
achieve it. We separate the creation of the fixture into a conftest.py
file:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of conftest.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="kn">import</span> <span class="nn">tempfile</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">cleandir</span><span class="p">():</span>
<span class="n">newpath</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">mkdtemp</span><span class="p">()</span>
<span class="n">os</span><span class="o">.</span><span class="n">chdir</span><span class="p">(</span><span class="n">newpath</span><span class="p">)</span>
</pre></div>
</div>
<p>and declare its use in a test module via a <code class="docutils literal"><span class="pre">usefixtures</span></code> marker:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of test_setenv.py</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">usefixtures</span><span class="p">(</span><span class="s2">"cleandir"</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">TestDirectoryInit</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">test_cwd_starts_empty</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">getcwd</span><span class="p">())</span> <span class="o">==</span> <span class="p">[]</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">"myfile"</span><span class="p">,</span> <span class="s2">"w"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"hello"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_cwd_again_starts_empty</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">getcwd</span><span class="p">())</span> <span class="o">==</span> <span class="p">[]</span>
</pre></div>
</div>
<p>Due to the <code class="docutils literal"><span class="pre">usefixtures</span></code> marker, the <code class="docutils literal"><span class="pre">cleandir</span></code> fixture
will be required for the execution of each test method, just as if
you specified a "cleandir" function argument to each of them. Let's run it
to verify our fixture is activated and the tests pass:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest -q
.. [100%]
2 passed in 0.12 seconds
</pre></div>
</div>
<p>You can specify multiple fixtures like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="nd">@pytest.mark.usefixtures</span><span class="p">(</span><span class="s2">"cleandir"</span><span class="p">,</span> <span class="s2">"anotherfixture"</span><span class="p">)</span>
</pre></div>
</div>
<p>and you may specify fixture usage at the test module level, using
a generic feature of the mark mechanism:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="n">pytestmark</span> <span class="o">=</span> <span class="n">pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">usefixtures</span><span class="p">(</span><span class="s2">"cleandir"</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that the assigned variable <em>must</em> be called <code class="docutils literal"><span class="pre">pytestmark</span></code>, assigning e.g.
<code class="docutils literal"><span class="pre">foomark</span></code> will not activate the fixtures.</p>
<p>Lastly you can put fixtures required by all tests in your project
into an ini-file:</p>
<div class="highlight-ini"><div class="highlight"><pre><span></span><span class="c1"># content of pytest.ini</span>
<span class="k">[pytest]</span>
<span class="na">usefixtures</span> <span class="o">=</span> <span class="s">cleandir</span>
</pre></div>
</div>
</div>
<div class="section" id="autouse-fixtures-xunit-setup-on-steroids">
<span id="autouse-fixtures"></span><span id="autouse"></span><h2>Autouse fixtures (xUnit setup on steroids)<a class="headerlink" href="#autouse-fixtures-xunit-setup-on-steroids" title="Permalink to this headline">¶</a></h2>
<p>Occasionally, you may want to have fixtures get invoked automatically
without declaring a function argument explicitly or a <a class="reference internal" href="#usefixtures">usefixtures</a> decorator.
As a practical example, suppose we have a database fixture which has a
begin/rollback/commit architecture and we want to automatically surround
each test method by a transaction and a rollback. Here is a dummy
self-contained implementation of this idea:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of test_db_transact.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="k">class</span> <span class="nc">DB</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">intransaction</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">def</span> <span class="nf">begin</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">intransaction</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">rollback</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">intransaction</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s2">"module"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">db</span><span class="p">():</span>
<span class="k">return</span> <span class="n">DB</span><span class="p">()</span>
<span class="k">class</span> <span class="nc">TestClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">autouse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">transact</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">,</span> <span class="n">db</span><span class="p">):</span>
<span class="n">db</span><span class="o">.</span><span class="n">begin</span><span class="p">(</span><span class="n">request</span><span class="o">.</span><span class="n">function</span><span class="o">.</span><span class="vm">__name__</span><span class="p">)</span>
<span class="k">yield</span>
<span class="n">db</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">test_method1</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">db</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">db</span><span class="o">.</span><span class="n">intransaction</span> <span class="o">==</span> <span class="p">[</span><span class="s2">"test_method1"</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">test_method2</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">db</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">db</span><span class="o">.</span><span class="n">intransaction</span> <span class="o">==</span> <span class="p">[</span><span class="s2">"test_method2"</span><span class="p">]</span>
</pre></div>
</div>
<p>The class-level <code class="docutils literal"><span class="pre">transact</span></code> fixture is marked with <em>autouse=true</em>
which implies that all test methods in the class will use this fixture
without a need to state it in the test function signature or with a
class-level <code class="docutils literal"><span class="pre">usefixtures</span></code> decorator.</p>
<p>If we run it, we get two passing tests:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$ pytest -q
.. [100%]
2 passed in 0.12 seconds
</pre></div>
</div>
<p>Here is how autouse fixtures work in other scopes:</p>
<ul class="simple">
<li>autouse fixtures obey the <code class="docutils literal"><span class="pre">scope=</span></code> keyword-argument: if an autouse fixture
has <code class="docutils literal"><span class="pre">scope='session'</span></code> it will only be run once, no matter where it is
defined. <code class="docutils literal"><span class="pre">scope='class'</span></code> means it will be run once per class, etc.</li>
<li>if an autouse fixture is defined in a test module, all its test
functions automatically use it.</li>
<li>if an autouse fixture is defined in a conftest.py file then all tests in
all test modules below its directory will invoke the fixture.</li>
<li>lastly, and <strong>please use that with care</strong>: if you define an autouse
fixture in a plugin, it will be invoked for all tests in all projects
where the plugin is installed. This can be useful if a fixture only
anyway works in the presence of certain settings e. g. in the ini-file. Such
a global fixture should always quickly determine if it should do
any work and avoid otherwise expensive imports or computation.</li>
</ul>
<p>Note that the above <code class="docutils literal"><span class="pre">transact</span></code> fixture may very well be a fixture that
you want to make available in your project without having it generally
active. The canonical way to do that is to put the transact definition
into a conftest.py file <strong>without</strong> using <code class="docutils literal"><span class="pre">autouse</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># content of conftest.py</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">transact</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">db</span><span class="p">):</span>
<span class="n">db</span><span class="o">.</span><span class="n">begin</span><span class="p">()</span>
<span class="k">yield</span>
<span class="n">db</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
</pre></div>
</div>
<p>and then e.g. have a TestClass using it by declaring the need:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="nd">@pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">usefixtures</span><span class="p">(</span><span class="s2">"transact"</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">TestClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">test_method1</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="o">...</span>
</pre></div>
</div>
<p>All test methods in this TestClass will use the transaction fixture while
other test classes or functions in the module will not use it unless
they also add a <code class="docutils literal"><span class="pre">transact</span></code> reference.</p>
</div>
<div class="section" id="overriding-fixtures-on-various-levels">
<h2>Overriding fixtures on various levels<a class="headerlink" href="#overriding-fixtures-on-various-levels" title="Permalink to this headline">¶</a></h2>
<p>In relatively large test suite, you most likely need to <code class="docutils literal"><span class="pre">override</span></code> a <code class="docutils literal"><span class="pre">global</span></code> or <code class="docutils literal"><span class="pre">root</span></code> fixture with a <code class="docutils literal"><span class="pre">locally</span></code>
defined one, keeping the test code readable and maintainable.</p>
<div class="section" id="override-a-fixture-on-a-folder-conftest-level">
<h3>Override a fixture on a folder (conftest) level<a class="headerlink" href="#override-a-fixture-on-a-folder-conftest-level" title="Permalink to this headline">¶</a></h3>
<p>Given the tests file structure is:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">tests</span><span class="o">/</span>
<span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">conftest</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/conftest.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">username</span><span class="p">():</span>
<span class="k">return</span> <span class="s1">'username'</span>
<span class="n">test_something</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/test_something.py</span>
<span class="k">def</span> <span class="nf">test_username</span><span class="p">(</span><span class="n">username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">username</span> <span class="o">==</span> <span class="s1">'username'</span>
<span class="n">subfolder</span><span class="o">/</span>
<span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">conftest</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/subfolder/conftest.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">username</span><span class="p">(</span><span class="n">username</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'overridden-'</span> <span class="o">+</span> <span class="n">username</span>
<span class="n">test_something</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/subfolder/test_something.py</span>
<span class="k">def</span> <span class="nf">test_username</span><span class="p">(</span><span class="n">username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">username</span> <span class="o">==</span> <span class="s1">'overridden-username'</span>
</pre></div>
</div>
<p>As you can see, a fixture with the same name can be overridden for certain test folder level.
Note that the <code class="docutils literal"><span class="pre">base</span></code> or <code class="docutils literal"><span class="pre">super</span></code> fixture can be accessed from the <code class="docutils literal"><span class="pre">overriding</span></code>
fixture easily - used in the example above.</p>
</div>
<div class="section" id="override-a-fixture-on-a-test-module-level">
<h3>Override a fixture on a test module level<a class="headerlink" href="#override-a-fixture-on-a-test-module-level" title="Permalink to this headline">¶</a></h3>
<p>Given the tests file structure is:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">tests</span><span class="o">/</span>
<span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">conftest</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/conftest.py</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">username</span><span class="p">():</span>
<span class="k">return</span> <span class="s1">'username'</span>
<span class="n">test_something</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/test_something.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">username</span><span class="p">(</span><span class="n">username</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'overridden-'</span> <span class="o">+</span> <span class="n">username</span>
<span class="k">def</span> <span class="nf">test_username</span><span class="p">(</span><span class="n">username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">username</span> <span class="o">==</span> <span class="s1">'overridden-username'</span>
<span class="n">test_something_else</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/test_something_else.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">username</span><span class="p">(</span><span class="n">username</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'overridden-else-'</span> <span class="o">+</span> <span class="n">username</span>
<span class="k">def</span> <span class="nf">test_username</span><span class="p">(</span><span class="n">username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">username</span> <span class="o">==</span> <span class="s1">'overridden-else-username'</span>
</pre></div>
</div>
<p>In the example above, a fixture with the same name can be overridden for certain test module.</p>
</div>
<div class="section" id="override-a-fixture-with-direct-test-parametrization">
<h3>Override a fixture with direct test parametrization<a class="headerlink" href="#override-a-fixture-with-direct-test-parametrization" title="Permalink to this headline">¶</a></h3>
<p>Given the tests file structure is:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">tests</span><span class="o">/</span>
<span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">conftest</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/conftest.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">username</span><span class="p">():</span>
<span class="k">return</span> <span class="s1">'username'</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">other_username</span><span class="p">(</span><span class="n">username</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'other-'</span> <span class="o">+</span> <span class="n">username</span>
<span class="n">test_something</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/test_something.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">parametrize</span><span class="p">(</span><span class="s1">'username'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'directly-overridden-username'</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">test_username</span><span class="p">(</span><span class="n">username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">username</span> <span class="o">==</span> <span class="s1">'directly-overridden-username'</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">mark</span><span class="o">.</span><span class="n">parametrize</span><span class="p">(</span><span class="s1">'username'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'directly-overridden-username-other'</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">test_username_other</span><span class="p">(</span><span class="n">other_username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">other_username</span> <span class="o">==</span> <span class="s1">'other-directly-overridden-username-other'</span>
</pre></div>
</div>
<p>In the example above, a fixture value is overridden by the test parameter value. Note that the value of the fixture
can be overridden this way even if the test doesn't use it directly (doesn't mention it in the function prototype).</p>
</div>
<div class="section" id="override-a-parametrized-fixture-with-non-parametrized-one-and-vice-versa">
<h3>Override a parametrized fixture with non-parametrized one and vice versa<a class="headerlink" href="#override-a-parametrized-fixture-with-non-parametrized-one-and-vice-versa" title="Permalink to this headline">¶</a></h3>
<p>Given the tests file structure is:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">tests</span><span class="o">/</span>
<span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">conftest</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/conftest.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="s1">'one'</span><span class="p">,</span> <span class="s1">'two'</span><span class="p">,</span> <span class="s1">'three'</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">parametrized_username</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">request</span><span class="o">.</span><span class="n">param</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">non_parametrized_username</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'username'</span>
<span class="n">test_something</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/test_something.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span>
<span class="k">def</span> <span class="nf">parametrized_username</span><span class="p">():</span>
<span class="k">return</span> <span class="s1">'overridden-username'</span>
<span class="nd">@pytest</span><span class="o">.</span><span class="n">fixture</span><span class="p">(</span><span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="s1">'one'</span><span class="p">,</span> <span class="s1">'two'</span><span class="p">,</span> <span class="s1">'three'</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">non_parametrized_username</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">request</span><span class="o">.</span><span class="n">param</span>
<span class="k">def</span> <span class="nf">test_username</span><span class="p">(</span><span class="n">parametrized_username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">parametrized_username</span> <span class="o">==</span> <span class="s1">'overridden-username'</span>
<span class="k">def</span> <span class="nf">test_parametrized_username</span><span class="p">(</span><span class="n">non_parametrized_username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">non_parametrized_username</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">'one'</span><span class="p">,</span> <span class="s1">'two'</span><span class="p">,</span> <span class="s1">'three'</span><span class="p">]</span>
<span class="n">test_something_else</span><span class="o">.</span><span class="n">py</span>
<span class="c1"># content of tests/test_something_else.py</span>
<span class="k">def</span> <span class="nf">test_username</span><span class="p">(</span><span class="n">parametrized_username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">parametrized_username</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">'one'</span><span class="p">,</span> <span class="s1">'two'</span><span class="p">,</span> <span class="s1">'three'</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">test_username</span><span class="p">(</span><span class="n">non_parametrized_username</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">non_parametrized_username</span> <span class="o">==</span> <span class="s1">'username'</span>
</pre></div>
</div>
<p>In the example above, a parametrized fixture is overridden with a non-parametrized version, and
a non-parametrized fixture is overridden with a parametrized version for certain test module.
The same applies for the test folder level obviously.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<p class="logo"><a href="contents.html">
<img class="logo" src="_static/pytest1.png" alt="Logo"/>
</a></p><h3><a href="contents.html">Table Of Contents</a></h3>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="contents.html">Contents</a></li>
<li><a href="getting-started.html">Install</a></li>
<li><a href="example/index.html">Examples</a></li>
<li><a href="customize.html">Customize</a></li>
<li><a href="contact.html">Contact</a></li>
<li><a href="talks.html">Talks/Posts</a></li>
<li><a href="changelog.html">Changelog</a></li>
<li><a href="backwards-compatibility.html">Backwards Compatibility</a></li>
<li><a href="license.html">License</a></li>
</ul>
<hr>
<ul>
<li><a class="reference internal" href="#">pytest fixtures: explicit, modular, scalable</a><ul>
<li><a class="reference internal" href="#fixtures-as-function-arguments">Fixtures as Function arguments</a></li>
<li><a class="reference internal" href="#fixtures-a-prime-example-of-dependency-injection">Fixtures: a prime example of dependency injection</a></li>
<li><a class="reference internal" href="#conftest-py-sharing-fixture-functions"><code class="docutils literal"><span class="pre">conftest.py</span></code>: sharing fixture functions</a></li>
<li><a class="reference internal" href="#sharing-test-data">Sharing test data</a></li>
<li><a class="reference internal" href="#scope-sharing-a-fixture-instance-across-tests-in-a-class-module-or-session">Scope: sharing a fixture instance across tests in a class, module or session</a></li>
<li><a class="reference internal" href="#fixture-finalization-executing-teardown-code">Fixture finalization / executing teardown code</a></li>
<li><a class="reference internal" href="#fixtures-can-introspect-the-requesting-test-context">Fixtures can introspect the requesting test context</a></li>
<li><a class="reference internal" href="#parametrizing-fixtures">Parametrizing fixtures</a></li>
<li><a class="reference internal" href="#modularity-using-fixtures-from-a-fixture-function">Modularity: using fixtures from a fixture function</a></li>
<li><a class="reference internal" href="#automatic-grouping-of-tests-by-fixture-instances">Automatic grouping of tests by fixture instances</a></li>
<li><a class="reference internal" href="#using-fixtures-from-classes-modules-or-projects">Using fixtures from classes, modules or projects</a></li>
<li><a class="reference internal" href="#autouse-fixtures-xunit-setup-on-steroids">Autouse fixtures (xUnit setup on steroids)</a></li>
<li><a class="reference internal" href="#overriding-fixtures-on-various-levels">Overriding fixtures on various levels</a><ul>
<li><a class="reference internal" href="#override-a-fixture-on-a-folder-conftest-level">Override a fixture on a folder (conftest) level</a></li>
<li><a class="reference internal" href="#override-a-fixture-on-a-test-module-level">Override a fixture on a test module level</a></li>
<li><a class="reference internal" href="#override-a-fixture-with-direct-test-parametrization">Override a fixture with direct test parametrization</a></li>
<li><a class="reference internal" href="#override-a-parametrized-fixture-with-non-parametrized-one-and-vice-versa">Override a parametrized fixture with non-parametrized one and vice versa</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h3>Related Topics</h3>
<ul>
<li><a href="contents.html">Documentation overview</a><ul>
<li>Previous: <a href="builtin.html" title="previous chapter">Pytest API and builtin fixtures</a></li>
<li>Next: <a href="monkeypatch.html" title="next chapter">Monkeypatching/mocking modules and environments</a></li>
</ul></li>
</ul><h3>Useful Links</h3>
<ul>
<li><a href="index.html">The pytest Website</a></li>
<li><a href="contributing.html">Contribution Guide</a></li>
<li><a href="https://pypi.python.org/pypi/pytest">pytest @ PyPI</a></li>
<li><a href="https://github.com/pytest-dev/pytest/">pytest @ GitHub</a></li>
<li><a href="http://plugincompat.herokuapp.com/">3rd party plugins</a></li>
<li><a href="https://github.com/pytest-dev/pytest/issues">Issue Tracker</a></li>
<li><a href="https://media.readthedocs.org/pdf/pytest/latest/pytest.pdf">PDF Documentation</a>
</ul>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
© Copyright 2018, holger krekel and pytest-dev team.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>.
</div>
</body>
</html>
|