1from textwrap import dedent 2 3import _pytest._code 4import pytest 5from _pytest.pytester import get_public_names 6from _pytest.fixtures import FixtureLookupError, FixtureRequest 7from _pytest import fixtures 8 9 10def test_getfuncargnames(): 11 12 def f(): 13 pass 14 15 assert not fixtures.getfuncargnames(f) 16 17 def g(arg): 18 pass 19 20 assert fixtures.getfuncargnames(g) == ("arg",) 21 22 def h(arg1, arg2="hello"): 23 pass 24 25 assert fixtures.getfuncargnames(h) == ("arg1",) 26 27 def h(arg1, arg2, arg3="hello"): 28 pass 29 30 assert fixtures.getfuncargnames(h) == ("arg1", "arg2") 31 32 class A(object): 33 34 def f(self, arg1, arg2="hello"): 35 pass 36 37 @staticmethod 38 def static(arg1, arg2): 39 pass 40 41 assert fixtures.getfuncargnames(A().f) == ("arg1",) 42 assert fixtures.getfuncargnames(A.static, cls=A) == ("arg1", "arg2") 43 44 45class TestFillFixtures(object): 46 47 def test_fillfuncargs_exposed(self): 48 # used by oejskit, kept for compatibility 49 assert pytest._fillfuncargs == fixtures.fillfixtures 50 51 def test_funcarg_lookupfails(self, testdir): 52 testdir.makepyfile( 53 """ 54 import pytest 55 56 @pytest.fixture 57 def xyzsomething(request): 58 return 42 59 60 def test_func(some): 61 pass 62 """ 63 ) 64 result = testdir.runpytest() # "--collect-only") 65 assert result.ret != 0 66 result.stdout.fnmatch_lines( 67 ["*def test_func(some)*", "*fixture*some*not found*", "*xyzsomething*"] 68 ) 69 70 def test_funcarg_basic(self, testdir): 71 item = testdir.getitem( 72 """ 73 import pytest 74 75 @pytest.fixture 76 def some(request): 77 return request.function.__name__ 78 @pytest.fixture 79 def other(request): 80 return 42 81 def test_func(some, other): 82 pass 83 """ 84 ) 85 fixtures.fillfixtures(item) 86 del item.funcargs["request"] 87 assert len(get_public_names(item.funcargs)) == 2 88 assert item.funcargs["some"] == "test_func" 89 assert item.funcargs["other"] == 42 90 91 def test_funcarg_lookup_modulelevel(self, testdir): 92 testdir.makepyfile( 93 """ 94 import pytest 95 96 @pytest.fixture 97 def something(request): 98 return request.function.__name__ 99 100 class TestClass(object): 101 def test_method(self, something): 102 assert something == "test_method" 103 def test_func(something): 104 assert something == "test_func" 105 """ 106 ) 107 reprec = testdir.inline_run() 108 reprec.assertoutcome(passed=2) 109 110 def test_funcarg_lookup_classlevel(self, testdir): 111 p = testdir.makepyfile( 112 """ 113 import pytest 114 class TestClass(object): 115 116 @pytest.fixture 117 def something(self, request): 118 return request.instance 119 120 def test_method(self, something): 121 assert something is self 122 """ 123 ) 124 result = testdir.runpytest(p) 125 result.stdout.fnmatch_lines(["*1 passed*"]) 126 127 def test_conftest_funcargs_only_available_in_subdir(self, testdir): 128 sub1 = testdir.mkpydir("sub1") 129 sub2 = testdir.mkpydir("sub2") 130 sub1.join("conftest.py").write( 131 _pytest._code.Source( 132 """ 133 import pytest 134 @pytest.fixture 135 def arg1(request): 136 pytest.raises(Exception, "request.getfixturevalue('arg2')") 137 """ 138 ) 139 ) 140 sub2.join("conftest.py").write( 141 _pytest._code.Source( 142 """ 143 import pytest 144 @pytest.fixture 145 def arg2(request): 146 pytest.raises(Exception, "request.getfixturevalue('arg1')") 147 """ 148 ) 149 ) 150 151 sub1.join("test_in_sub1.py").write("def test_1(arg1): pass") 152 sub2.join("test_in_sub2.py").write("def test_2(arg2): pass") 153 result = testdir.runpytest("-v") 154 result.assert_outcomes(passed=2) 155 156 def test_extend_fixture_module_class(self, testdir): 157 testfile = testdir.makepyfile( 158 """ 159 import pytest 160 161 @pytest.fixture 162 def spam(): 163 return 'spam' 164 165 class TestSpam(object): 166 167 @pytest.fixture 168 def spam(self, spam): 169 return spam * 2 170 171 def test_spam(self, spam): 172 assert spam == 'spamspam' 173 """ 174 ) 175 result = testdir.runpytest() 176 result.stdout.fnmatch_lines(["*1 passed*"]) 177 result = testdir.runpytest(testfile) 178 result.stdout.fnmatch_lines(["*1 passed*"]) 179 180 def test_extend_fixture_conftest_module(self, testdir): 181 testdir.makeconftest( 182 """ 183 import pytest 184 185 @pytest.fixture 186 def spam(): 187 return 'spam' 188 """ 189 ) 190 testfile = testdir.makepyfile( 191 """ 192 import pytest 193 194 @pytest.fixture 195 def spam(spam): 196 return spam * 2 197 198 def test_spam(spam): 199 assert spam == 'spamspam' 200 """ 201 ) 202 result = testdir.runpytest() 203 result.stdout.fnmatch_lines(["*1 passed*"]) 204 result = testdir.runpytest(testfile) 205 result.stdout.fnmatch_lines(["*1 passed*"]) 206 207 def test_extend_fixture_conftest_conftest(self, testdir): 208 testdir.makeconftest( 209 """ 210 import pytest 211 212 @pytest.fixture 213 def spam(): 214 return 'spam' 215 """ 216 ) 217 pkg = testdir.mkpydir("pkg") 218 pkg.join("conftest.py").write( 219 _pytest._code.Source( 220 """ 221 import pytest 222 223 @pytest.fixture 224 def spam(spam): 225 return spam * 2 226 """ 227 ) 228 ) 229 testfile = pkg.join("test_spam.py") 230 testfile.write( 231 _pytest._code.Source( 232 """ 233 def test_spam(spam): 234 assert spam == "spamspam" 235 """ 236 ) 237 ) 238 result = testdir.runpytest() 239 result.stdout.fnmatch_lines(["*1 passed*"]) 240 result = testdir.runpytest(testfile) 241 result.stdout.fnmatch_lines(["*1 passed*"]) 242 243 def test_extend_fixture_conftest_plugin(self, testdir): 244 testdir.makepyfile( 245 testplugin=""" 246 import pytest 247 248 @pytest.fixture 249 def foo(): 250 return 7 251 """ 252 ) 253 testdir.syspathinsert() 254 testdir.makeconftest( 255 """ 256 import pytest 257 258 pytest_plugins = 'testplugin' 259 260 @pytest.fixture 261 def foo(foo): 262 return foo + 7 263 """ 264 ) 265 testdir.makepyfile( 266 """ 267 def test_foo(foo): 268 assert foo == 14 269 """ 270 ) 271 result = testdir.runpytest("-s") 272 assert result.ret == 0 273 274 def test_extend_fixture_plugin_plugin(self, testdir): 275 # Two plugins should extend each order in loading order 276 testdir.makepyfile( 277 testplugin0=""" 278 import pytest 279 280 @pytest.fixture 281 def foo(): 282 return 7 283 """ 284 ) 285 testdir.makepyfile( 286 testplugin1=""" 287 import pytest 288 289 @pytest.fixture 290 def foo(foo): 291 return foo + 7 292 """ 293 ) 294 testdir.syspathinsert() 295 testdir.makepyfile( 296 """ 297 pytest_plugins = ['testplugin0', 'testplugin1'] 298 299 def test_foo(foo): 300 assert foo == 14 301 """ 302 ) 303 result = testdir.runpytest() 304 assert result.ret == 0 305 306 def test_override_parametrized_fixture_conftest_module(self, testdir): 307 """Test override of the parametrized fixture with non-parametrized one on the test module level.""" 308 testdir.makeconftest( 309 """ 310 import pytest 311 312 @pytest.fixture(params=[1, 2, 3]) 313 def spam(request): 314 return request.param 315 """ 316 ) 317 testfile = testdir.makepyfile( 318 """ 319 import pytest 320 321 @pytest.fixture 322 def spam(): 323 return 'spam' 324 325 def test_spam(spam): 326 assert spam == 'spam' 327 """ 328 ) 329 result = testdir.runpytest() 330 result.stdout.fnmatch_lines(["*1 passed*"]) 331 result = testdir.runpytest(testfile) 332 result.stdout.fnmatch_lines(["*1 passed*"]) 333 334 def test_override_parametrized_fixture_conftest_conftest(self, testdir): 335 """Test override of the parametrized fixture with non-parametrized one on the conftest level.""" 336 testdir.makeconftest( 337 """ 338 import pytest 339 340 @pytest.fixture(params=[1, 2, 3]) 341 def spam(request): 342 return request.param 343 """ 344 ) 345 subdir = testdir.mkpydir("subdir") 346 subdir.join("conftest.py").write( 347 _pytest._code.Source( 348 """ 349 import pytest 350 351 @pytest.fixture 352 def spam(): 353 return 'spam' 354 """ 355 ) 356 ) 357 testfile = subdir.join("test_spam.py") 358 testfile.write( 359 _pytest._code.Source( 360 """ 361 def test_spam(spam): 362 assert spam == "spam" 363 """ 364 ) 365 ) 366 result = testdir.runpytest() 367 result.stdout.fnmatch_lines(["*1 passed*"]) 368 result = testdir.runpytest(testfile) 369 result.stdout.fnmatch_lines(["*1 passed*"]) 370 371 def test_override_non_parametrized_fixture_conftest_module(self, testdir): 372 """Test override of the non-parametrized fixture with parametrized one on the test module level.""" 373 testdir.makeconftest( 374 """ 375 import pytest 376 377 @pytest.fixture 378 def spam(): 379 return 'spam' 380 """ 381 ) 382 testfile = testdir.makepyfile( 383 """ 384 import pytest 385 386 @pytest.fixture(params=[1, 2, 3]) 387 def spam(request): 388 return request.param 389 390 params = {'spam': 1} 391 392 def test_spam(spam): 393 assert spam == params['spam'] 394 params['spam'] += 1 395 """ 396 ) 397 result = testdir.runpytest() 398 result.stdout.fnmatch_lines(["*3 passed*"]) 399 result = testdir.runpytest(testfile) 400 result.stdout.fnmatch_lines(["*3 passed*"]) 401 402 def test_override_non_parametrized_fixture_conftest_conftest(self, testdir): 403 """Test override of the non-parametrized fixture with parametrized one on the conftest level.""" 404 testdir.makeconftest( 405 """ 406 import pytest 407 408 @pytest.fixture 409 def spam(): 410 return 'spam' 411 """ 412 ) 413 subdir = testdir.mkpydir("subdir") 414 subdir.join("conftest.py").write( 415 _pytest._code.Source( 416 """ 417 import pytest 418 419 @pytest.fixture(params=[1, 2, 3]) 420 def spam(request): 421 return request.param 422 """ 423 ) 424 ) 425 testfile = subdir.join("test_spam.py") 426 testfile.write( 427 _pytest._code.Source( 428 """ 429 params = {'spam': 1} 430 431 def test_spam(spam): 432 assert spam == params['spam'] 433 params['spam'] += 1 434 """ 435 ) 436 ) 437 result = testdir.runpytest() 438 result.stdout.fnmatch_lines(["*3 passed*"]) 439 result = testdir.runpytest(testfile) 440 result.stdout.fnmatch_lines(["*3 passed*"]) 441 442 def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest( 443 self, testdir 444 ): 445 """Test override of the autouse fixture with parametrized one on the conftest level. 446 This test covers the issue explained in issue 1601 447 """ 448 testdir.makeconftest( 449 """ 450 import pytest 451 452 @pytest.fixture(autouse=True) 453 def spam(): 454 return 'spam' 455 """ 456 ) 457 subdir = testdir.mkpydir("subdir") 458 subdir.join("conftest.py").write( 459 _pytest._code.Source( 460 """ 461 import pytest 462 463 @pytest.fixture(params=[1, 2, 3]) 464 def spam(request): 465 return request.param 466 """ 467 ) 468 ) 469 testfile = subdir.join("test_spam.py") 470 testfile.write( 471 _pytest._code.Source( 472 """ 473 params = {'spam': 1} 474 475 def test_spam(spam): 476 assert spam == params['spam'] 477 params['spam'] += 1 478 """ 479 ) 480 ) 481 result = testdir.runpytest() 482 result.stdout.fnmatch_lines(["*3 passed*"]) 483 result = testdir.runpytest(testfile) 484 result.stdout.fnmatch_lines(["*3 passed*"]) 485 486 def test_autouse_fixture_plugin(self, testdir): 487 # A fixture from a plugin has no baseid set, which screwed up 488 # the autouse fixture handling. 489 testdir.makepyfile( 490 testplugin=""" 491 import pytest 492 493 @pytest.fixture(autouse=True) 494 def foo(request): 495 request.function.foo = 7 496 """ 497 ) 498 testdir.syspathinsert() 499 testdir.makepyfile( 500 """ 501 pytest_plugins = 'testplugin' 502 503 def test_foo(request): 504 assert request.function.foo == 7 505 """ 506 ) 507 result = testdir.runpytest() 508 assert result.ret == 0 509 510 def test_funcarg_lookup_error(self, testdir): 511 testdir.makeconftest( 512 """ 513 import pytest 514 515 @pytest.fixture 516 def a_fixture(): pass 517 518 @pytest.fixture 519 def b_fixture(): pass 520 521 @pytest.fixture 522 def c_fixture(): pass 523 524 @pytest.fixture 525 def d_fixture(): pass 526 """ 527 ) 528 testdir.makepyfile( 529 """ 530 def test_lookup_error(unknown): 531 pass 532 """ 533 ) 534 result = testdir.runpytest() 535 result.stdout.fnmatch_lines( 536 [ 537 "*ERROR at setup of test_lookup_error*", 538 " def test_lookup_error(unknown):*", 539 "E fixture 'unknown' not found", 540 "> available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*", # sorted 541 "> use 'py*test --fixtures *' for help on them.", 542 "*1 error*", 543 ] 544 ) 545 assert "INTERNAL" not in result.stdout.str() 546 547 def test_fixture_excinfo_leak(self, testdir): 548 # on python2 sys.excinfo would leak into fixture executions 549 testdir.makepyfile( 550 """ 551 import sys 552 import traceback 553 import pytest 554 555 @pytest.fixture 556 def leak(): 557 if sys.exc_info()[0]: # python3 bug :) 558 traceback.print_exc() 559 #fails 560 assert sys.exc_info() == (None, None, None) 561 562 def test_leak(leak): 563 if sys.exc_info()[0]: # python3 bug :) 564 traceback.print_exc() 565 assert sys.exc_info() == (None, None, None) 566 """ 567 ) 568 result = testdir.runpytest() 569 assert result.ret == 0 570 571 572class TestRequestBasic(object): 573 574 def test_request_attributes(self, testdir): 575 item = testdir.getitem( 576 """ 577 import pytest 578 579 @pytest.fixture 580 def something(request): pass 581 def test_func(something): pass 582 """ 583 ) 584 req = fixtures.FixtureRequest(item) 585 assert req.function == item.obj 586 assert req.keywords == item.keywords 587 assert hasattr(req.module, "test_func") 588 assert req.cls is None 589 assert req.function.__name__ == "test_func" 590 assert req.config == item.config 591 assert repr(req).find(req.function.__name__) != -1 592 593 def test_request_attributes_method(self, testdir): 594 item, = testdir.getitems( 595 """ 596 import pytest 597 class TestB(object): 598 599 @pytest.fixture 600 def something(self, request): 601 return 1 602 def test_func(self, something): 603 pass 604 """ 605 ) 606 req = item._request 607 assert req.cls.__name__ == "TestB" 608 assert req.instance.__class__ == req.cls 609 610 def test_request_contains_funcarg_arg2fixturedefs(self, testdir): 611 modcol = testdir.getmodulecol( 612 """ 613 import pytest 614 @pytest.fixture 615 def something(request): 616 pass 617 class TestClass(object): 618 def test_method(self, something): 619 pass 620 """ 621 ) 622 item1, = testdir.genitems([modcol]) 623 assert item1.name == "test_method" 624 arg2fixturedefs = fixtures.FixtureRequest(item1)._arg2fixturedefs 625 assert len(arg2fixturedefs) == 1 626 assert arg2fixturedefs["something"][0].argname == "something" 627 628 def test_request_garbage(self, testdir): 629 testdir.makepyfile( 630 """ 631 import sys 632 import pytest 633 from _pytest.fixtures import PseudoFixtureDef 634 import gc 635 636 @pytest.fixture(autouse=True) 637 def something(request): 638 # this method of test doesn't work on pypy 639 if hasattr(sys, "pypy_version_info"): 640 yield 641 else: 642 original = gc.get_debug() 643 gc.set_debug(gc.DEBUG_SAVEALL) 644 gc.collect() 645 646 yield 647 648 gc.collect() 649 leaked_types = sum(1 for _ in gc.garbage 650 if isinstance(_, PseudoFixtureDef)) 651 652 gc.garbage[:] = [] 653 654 try: 655 assert leaked_types == 0 656 finally: 657 gc.set_debug(original) 658 659 def test_func(): 660 pass 661 """ 662 ) 663 reprec = testdir.inline_run() 664 reprec.assertoutcome(passed=1) 665 666 def test_getfixturevalue_recursive(self, testdir): 667 testdir.makeconftest( 668 """ 669 import pytest 670 671 @pytest.fixture 672 def something(request): 673 return 1 674 """ 675 ) 676 testdir.makepyfile( 677 """ 678 import pytest 679 680 @pytest.fixture 681 def something(request): 682 return request.getfixturevalue("something") + 1 683 def test_func(something): 684 assert something == 2 685 """ 686 ) 687 reprec = testdir.inline_run() 688 reprec.assertoutcome(passed=1) 689 690 @pytest.mark.parametrize("getfixmethod", ("getfixturevalue", "getfuncargvalue")) 691 def test_getfixturevalue(self, testdir, getfixmethod): 692 item = testdir.getitem( 693 """ 694 import pytest 695 values = [2] 696 @pytest.fixture 697 def something(request): return 1 698 @pytest.fixture 699 def other(request): 700 return values.pop() 701 def test_func(something): pass 702 """ 703 ) 704 import contextlib 705 706 if getfixmethod == "getfuncargvalue": 707 warning_expectation = pytest.warns(DeprecationWarning) 708 else: 709 # see #1830 for a cleaner way to accomplish this 710 @contextlib.contextmanager 711 def expecting_no_warning(): 712 yield 713 714 warning_expectation = expecting_no_warning() 715 716 req = item._request 717 with warning_expectation: 718 fixture_fetcher = getattr(req, getfixmethod) 719 with pytest.raises(FixtureLookupError): 720 fixture_fetcher("notexists") 721 val = fixture_fetcher("something") 722 assert val == 1 723 val = fixture_fetcher("something") 724 assert val == 1 725 val2 = fixture_fetcher("other") 726 assert val2 == 2 727 val2 = fixture_fetcher("other") # see about caching 728 assert val2 == 2 729 pytest._fillfuncargs(item) 730 assert item.funcargs["something"] == 1 731 assert len(get_public_names(item.funcargs)) == 2 732 assert "request" in item.funcargs 733 734 def test_request_addfinalizer(self, testdir): 735 item = testdir.getitem( 736 """ 737 import pytest 738 teardownlist = [] 739 @pytest.fixture 740 def something(request): 741 request.addfinalizer(lambda: teardownlist.append(1)) 742 def test_func(something): pass 743 """ 744 ) 745 item.session._setupstate.prepare(item) 746 pytest._fillfuncargs(item) 747 # successively check finalization calls 748 teardownlist = item.getparent(pytest.Module).obj.teardownlist 749 ss = item.session._setupstate 750 assert not teardownlist 751 ss.teardown_exact(item, None) 752 print(ss.stack) 753 assert teardownlist == [1] 754 755 def test_mark_as_fixture_with_prefix_and_decorator_fails(self, testdir): 756 testdir.makeconftest( 757 """ 758 import pytest 759 760 @pytest.fixture 761 def pytest_funcarg__marked_with_prefix_and_decorator(): 762 pass 763 """ 764 ) 765 result = testdir.runpytest_subprocess() 766 assert result.ret != 0 767 result.stdout.fnmatch_lines( 768 [ 769 "*AssertionError: fixtures cannot have*@pytest.fixture*", 770 "*pytest_funcarg__marked_with_prefix_and_decorator*", 771 ] 772 ) 773 774 def test_request_addfinalizer_failing_setup(self, testdir): 775 testdir.makepyfile( 776 """ 777 import pytest 778 values = [1] 779 @pytest.fixture 780 def myfix(request): 781 request.addfinalizer(values.pop) 782 assert 0 783 def test_fix(myfix): 784 pass 785 def test_finalizer_ran(): 786 assert not values 787 """ 788 ) 789 reprec = testdir.inline_run("-s") 790 reprec.assertoutcome(failed=1, passed=1) 791 792 def test_request_addfinalizer_failing_setup_module(self, testdir): 793 testdir.makepyfile( 794 """ 795 import pytest 796 values = [1, 2] 797 @pytest.fixture(scope="module") 798 def myfix(request): 799 request.addfinalizer(values.pop) 800 request.addfinalizer(values.pop) 801 assert 0 802 def test_fix(myfix): 803 pass 804 """ 805 ) 806 reprec = testdir.inline_run("-s") 807 mod = reprec.getcalls("pytest_runtest_setup")[0].item.module 808 assert not mod.values 809 810 def test_request_addfinalizer_partial_setup_failure(self, testdir): 811 p = testdir.makepyfile( 812 """ 813 import pytest 814 values = [] 815 @pytest.fixture 816 def something(request): 817 request.addfinalizer(lambda: values.append(None)) 818 def test_func(something, missingarg): 819 pass 820 def test_second(): 821 assert len(values) == 1 822 """ 823 ) 824 result = testdir.runpytest(p) 825 result.stdout.fnmatch_lines( 826 ["*1 error*"] # XXX the whole module collection fails 827 ) 828 829 def test_request_subrequest_addfinalizer_exceptions(self, testdir): 830 """ 831 Ensure exceptions raised during teardown by a finalizer are suppressed 832 until all finalizers are called, re-raising the first exception (#2440) 833 """ 834 testdir.makepyfile( 835 """ 836 import pytest 837 values = [] 838 def _excepts(where): 839 raise Exception('Error in %s fixture' % where) 840 @pytest.fixture 841 def subrequest(request): 842 return request 843 @pytest.fixture 844 def something(subrequest): 845 subrequest.addfinalizer(lambda: values.append(1)) 846 subrequest.addfinalizer(lambda: values.append(2)) 847 subrequest.addfinalizer(lambda: _excepts('something')) 848 @pytest.fixture 849 def excepts(subrequest): 850 subrequest.addfinalizer(lambda: _excepts('excepts')) 851 subrequest.addfinalizer(lambda: values.append(3)) 852 def test_first(something, excepts): 853 pass 854 def test_second(): 855 assert values == [3, 2, 1] 856 """ 857 ) 858 result = testdir.runpytest() 859 result.stdout.fnmatch_lines( 860 ["*Exception: Error in excepts fixture", "* 2 passed, 1 error in *"] 861 ) 862 863 def test_request_getmodulepath(self, testdir): 864 modcol = testdir.getmodulecol("def test_somefunc(): pass") 865 item, = testdir.genitems([modcol]) 866 req = fixtures.FixtureRequest(item) 867 assert req.fspath == modcol.fspath 868 869 def test_request_fixturenames(self, testdir): 870 testdir.makepyfile( 871 """ 872 import pytest 873 from _pytest.pytester import get_public_names 874 @pytest.fixture() 875 def arg1(): 876 pass 877 @pytest.fixture() 878 def farg(arg1): 879 pass 880 @pytest.fixture(autouse=True) 881 def sarg(tmpdir): 882 pass 883 def test_function(request, farg): 884 assert set(get_public_names(request.fixturenames)) == \ 885 set(["tmpdir", "sarg", "arg1", "request", "farg", 886 "tmpdir_factory"]) 887 """ 888 ) 889 reprec = testdir.inline_run() 890 reprec.assertoutcome(passed=1) 891 892 def test_funcargnames_compatattr(self, testdir): 893 testdir.makepyfile( 894 """ 895 import pytest 896 def pytest_generate_tests(metafunc): 897 assert metafunc.funcargnames == metafunc.fixturenames 898 @pytest.fixture 899 def fn(request): 900 assert request._pyfuncitem.funcargnames == \ 901 request._pyfuncitem.fixturenames 902 return request.funcargnames, request.fixturenames 903 904 def test_hello(fn): 905 assert fn[0] == fn[1] 906 """ 907 ) 908 reprec = testdir.inline_run() 909 reprec.assertoutcome(passed=1) 910 911 def test_setupdecorator_and_xunit(self, testdir): 912 testdir.makepyfile( 913 """ 914 import pytest 915 values = [] 916 @pytest.fixture(scope='module', autouse=True) 917 def setup_module(): 918 values.append("module") 919 @pytest.fixture(autouse=True) 920 def setup_function(): 921 values.append("function") 922 923 def test_func(): 924 pass 925 926 class TestClass(object): 927 @pytest.fixture(scope="class", autouse=True) 928 def setup_class(self): 929 values.append("class") 930 @pytest.fixture(autouse=True) 931 def setup_method(self): 932 values.append("method") 933 def test_method(self): 934 pass 935 def test_all(): 936 assert values == ["module", "function", "class", 937 "function", "method", "function"] 938 """ 939 ) 940 reprec = testdir.inline_run("-v") 941 reprec.assertoutcome(passed=3) 942 943 def test_fixtures_sub_subdir_normalize_sep(self, testdir): 944 # this tests that normalization of nodeids takes place 945 b = testdir.mkdir("tests").mkdir("unit") 946 b.join("conftest.py").write( 947 _pytest._code.Source( 948 """ 949 import pytest 950 @pytest.fixture 951 def arg1(): 952 pass 953 """ 954 ) 955 ) 956 p = b.join("test_module.py") 957 p.write("def test_func(arg1): pass") 958 result = testdir.runpytest(p, "--fixtures") 959 assert result.ret == 0 960 result.stdout.fnmatch_lines( 961 """ 962 *fixtures defined*conftest* 963 *arg1* 964 """ 965 ) 966 967 def test_show_fixtures_color_yes(self, testdir): 968 testdir.makepyfile("def test_this(): assert 1") 969 result = testdir.runpytest("--color=yes", "--fixtures") 970 assert "\x1b[32mtmpdir" in result.stdout.str() 971 972 def test_newstyle_with_request(self, testdir): 973 testdir.makepyfile( 974 """ 975 import pytest 976 @pytest.fixture() 977 def arg(request): 978 pass 979 def test_1(arg): 980 pass 981 """ 982 ) 983 reprec = testdir.inline_run() 984 reprec.assertoutcome(passed=1) 985 986 def test_setupcontext_no_param(self, testdir): 987 testdir.makepyfile( 988 """ 989 import pytest 990 @pytest.fixture(params=[1,2]) 991 def arg(request): 992 return request.param 993 994 @pytest.fixture(autouse=True) 995 def mysetup(request, arg): 996 assert not hasattr(request, "param") 997 def test_1(arg): 998 assert arg in (1,2) 999 """ 1000 ) 1001 reprec = testdir.inline_run() 1002 reprec.assertoutcome(passed=2) 1003 1004 1005class TestRequestMarking(object): 1006 1007 def test_applymarker(self, testdir): 1008 item1, item2 = testdir.getitems( 1009 """ 1010 import pytest 1011 1012 @pytest.fixture 1013 def something(request): 1014 pass 1015 class TestClass(object): 1016 def test_func1(self, something): 1017 pass 1018 def test_func2(self, something): 1019 pass 1020 """ 1021 ) 1022 req1 = fixtures.FixtureRequest(item1) 1023 assert "xfail" not in item1.keywords 1024 req1.applymarker(pytest.mark.xfail) 1025 assert "xfail" in item1.keywords 1026 assert "skipif" not in item1.keywords 1027 req1.applymarker(pytest.mark.skipif) 1028 assert "skipif" in item1.keywords 1029 pytest.raises(ValueError, "req1.applymarker(42)") 1030 1031 def test_accesskeywords(self, testdir): 1032 testdir.makepyfile( 1033 """ 1034 import pytest 1035 @pytest.fixture() 1036 def keywords(request): 1037 return request.keywords 1038 @pytest.mark.XYZ 1039 def test_function(keywords): 1040 assert keywords["XYZ"] 1041 assert "abc" not in keywords 1042 """ 1043 ) 1044 reprec = testdir.inline_run() 1045 reprec.assertoutcome(passed=1) 1046 1047 def test_accessmarker_dynamic(self, testdir): 1048 testdir.makeconftest( 1049 """ 1050 import pytest 1051 @pytest.fixture() 1052 def keywords(request): 1053 return request.keywords 1054 1055 @pytest.fixture(scope="class", autouse=True) 1056 def marking(request): 1057 request.applymarker(pytest.mark.XYZ("hello")) 1058 """ 1059 ) 1060 testdir.makepyfile( 1061 """ 1062 import pytest 1063 def test_fun1(keywords): 1064 assert keywords["XYZ"] is not None 1065 assert "abc" not in keywords 1066 def test_fun2(keywords): 1067 assert keywords["XYZ"] is not None 1068 assert "abc" not in keywords 1069 """ 1070 ) 1071 reprec = testdir.inline_run() 1072 reprec.assertoutcome(passed=2) 1073 1074 1075class TestRequestCachedSetup(object): 1076 1077 def test_request_cachedsetup_defaultmodule(self, testdir): 1078 reprec = testdir.inline_runsource( 1079 """ 1080 mysetup = ["hello",].pop 1081 1082 import pytest 1083 1084 @pytest.fixture 1085 def something(request): 1086 return request.cached_setup(mysetup, scope="module") 1087 1088 def test_func1(something): 1089 assert something == "hello" 1090 class TestClass(object): 1091 def test_func1a(self, something): 1092 assert something == "hello" 1093 """ 1094 ) 1095 reprec.assertoutcome(passed=2) 1096 1097 def test_request_cachedsetup_class(self, testdir): 1098 reprec = testdir.inline_runsource( 1099 """ 1100 mysetup = ["hello", "hello2", "hello3"].pop 1101 1102 import pytest 1103 @pytest.fixture 1104 def something(request): 1105 return request.cached_setup(mysetup, scope="class") 1106 def test_func1(something): 1107 assert something == "hello3" 1108 def test_func2(something): 1109 assert something == "hello2" 1110 class TestClass(object): 1111 def test_func1a(self, something): 1112 assert something == "hello" 1113 def test_func2b(self, something): 1114 assert something == "hello" 1115 """ 1116 ) 1117 reprec.assertoutcome(passed=4) 1118 1119 def test_request_cachedsetup_extrakey(self, testdir): 1120 item1 = testdir.getitem("def test_func(): pass") 1121 req1 = fixtures.FixtureRequest(item1) 1122 values = ["hello", "world"] 1123 1124 def setup(): 1125 return values.pop() 1126 1127 ret1 = req1.cached_setup(setup, extrakey=1) 1128 ret2 = req1.cached_setup(setup, extrakey=2) 1129 assert ret2 == "hello" 1130 assert ret1 == "world" 1131 ret1b = req1.cached_setup(setup, extrakey=1) 1132 ret2b = req1.cached_setup(setup, extrakey=2) 1133 assert ret1 == ret1b 1134 assert ret2 == ret2b 1135 1136 def test_request_cachedsetup_cache_deletion(self, testdir): 1137 item1 = testdir.getitem("def test_func(): pass") 1138 req1 = fixtures.FixtureRequest(item1) 1139 values = [] 1140 1141 def setup(): 1142 values.append("setup") 1143 1144 def teardown(val): 1145 values.append("teardown") 1146 1147 req1.cached_setup(setup, teardown, scope="function") 1148 assert values == ["setup"] 1149 # artificial call of finalizer 1150 setupstate = req1._pyfuncitem.session._setupstate 1151 setupstate._callfinalizers(item1) 1152 assert values == ["setup", "teardown"] 1153 req1.cached_setup(setup, teardown, scope="function") 1154 assert values == ["setup", "teardown", "setup"] 1155 setupstate._callfinalizers(item1) 1156 assert values == ["setup", "teardown", "setup", "teardown"] 1157 1158 def test_request_cached_setup_two_args(self, testdir): 1159 testdir.makepyfile( 1160 """ 1161 import pytest 1162 1163 @pytest.fixture 1164 def arg1(request): 1165 return request.cached_setup(lambda: 42) 1166 @pytest.fixture 1167 def arg2(request): 1168 return request.cached_setup(lambda: 17) 1169 def test_two_different_setups(arg1, arg2): 1170 assert arg1 != arg2 1171 """ 1172 ) 1173 result = testdir.runpytest("-v") 1174 result.stdout.fnmatch_lines(["*1 passed*"]) 1175 1176 def test_request_cached_setup_getfixturevalue(self, testdir): 1177 testdir.makepyfile( 1178 """ 1179 import pytest 1180 1181 @pytest.fixture 1182 def arg1(request): 1183 arg1 = request.getfixturevalue("arg2") 1184 return request.cached_setup(lambda: arg1 + 1) 1185 @pytest.fixture 1186 def arg2(request): 1187 return request.cached_setup(lambda: 10) 1188 def test_two_funcarg(arg1): 1189 assert arg1 == 11 1190 """ 1191 ) 1192 result = testdir.runpytest("-v") 1193 result.stdout.fnmatch_lines(["*1 passed*"]) 1194 1195 def test_request_cached_setup_functional(self, testdir): 1196 testdir.makepyfile( 1197 test_0=""" 1198 import pytest 1199 values = [] 1200 @pytest.fixture 1201 def something(request): 1202 val = request.cached_setup(fsetup, fteardown) 1203 return val 1204 def fsetup(mycache=[1]): 1205 values.append(mycache.pop()) 1206 return values 1207 def fteardown(something): 1208 values.remove(something[0]) 1209 values.append(2) 1210 def test_list_once(something): 1211 assert something == [1] 1212 def test_list_twice(something): 1213 assert something == [1] 1214 """ 1215 ) 1216 testdir.makepyfile( 1217 test_1=""" 1218 import test_0 # should have run already 1219 def test_check_test0_has_teardown_correct(): 1220 assert test_0.values == [2] 1221 """ 1222 ) 1223 result = testdir.runpytest("-v") 1224 result.stdout.fnmatch_lines(["*3 passed*"]) 1225 1226 def test_issue117_sessionscopeteardown(self, testdir): 1227 testdir.makepyfile( 1228 """ 1229 import pytest 1230 1231 @pytest.fixture 1232 def app(request): 1233 app = request.cached_setup( 1234 scope='session', 1235 setup=lambda: 0, 1236 teardown=lambda x: 3/x) 1237 return app 1238 def test_func(app): 1239 pass 1240 """ 1241 ) 1242 result = testdir.runpytest() 1243 assert result.ret != 0 1244 result.stdout.fnmatch_lines(["*3/x*", "*ZeroDivisionError*"]) 1245 1246 1247class TestFixtureUsages(object): 1248 1249 def test_noargfixturedec(self, testdir): 1250 testdir.makepyfile( 1251 """ 1252 import pytest 1253 @pytest.fixture 1254 def arg1(): 1255 return 1 1256 1257 def test_func(arg1): 1258 assert arg1 == 1 1259 """ 1260 ) 1261 reprec = testdir.inline_run() 1262 reprec.assertoutcome(passed=1) 1263 1264 def test_receives_funcargs(self, testdir): 1265 testdir.makepyfile( 1266 """ 1267 import pytest 1268 @pytest.fixture() 1269 def arg1(): 1270 return 1 1271 1272 @pytest.fixture() 1273 def arg2(arg1): 1274 return arg1 + 1 1275 1276 def test_add(arg2): 1277 assert arg2 == 2 1278 def test_all(arg1, arg2): 1279 assert arg1 == 1 1280 assert arg2 == 2 1281 """ 1282 ) 1283 reprec = testdir.inline_run() 1284 reprec.assertoutcome(passed=2) 1285 1286 def test_receives_funcargs_scope_mismatch(self, testdir): 1287 testdir.makepyfile( 1288 """ 1289 import pytest 1290 @pytest.fixture(scope="function") 1291 def arg1(): 1292 return 1 1293 1294 @pytest.fixture(scope="module") 1295 def arg2(arg1): 1296 return arg1 + 1 1297 1298 def test_add(arg2): 1299 assert arg2 == 2 1300 """ 1301 ) 1302 result = testdir.runpytest() 1303 result.stdout.fnmatch_lines( 1304 [ 1305 "*ScopeMismatch*involved factories*", 1306 "* def arg2*", 1307 "* def arg1*", 1308 "*1 error*", 1309 ] 1310 ) 1311 1312 def test_receives_funcargs_scope_mismatch_issue660(self, testdir): 1313 testdir.makepyfile( 1314 """ 1315 import pytest 1316 @pytest.fixture(scope="function") 1317 def arg1(): 1318 return 1 1319 1320 @pytest.fixture(scope="module") 1321 def arg2(arg1): 1322 return arg1 + 1 1323 1324 def test_add(arg1, arg2): 1325 assert arg2 == 2 1326 """ 1327 ) 1328 result = testdir.runpytest() 1329 result.stdout.fnmatch_lines( 1330 ["*ScopeMismatch*involved factories*", "* def arg2*", "*1 error*"] 1331 ) 1332 1333 def test_invalid_scope(self, testdir): 1334 testdir.makepyfile( 1335 """ 1336 import pytest 1337 @pytest.fixture(scope="functions") 1338 def badscope(): 1339 pass 1340 1341 def test_nothing(badscope): 1342 pass 1343 """ 1344 ) 1345 result = testdir.runpytest_inprocess() 1346 result.stdout.fnmatch_lines( 1347 ( 1348 "*ValueError: fixture badscope from test_invalid_scope.py has an unsupported" 1349 " scope value 'functions'" 1350 ) 1351 ) 1352 1353 def test_funcarg_parametrized_and_used_twice(self, testdir): 1354 testdir.makepyfile( 1355 """ 1356 import pytest 1357 values = [] 1358 @pytest.fixture(params=[1,2]) 1359 def arg1(request): 1360 values.append(1) 1361 return request.param 1362 1363 @pytest.fixture() 1364 def arg2(arg1): 1365 return arg1 + 1 1366 1367 def test_add(arg1, arg2): 1368 assert arg2 == arg1 + 1 1369 assert len(values) == arg1 1370 """ 1371 ) 1372 result = testdir.runpytest() 1373 result.stdout.fnmatch_lines(["*2 passed*"]) 1374 1375 def test_factory_uses_unknown_funcarg_as_dependency_error(self, testdir): 1376 testdir.makepyfile( 1377 """ 1378 import pytest 1379 1380 @pytest.fixture() 1381 def fail(missing): 1382 return 1383 1384 @pytest.fixture() 1385 def call_fail(fail): 1386 return 1387 1388 def test_missing(call_fail): 1389 pass 1390 """ 1391 ) 1392 result = testdir.runpytest() 1393 result.stdout.fnmatch_lines( 1394 """ 1395 *pytest.fixture()* 1396 *def call_fail(fail)* 1397 *pytest.fixture()* 1398 *def fail* 1399 *fixture*'missing'*not found* 1400 """ 1401 ) 1402 1403 def test_factory_setup_as_classes_fails(self, testdir): 1404 testdir.makepyfile( 1405 """ 1406 import pytest 1407 class arg1(object): 1408 def __init__(self, request): 1409 self.x = 1 1410 arg1 = pytest.fixture()(arg1) 1411 1412 """ 1413 ) 1414 reprec = testdir.inline_run() 1415 values = reprec.getfailedcollections() 1416 assert len(values) == 1 1417 1418 def test_request_can_be_overridden(self, testdir): 1419 testdir.makepyfile( 1420 """ 1421 import pytest 1422 @pytest.fixture() 1423 def request(request): 1424 request.a = 1 1425 return request 1426 def test_request(request): 1427 assert request.a == 1 1428 """ 1429 ) 1430 reprec = testdir.inline_run() 1431 reprec.assertoutcome(passed=1) 1432 1433 def test_usefixtures_marker(self, testdir): 1434 testdir.makepyfile( 1435 """ 1436 import pytest 1437 1438 values = [] 1439 1440 @pytest.fixture(scope="class") 1441 def myfix(request): 1442 request.cls.hello = "world" 1443 values.append(1) 1444 1445 class TestClass(object): 1446 def test_one(self): 1447 assert self.hello == "world" 1448 assert len(values) == 1 1449 def test_two(self): 1450 assert self.hello == "world" 1451 assert len(values) == 1 1452 pytest.mark.usefixtures("myfix")(TestClass) 1453 """ 1454 ) 1455 reprec = testdir.inline_run() 1456 reprec.assertoutcome(passed=2) 1457 1458 def test_usefixtures_ini(self, testdir): 1459 testdir.makeini( 1460 """ 1461 [pytest] 1462 usefixtures = myfix 1463 """ 1464 ) 1465 testdir.makeconftest( 1466 """ 1467 import pytest 1468 1469 @pytest.fixture(scope="class") 1470 def myfix(request): 1471 request.cls.hello = "world" 1472 1473 """ 1474 ) 1475 testdir.makepyfile( 1476 """ 1477 class TestClass(object): 1478 def test_one(self): 1479 assert self.hello == "world" 1480 def test_two(self): 1481 assert self.hello == "world" 1482 """ 1483 ) 1484 reprec = testdir.inline_run() 1485 reprec.assertoutcome(passed=2) 1486 1487 def test_usefixtures_seen_in_showmarkers(self, testdir): 1488 result = testdir.runpytest("--markers") 1489 result.stdout.fnmatch_lines( 1490 """ 1491 *usefixtures(fixturename1*mark tests*fixtures* 1492 """ 1493 ) 1494 1495 def test_request_instance_issue203(self, testdir): 1496 testdir.makepyfile( 1497 """ 1498 import pytest 1499 1500 class TestClass(object): 1501 @pytest.fixture 1502 def setup1(self, request): 1503 assert self == request.instance 1504 self.arg1 = 1 1505 def test_hello(self, setup1): 1506 assert self.arg1 == 1 1507 """ 1508 ) 1509 reprec = testdir.inline_run() 1510 reprec.assertoutcome(passed=1) 1511 1512 def test_fixture_parametrized_with_iterator(self, testdir): 1513 testdir.makepyfile( 1514 """ 1515 import pytest 1516 1517 values = [] 1518 def f(): 1519 yield 1 1520 yield 2 1521 dec = pytest.fixture(scope="module", params=f()) 1522 1523 @dec 1524 def arg(request): 1525 return request.param 1526 @dec 1527 def arg2(request): 1528 return request.param 1529 1530 def test_1(arg): 1531 values.append(arg) 1532 def test_2(arg2): 1533 values.append(arg2*10) 1534 """ 1535 ) 1536 reprec = testdir.inline_run("-v") 1537 reprec.assertoutcome(passed=4) 1538 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values 1539 assert values == [1, 2, 10, 20] 1540 1541 1542class TestFixtureManagerParseFactories(object): 1543 1544 @pytest.fixture 1545 def testdir(self, request): 1546 testdir = request.getfixturevalue("testdir") 1547 testdir.makeconftest( 1548 """ 1549 import pytest 1550 1551 @pytest.fixture 1552 def hello(request): 1553 return "conftest" 1554 1555 @pytest.fixture 1556 def fm(request): 1557 return request._fixturemanager 1558 1559 @pytest.fixture 1560 def item(request): 1561 return request._pyfuncitem 1562 """ 1563 ) 1564 return testdir 1565 1566 def test_parsefactories_evil_objects_issue214(self, testdir): 1567 testdir.makepyfile( 1568 """ 1569 class A(object): 1570 def __call__(self): 1571 pass 1572 def __getattr__(self, name): 1573 raise RuntimeError() 1574 a = A() 1575 def test_hello(): 1576 pass 1577 """ 1578 ) 1579 reprec = testdir.inline_run() 1580 reprec.assertoutcome(passed=1, failed=0) 1581 1582 def test_parsefactories_conftest(self, testdir): 1583 testdir.makepyfile( 1584 """ 1585 def test_hello(item, fm): 1586 for name in ("fm", "hello", "item"): 1587 faclist = fm.getfixturedefs(name, item.nodeid) 1588 assert len(faclist) == 1 1589 fac = faclist[0] 1590 assert fac.func.__name__ == name 1591 """ 1592 ) 1593 reprec = testdir.inline_run("-s") 1594 reprec.assertoutcome(passed=1) 1595 1596 def test_parsefactories_conftest_and_module_and_class(self, testdir): 1597 testdir.makepyfile( 1598 """ 1599 import pytest 1600 1601 @pytest.fixture 1602 def hello(request): 1603 return "module" 1604 class TestClass(object): 1605 @pytest.fixture 1606 def hello(self, request): 1607 return "class" 1608 def test_hello(self, item, fm): 1609 faclist = fm.getfixturedefs("hello", item.nodeid) 1610 print (faclist) 1611 assert len(faclist) == 3 1612 assert faclist[0].func(item._request) == "conftest" 1613 assert faclist[1].func(item._request) == "module" 1614 assert faclist[2].func(item._request) == "class" 1615 """ 1616 ) 1617 reprec = testdir.inline_run("-s") 1618 reprec.assertoutcome(passed=1) 1619 1620 def test_parsefactories_relative_node_ids(self, testdir): 1621 # example mostly taken from: 1622 # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html 1623 runner = testdir.mkdir("runner") 1624 package = testdir.mkdir("package") 1625 package.join("conftest.py").write( 1626 dedent( 1627 """\ 1628 import pytest 1629 @pytest.fixture 1630 def one(): 1631 return 1 1632 """ 1633 ) 1634 ) 1635 package.join("test_x.py").write( 1636 dedent( 1637 """\ 1638 def test_x(one): 1639 assert one == 1 1640 """ 1641 ) 1642 ) 1643 sub = package.mkdir("sub") 1644 sub.join("__init__.py").ensure() 1645 sub.join("conftest.py").write( 1646 dedent( 1647 """\ 1648 import pytest 1649 @pytest.fixture 1650 def one(): 1651 return 2 1652 """ 1653 ) 1654 ) 1655 sub.join("test_y.py").write( 1656 dedent( 1657 """\ 1658 def test_x(one): 1659 assert one == 2 1660 """ 1661 ) 1662 ) 1663 reprec = testdir.inline_run() 1664 reprec.assertoutcome(passed=2) 1665 with runner.as_cwd(): 1666 reprec = testdir.inline_run("..") 1667 reprec.assertoutcome(passed=2) 1668 1669 1670class TestAutouseDiscovery(object): 1671 1672 @pytest.fixture 1673 def testdir(self, testdir): 1674 testdir.makeconftest( 1675 """ 1676 import pytest 1677 @pytest.fixture(autouse=True) 1678 def perfunction(request, tmpdir): 1679 pass 1680 1681 @pytest.fixture() 1682 def arg1(tmpdir): 1683 pass 1684 @pytest.fixture(autouse=True) 1685 def perfunction2(arg1): 1686 pass 1687 1688 @pytest.fixture 1689 def fm(request): 1690 return request._fixturemanager 1691 1692 @pytest.fixture 1693 def item(request): 1694 return request._pyfuncitem 1695 """ 1696 ) 1697 return testdir 1698 1699 def test_parsefactories_conftest(self, testdir): 1700 testdir.makepyfile( 1701 """ 1702 from _pytest.pytester import get_public_names 1703 def test_check_setup(item, fm): 1704 autousenames = fm._getautousenames(item.nodeid) 1705 assert len(get_public_names(autousenames)) == 2 1706 assert "perfunction2" in autousenames 1707 assert "perfunction" in autousenames 1708 """ 1709 ) 1710 reprec = testdir.inline_run("-s") 1711 reprec.assertoutcome(passed=1) 1712 1713 def test_two_classes_separated_autouse(self, testdir): 1714 testdir.makepyfile( 1715 """ 1716 import pytest 1717 class TestA(object): 1718 values = [] 1719 @pytest.fixture(autouse=True) 1720 def setup1(self): 1721 self.values.append(1) 1722 def test_setup1(self): 1723 assert self.values == [1] 1724 class TestB(object): 1725 values = [] 1726 @pytest.fixture(autouse=True) 1727 def setup2(self): 1728 self.values.append(1) 1729 def test_setup2(self): 1730 assert self.values == [1] 1731 """ 1732 ) 1733 reprec = testdir.inline_run() 1734 reprec.assertoutcome(passed=2) 1735 1736 def test_setup_at_classlevel(self, testdir): 1737 testdir.makepyfile( 1738 """ 1739 import pytest 1740 class TestClass(object): 1741 @pytest.fixture(autouse=True) 1742 def permethod(self, request): 1743 request.instance.funcname = request.function.__name__ 1744 def test_method1(self): 1745 assert self.funcname == "test_method1" 1746 def test_method2(self): 1747 assert self.funcname == "test_method2" 1748 """ 1749 ) 1750 reprec = testdir.inline_run("-s") 1751 reprec.assertoutcome(passed=2) 1752 1753 @pytest.mark.xfail(reason="'enabled' feature not implemented") 1754 def test_setup_enabled_functionnode(self, testdir): 1755 testdir.makepyfile( 1756 """ 1757 import pytest 1758 1759 def enabled(parentnode, markers): 1760 return "needsdb" in markers 1761 1762 @pytest.fixture(params=[1,2]) 1763 def db(request): 1764 return request.param 1765 1766 @pytest.fixture(enabled=enabled, autouse=True) 1767 def createdb(db): 1768 pass 1769 1770 def test_func1(request): 1771 assert "db" not in request.fixturenames 1772 1773 @pytest.mark.needsdb 1774 def test_func2(request): 1775 assert "db" in request.fixturenames 1776 """ 1777 ) 1778 reprec = testdir.inline_run("-s") 1779 reprec.assertoutcome(passed=2) 1780 1781 def test_callables_nocode(self, testdir): 1782 """ 1783 an imported mock.call would break setup/factory discovery 1784 due to it being callable and __code__ not being a code object 1785 """ 1786 testdir.makepyfile( 1787 """ 1788 class _call(tuple): 1789 def __call__(self, *k, **kw): 1790 pass 1791 def __getattr__(self, k): 1792 return self 1793 1794 call = _call() 1795 """ 1796 ) 1797 reprec = testdir.inline_run("-s") 1798 reprec.assertoutcome(failed=0, passed=0) 1799 1800 def test_autouse_in_conftests(self, testdir): 1801 a = testdir.mkdir("a") 1802 b = testdir.mkdir("a1") 1803 conftest = testdir.makeconftest( 1804 """ 1805 import pytest 1806 @pytest.fixture(autouse=True) 1807 def hello(): 1808 xxx 1809 """ 1810 ) 1811 conftest.move(a.join(conftest.basename)) 1812 a.join("test_something.py").write("def test_func(): pass") 1813 b.join("test_otherthing.py").write("def test_func(): pass") 1814 result = testdir.runpytest() 1815 result.stdout.fnmatch_lines( 1816 """ 1817 *1 passed*1 error* 1818 """ 1819 ) 1820 1821 def test_autouse_in_module_and_two_classes(self, testdir): 1822 testdir.makepyfile( 1823 """ 1824 import pytest 1825 values = [] 1826 @pytest.fixture(autouse=True) 1827 def append1(): 1828 values.append("module") 1829 def test_x(): 1830 assert values == ["module"] 1831 1832 class TestA(object): 1833 @pytest.fixture(autouse=True) 1834 def append2(self): 1835 values.append("A") 1836 def test_hello(self): 1837 assert values == ["module", "module", "A"], values 1838 class TestA2(object): 1839 def test_world(self): 1840 assert values == ["module", "module", "A", "module"], values 1841 """ 1842 ) 1843 reprec = testdir.inline_run() 1844 reprec.assertoutcome(passed=3) 1845 1846 1847class TestAutouseManagement(object): 1848 1849 def test_autouse_conftest_mid_directory(self, testdir): 1850 pkgdir = testdir.mkpydir("xyz123") 1851 pkgdir.join("conftest.py").write( 1852 _pytest._code.Source( 1853 """ 1854 import pytest 1855 @pytest.fixture(autouse=True) 1856 def app(): 1857 import sys 1858 sys._myapp = "hello" 1859 """ 1860 ) 1861 ) 1862 t = pkgdir.ensure("tests", "test_app.py") 1863 t.write( 1864 _pytest._code.Source( 1865 """ 1866 import sys 1867 def test_app(): 1868 assert sys._myapp == "hello" 1869 """ 1870 ) 1871 ) 1872 reprec = testdir.inline_run("-s") 1873 reprec.assertoutcome(passed=1) 1874 1875 def test_autouse_honored_for_yield(self, testdir): 1876 testdir.makepyfile( 1877 """ 1878 import pytest 1879 @pytest.fixture(autouse=True) 1880 def tst(): 1881 global x 1882 x = 3 1883 def test_gen(): 1884 def f(hello): 1885 assert x == abs(hello) 1886 yield f, 3 1887 yield f, -3 1888 """ 1889 ) 1890 reprec = testdir.inline_run() 1891 reprec.assertoutcome(passed=2) 1892 1893 def test_funcarg_and_setup(self, testdir): 1894 testdir.makepyfile( 1895 """ 1896 import pytest 1897 values = [] 1898 @pytest.fixture(scope="module") 1899 def arg(): 1900 values.append(1) 1901 return 0 1902 @pytest.fixture(scope="module", autouse=True) 1903 def something(arg): 1904 values.append(2) 1905 1906 def test_hello(arg): 1907 assert len(values) == 2 1908 assert values == [1,2] 1909 assert arg == 0 1910 1911 def test_hello2(arg): 1912 assert len(values) == 2 1913 assert values == [1,2] 1914 assert arg == 0 1915 """ 1916 ) 1917 reprec = testdir.inline_run() 1918 reprec.assertoutcome(passed=2) 1919 1920 def test_uses_parametrized_resource(self, testdir): 1921 testdir.makepyfile( 1922 """ 1923 import pytest 1924 values = [] 1925 @pytest.fixture(params=[1,2]) 1926 def arg(request): 1927 return request.param 1928 1929 @pytest.fixture(autouse=True) 1930 def something(arg): 1931 values.append(arg) 1932 1933 def test_hello(): 1934 if len(values) == 1: 1935 assert values == [1] 1936 elif len(values) == 2: 1937 assert values == [1, 2] 1938 else: 1939 0/0 1940 1941 """ 1942 ) 1943 reprec = testdir.inline_run("-s") 1944 reprec.assertoutcome(passed=2) 1945 1946 def test_session_parametrized_function(self, testdir): 1947 testdir.makepyfile( 1948 """ 1949 import pytest 1950 1951 values = [] 1952 1953 @pytest.fixture(scope="session", params=[1,2]) 1954 def arg(request): 1955 return request.param 1956 1957 @pytest.fixture(scope="function", autouse=True) 1958 def append(request, arg): 1959 if request.function.__name__ == "test_some": 1960 values.append(arg) 1961 1962 def test_some(): 1963 pass 1964 1965 def test_result(arg): 1966 assert len(values) == arg 1967 assert values[:arg] == [1,2][:arg] 1968 """ 1969 ) 1970 reprec = testdir.inline_run("-v", "-s") 1971 reprec.assertoutcome(passed=4) 1972 1973 def test_class_function_parametrization_finalization(self, testdir): 1974 p = testdir.makeconftest( 1975 """ 1976 import pytest 1977 import pprint 1978 1979 values = [] 1980 1981 @pytest.fixture(scope="function", params=[1,2]) 1982 def farg(request): 1983 return request.param 1984 1985 @pytest.fixture(scope="class", params=list("ab")) 1986 def carg(request): 1987 return request.param 1988 1989 @pytest.fixture(scope="function", autouse=True) 1990 def append(request, farg, carg): 1991 def fin(): 1992 values.append("fin_%s%s" % (carg, farg)) 1993 request.addfinalizer(fin) 1994 """ 1995 ) 1996 testdir.makepyfile( 1997 """ 1998 import pytest 1999 2000 class TestClass(object): 2001 def test_1(self): 2002 pass 2003 class TestClass2(object): 2004 def test_2(self): 2005 pass 2006 """ 2007 ) 2008 confcut = "--confcutdir={}".format(testdir.tmpdir) 2009 reprec = testdir.inline_run("-v", "-s", confcut) 2010 reprec.assertoutcome(passed=8) 2011 config = reprec.getcalls("pytest_unconfigure")[0].config 2012 values = config.pluginmanager._getconftestmodules(p)[0].values 2013 assert values == ["fin_a1", "fin_a2", "fin_b1", "fin_b2"] * 2 2014 2015 def test_scope_ordering(self, testdir): 2016 testdir.makepyfile( 2017 """ 2018 import pytest 2019 values = [] 2020 @pytest.fixture(scope="function", autouse=True) 2021 def fappend2(): 2022 values.append(2) 2023 @pytest.fixture(scope="class", autouse=True) 2024 def classappend3(): 2025 values.append(3) 2026 @pytest.fixture(scope="module", autouse=True) 2027 def mappend(): 2028 values.append(1) 2029 2030 class TestHallo(object): 2031 def test_method(self): 2032 assert values == [1,3,2] 2033 """ 2034 ) 2035 reprec = testdir.inline_run() 2036 reprec.assertoutcome(passed=1) 2037 2038 def test_parametrization_setup_teardown_ordering(self, testdir): 2039 testdir.makepyfile( 2040 """ 2041 import pytest 2042 values = [] 2043 def pytest_generate_tests(metafunc): 2044 if metafunc.cls is None: 2045 assert metafunc.function is test_finish 2046 if metafunc.cls is not None: 2047 metafunc.parametrize("item", [1,2], scope="class") 2048 class TestClass(object): 2049 @pytest.fixture(scope="class", autouse=True) 2050 def addteardown(self, item, request): 2051 values.append("setup-%d" % item) 2052 request.addfinalizer(lambda: values.append("teardown-%d" % item)) 2053 def test_step1(self, item): 2054 values.append("step1-%d" % item) 2055 def test_step2(self, item): 2056 values.append("step2-%d" % item) 2057 2058 def test_finish(): 2059 print (values) 2060 assert values == ["setup-1", "step1-1", "step2-1", "teardown-1", 2061 "setup-2", "step1-2", "step2-2", "teardown-2",] 2062 """ 2063 ) 2064 reprec = testdir.inline_run("-s") 2065 reprec.assertoutcome(passed=5) 2066 2067 def test_ordering_autouse_before_explicit(self, testdir): 2068 testdir.makepyfile( 2069 """ 2070 import pytest 2071 2072 values = [] 2073 @pytest.fixture(autouse=True) 2074 def fix1(): 2075 values.append(1) 2076 @pytest.fixture() 2077 def arg1(): 2078 values.append(2) 2079 def test_hello(arg1): 2080 assert values == [1,2] 2081 """ 2082 ) 2083 reprec = testdir.inline_run() 2084 reprec.assertoutcome(passed=1) 2085 2086 @pytest.mark.issue226 2087 @pytest.mark.parametrize("param1", ["", "params=[1]"], ids=["p00", "p01"]) 2088 @pytest.mark.parametrize("param2", ["", "params=[1]"], ids=["p10", "p11"]) 2089 def test_ordering_dependencies_torndown_first(self, testdir, param1, param2): 2090 testdir.makepyfile( 2091 """ 2092 import pytest 2093 values = [] 2094 @pytest.fixture(%(param1)s) 2095 def arg1(request): 2096 request.addfinalizer(lambda: values.append("fin1")) 2097 values.append("new1") 2098 @pytest.fixture(%(param2)s) 2099 def arg2(request, arg1): 2100 request.addfinalizer(lambda: values.append("fin2")) 2101 values.append("new2") 2102 2103 def test_arg(arg2): 2104 pass 2105 def test_check(): 2106 assert values == ["new1", "new2", "fin2", "fin1"] 2107 """ 2108 % locals() 2109 ) 2110 reprec = testdir.inline_run("-s") 2111 reprec.assertoutcome(passed=2) 2112 2113 2114class TestFixtureMarker(object): 2115 2116 def test_parametrize(self, testdir): 2117 testdir.makepyfile( 2118 """ 2119 import pytest 2120 @pytest.fixture(params=["a", "b", "c"]) 2121 def arg(request): 2122 return request.param 2123 values = [] 2124 def test_param(arg): 2125 values.append(arg) 2126 def test_result(): 2127 assert values == list("abc") 2128 """ 2129 ) 2130 reprec = testdir.inline_run() 2131 reprec.assertoutcome(passed=4) 2132 2133 def test_multiple_parametrization_issue_736(self, testdir): 2134 testdir.makepyfile( 2135 """ 2136 import pytest 2137 2138 @pytest.fixture(params=[1,2,3]) 2139 def foo(request): 2140 return request.param 2141 2142 @pytest.mark.parametrize('foobar', [4,5,6]) 2143 def test_issue(foo, foobar): 2144 assert foo in [1,2,3] 2145 assert foobar in [4,5,6] 2146 """ 2147 ) 2148 reprec = testdir.inline_run() 2149 reprec.assertoutcome(passed=9) 2150 2151 @pytest.mark.parametrize( 2152 "param_args", 2153 ["'fixt, val'", "'fixt,val'", "['fixt', 'val']", "('fixt', 'val')"], 2154 ) 2155 def test_override_parametrized_fixture_issue_979(self, testdir, param_args): 2156 """Make sure a parametrized argument can override a parametrized fixture. 2157 2158 This was a regression introduced in the fix for #736. 2159 """ 2160 testdir.makepyfile( 2161 """ 2162 import pytest 2163 2164 @pytest.fixture(params=[1, 2]) 2165 def fixt(request): 2166 return request.param 2167 2168 @pytest.mark.parametrize(%s, [(3, 'x'), (4, 'x')]) 2169 def test_foo(fixt, val): 2170 pass 2171 """ 2172 % param_args 2173 ) 2174 reprec = testdir.inline_run() 2175 reprec.assertoutcome(passed=2) 2176 2177 def test_scope_session(self, testdir): 2178 testdir.makepyfile( 2179 """ 2180 import pytest 2181 values = [] 2182 @pytest.fixture(scope="module") 2183 def arg(): 2184 values.append(1) 2185 return 1 2186 2187 def test_1(arg): 2188 assert arg == 1 2189 def test_2(arg): 2190 assert arg == 1 2191 assert len(values) == 1 2192 class TestClass(object): 2193 def test3(self, arg): 2194 assert arg == 1 2195 assert len(values) == 1 2196 """ 2197 ) 2198 reprec = testdir.inline_run() 2199 reprec.assertoutcome(passed=3) 2200 2201 def test_scope_session_exc(self, testdir): 2202 testdir.makepyfile( 2203 """ 2204 import pytest 2205 values = [] 2206 @pytest.fixture(scope="session") 2207 def fix(): 2208 values.append(1) 2209 pytest.skip('skipping') 2210 2211 def test_1(fix): 2212 pass 2213 def test_2(fix): 2214 pass 2215 def test_last(): 2216 assert values == [1] 2217 """ 2218 ) 2219 reprec = testdir.inline_run() 2220 reprec.assertoutcome(skipped=2, passed=1) 2221 2222 def test_scope_session_exc_two_fix(self, testdir): 2223 testdir.makepyfile( 2224 """ 2225 import pytest 2226 values = [] 2227 m = [] 2228 @pytest.fixture(scope="session") 2229 def a(): 2230 values.append(1) 2231 pytest.skip('skipping') 2232 @pytest.fixture(scope="session") 2233 def b(a): 2234 m.append(1) 2235 2236 def test_1(b): 2237 pass 2238 def test_2(b): 2239 pass 2240 def test_last(): 2241 assert values == [1] 2242 assert m == [] 2243 """ 2244 ) 2245 reprec = testdir.inline_run() 2246 reprec.assertoutcome(skipped=2, passed=1) 2247 2248 def test_scope_exc(self, testdir): 2249 testdir.makepyfile( 2250 test_foo=""" 2251 def test_foo(fix): 2252 pass 2253 """, 2254 test_bar=""" 2255 def test_bar(fix): 2256 pass 2257 """, 2258 conftest=""" 2259 import pytest 2260 reqs = [] 2261 @pytest.fixture(scope="session") 2262 def fix(request): 2263 reqs.append(1) 2264 pytest.skip() 2265 @pytest.fixture 2266 def req_list(): 2267 return reqs 2268 """, 2269 test_real=""" 2270 def test_last(req_list): 2271 assert req_list == [1] 2272 """, 2273 ) 2274 reprec = testdir.inline_run() 2275 reprec.assertoutcome(skipped=2, passed=1) 2276 2277 def test_scope_module_uses_session(self, testdir): 2278 testdir.makepyfile( 2279 """ 2280 import pytest 2281 values = [] 2282 @pytest.fixture(scope="module") 2283 def arg(): 2284 values.append(1) 2285 return 1 2286 2287 def test_1(arg): 2288 assert arg == 1 2289 def test_2(arg): 2290 assert arg == 1 2291 assert len(values) == 1 2292 class TestClass(object): 2293 def test3(self, arg): 2294 assert arg == 1 2295 assert len(values) == 1 2296 """ 2297 ) 2298 reprec = testdir.inline_run() 2299 reprec.assertoutcome(passed=3) 2300 2301 def test_scope_module_and_finalizer(self, testdir): 2302 testdir.makeconftest( 2303 """ 2304 import pytest 2305 finalized_list = [] 2306 created_list = [] 2307 @pytest.fixture(scope="module") 2308 def arg(request): 2309 created_list.append(1) 2310 assert request.scope == "module" 2311 request.addfinalizer(lambda: finalized_list.append(1)) 2312 @pytest.fixture 2313 def created(request): 2314 return len(created_list) 2315 @pytest.fixture 2316 def finalized(request): 2317 return len(finalized_list) 2318 """ 2319 ) 2320 testdir.makepyfile( 2321 test_mod1=""" 2322 def test_1(arg, created, finalized): 2323 assert created == 1 2324 assert finalized == 0 2325 def test_2(arg, created, finalized): 2326 assert created == 1 2327 assert finalized == 0""", 2328 test_mod2=""" 2329 def test_3(arg, created, finalized): 2330 assert created == 2 2331 assert finalized == 1""", 2332 test_mode3=""" 2333 def test_4(arg, created, finalized): 2334 assert created == 3 2335 assert finalized == 2 2336 """, 2337 ) 2338 reprec = testdir.inline_run() 2339 reprec.assertoutcome(passed=4) 2340 2341 @pytest.mark.parametrize( 2342 "method", 2343 [ 2344 'request.getfixturevalue("arg")', 2345 'request.cached_setup(lambda: None, scope="function")', 2346 ], 2347 ids=["getfixturevalue", "cached_setup"], 2348 ) 2349 def test_scope_mismatch_various(self, testdir, method): 2350 testdir.makeconftest( 2351 """ 2352 import pytest 2353 finalized = [] 2354 created = [] 2355 @pytest.fixture(scope="function") 2356 def arg(request): 2357 pass 2358 """ 2359 ) 2360 testdir.makepyfile( 2361 test_mod1=""" 2362 import pytest 2363 @pytest.fixture(scope="session") 2364 def arg(request): 2365 %s 2366 def test_1(arg): 2367 pass 2368 """ 2369 % method 2370 ) 2371 result = testdir.runpytest() 2372 assert result.ret != 0 2373 result.stdout.fnmatch_lines( 2374 ["*ScopeMismatch*You tried*function*session*request*"] 2375 ) 2376 2377 def test_register_only_with_mark(self, testdir): 2378 testdir.makeconftest( 2379 """ 2380 import pytest 2381 @pytest.fixture() 2382 def arg(): 2383 return 1 2384 """ 2385 ) 2386 testdir.makepyfile( 2387 test_mod1=""" 2388 import pytest 2389 @pytest.fixture() 2390 def arg(arg): 2391 return arg + 1 2392 def test_1(arg): 2393 assert arg == 2 2394 """ 2395 ) 2396 reprec = testdir.inline_run() 2397 reprec.assertoutcome(passed=1) 2398 2399 def test_parametrize_and_scope(self, testdir): 2400 testdir.makepyfile( 2401 """ 2402 import pytest 2403 @pytest.fixture(scope="module", params=["a", "b", "c"]) 2404 def arg(request): 2405 return request.param 2406 values = [] 2407 def test_param(arg): 2408 values.append(arg) 2409 """ 2410 ) 2411 reprec = testdir.inline_run("-v") 2412 reprec.assertoutcome(passed=3) 2413 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values 2414 assert len(values) == 3 2415 assert "a" in values 2416 assert "b" in values 2417 assert "c" in values 2418 2419 def test_scope_mismatch(self, testdir): 2420 testdir.makeconftest( 2421 """ 2422 import pytest 2423 @pytest.fixture(scope="function") 2424 def arg(request): 2425 pass 2426 """ 2427 ) 2428 testdir.makepyfile( 2429 """ 2430 import pytest 2431 @pytest.fixture(scope="session") 2432 def arg(arg): 2433 pass 2434 def test_mismatch(arg): 2435 pass 2436 """ 2437 ) 2438 result = testdir.runpytest() 2439 result.stdout.fnmatch_lines(["*ScopeMismatch*", "*1 error*"]) 2440 2441 def test_parametrize_separated_order(self, testdir): 2442 testdir.makepyfile( 2443 """ 2444 import pytest 2445 2446 @pytest.fixture(scope="module", params=[1, 2]) 2447 def arg(request): 2448 return request.param 2449 2450 values = [] 2451 def test_1(arg): 2452 values.append(arg) 2453 def test_2(arg): 2454 values.append(arg) 2455 """ 2456 ) 2457 reprec = testdir.inline_run("-v") 2458 reprec.assertoutcome(passed=4) 2459 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values 2460 assert values == [1, 1, 2, 2] 2461 2462 def test_module_parametrized_ordering(self, testdir): 2463 testdir.makeini( 2464 """ 2465 [pytest] 2466 console_output_style=classic 2467 """ 2468 ) 2469 testdir.makeconftest( 2470 """ 2471 import pytest 2472 2473 @pytest.fixture(scope="session", params="s1 s2".split()) 2474 def sarg(): 2475 pass 2476 @pytest.fixture(scope="module", params="m1 m2".split()) 2477 def marg(): 2478 pass 2479 """ 2480 ) 2481 testdir.makepyfile( 2482 test_mod1=""" 2483 def test_func(sarg): 2484 pass 2485 def test_func1(marg): 2486 pass 2487 """, 2488 test_mod2=""" 2489 def test_func2(sarg): 2490 pass 2491 def test_func3(sarg, marg): 2492 pass 2493 def test_func3b(sarg, marg): 2494 pass 2495 def test_func4(marg): 2496 pass 2497 """, 2498 ) 2499 result = testdir.runpytest("-v") 2500 result.stdout.fnmatch_lines( 2501 """ 2502 test_mod1.py::test_func[s1] PASSED 2503 test_mod2.py::test_func2[s1] PASSED 2504 test_mod2.py::test_func3[s1-m1] PASSED 2505 test_mod2.py::test_func3b[s1-m1] PASSED 2506 test_mod2.py::test_func3[s1-m2] PASSED 2507 test_mod2.py::test_func3b[s1-m2] PASSED 2508 test_mod1.py::test_func[s2] PASSED 2509 test_mod2.py::test_func2[s2] PASSED 2510 test_mod2.py::test_func3[s2-m1] PASSED 2511 test_mod2.py::test_func3b[s2-m1] PASSED 2512 test_mod2.py::test_func4[m1] PASSED 2513 test_mod2.py::test_func3[s2-m2] PASSED 2514 test_mod2.py::test_func3b[s2-m2] PASSED 2515 test_mod2.py::test_func4[m2] PASSED 2516 test_mod1.py::test_func1[m1] PASSED 2517 test_mod1.py::test_func1[m2] PASSED 2518 """ 2519 ) 2520 2521 def test_dynamic_parametrized_ordering(self, testdir): 2522 testdir.makeini( 2523 """ 2524 [pytest] 2525 console_output_style=classic 2526 """ 2527 ) 2528 testdir.makeconftest( 2529 """ 2530 import pytest 2531 2532 def pytest_configure(config): 2533 class DynamicFixturePlugin(object): 2534 @pytest.fixture(scope='session', params=['flavor1', 'flavor2']) 2535 def flavor(self, request): 2536 return request.param 2537 config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture') 2538 2539 @pytest.fixture(scope='session', params=['vxlan', 'vlan']) 2540 def encap(request): 2541 return request.param 2542 2543 @pytest.fixture(scope='session', autouse='True') 2544 def reprovision(request, flavor, encap): 2545 pass 2546 """ 2547 ) 2548 testdir.makepyfile( 2549 """ 2550 def test(reprovision): 2551 pass 2552 def test2(reprovision): 2553 pass 2554 """ 2555 ) 2556 result = testdir.runpytest("-v") 2557 result.stdout.fnmatch_lines( 2558 """ 2559 test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED 2560 test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED 2561 test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED 2562 test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED 2563 test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED 2564 test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED 2565 test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED 2566 test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED 2567 """ 2568 ) 2569 2570 def test_class_ordering(self, testdir): 2571 testdir.makeini( 2572 """ 2573 [pytest] 2574 console_output_style=classic 2575 """ 2576 ) 2577 testdir.makeconftest( 2578 """ 2579 import pytest 2580 2581 values = [] 2582 2583 @pytest.fixture(scope="function", params=[1,2]) 2584 def farg(request): 2585 return request.param 2586 2587 @pytest.fixture(scope="class", params=list("ab")) 2588 def carg(request): 2589 return request.param 2590 2591 @pytest.fixture(scope="function", autouse=True) 2592 def append(request, farg, carg): 2593 def fin(): 2594 values.append("fin_%s%s" % (carg, farg)) 2595 request.addfinalizer(fin) 2596 """ 2597 ) 2598 testdir.makepyfile( 2599 """ 2600 import pytest 2601 2602 class TestClass2(object): 2603 def test_1(self): 2604 pass 2605 def test_2(self): 2606 pass 2607 class TestClass(object): 2608 def test_3(self): 2609 pass 2610 """ 2611 ) 2612 result = testdir.runpytest("-vs") 2613 result.stdout.re_match_lines( 2614 r""" 2615 test_class_ordering.py::TestClass2::test_1\[a-1\] PASSED 2616 test_class_ordering.py::TestClass2::test_1\[a-2\] PASSED 2617 test_class_ordering.py::TestClass2::test_2\[a-1\] PASSED 2618 test_class_ordering.py::TestClass2::test_2\[a-2\] PASSED 2619 test_class_ordering.py::TestClass2::test_1\[b-1\] PASSED 2620 test_class_ordering.py::TestClass2::test_1\[b-2\] PASSED 2621 test_class_ordering.py::TestClass2::test_2\[b-1\] PASSED 2622 test_class_ordering.py::TestClass2::test_2\[b-2\] PASSED 2623 test_class_ordering.py::TestClass::test_3\[a-1\] PASSED 2624 test_class_ordering.py::TestClass::test_3\[a-2\] PASSED 2625 test_class_ordering.py::TestClass::test_3\[b-1\] PASSED 2626 test_class_ordering.py::TestClass::test_3\[b-2\] PASSED 2627 """ 2628 ) 2629 2630 def test_parametrize_separated_order_higher_scope_first(self, testdir): 2631 testdir.makepyfile( 2632 """ 2633 import pytest 2634 2635 @pytest.fixture(scope="function", params=[1, 2]) 2636 def arg(request): 2637 param = request.param 2638 request.addfinalizer(lambda: values.append("fin:%s" % param)) 2639 values.append("create:%s" % param) 2640 return request.param 2641 2642 @pytest.fixture(scope="module", params=["mod1", "mod2"]) 2643 def modarg(request): 2644 param = request.param 2645 request.addfinalizer(lambda: values.append("fin:%s" % param)) 2646 values.append("create:%s" % param) 2647 return request.param 2648 2649 values = [] 2650 def test_1(arg): 2651 values.append("test1") 2652 def test_2(modarg): 2653 values.append("test2") 2654 def test_3(arg, modarg): 2655 values.append("test3") 2656 def test_4(modarg, arg): 2657 values.append("test4") 2658 """ 2659 ) 2660 reprec = testdir.inline_run("-v") 2661 reprec.assertoutcome(passed=12) 2662 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values 2663 expected = [ 2664 "create:1", 2665 "test1", 2666 "fin:1", 2667 "create:2", 2668 "test1", 2669 "fin:2", 2670 "create:mod1", 2671 "test2", 2672 "create:1", 2673 "test3", 2674 "fin:1", 2675 "create:2", 2676 "test3", 2677 "fin:2", 2678 "create:1", 2679 "test4", 2680 "fin:1", 2681 "create:2", 2682 "test4", 2683 "fin:2", 2684 "fin:mod1", 2685 "create:mod2", 2686 "test2", 2687 "create:1", 2688 "test3", 2689 "fin:1", 2690 "create:2", 2691 "test3", 2692 "fin:2", 2693 "create:1", 2694 "test4", 2695 "fin:1", 2696 "create:2", 2697 "test4", 2698 "fin:2", 2699 "fin:mod2", 2700 ] 2701 import pprint 2702 2703 pprint.pprint(list(zip(values, expected))) 2704 assert values == expected 2705 2706 def test_parametrized_fixture_teardown_order(self, testdir): 2707 testdir.makepyfile( 2708 """ 2709 import pytest 2710 @pytest.fixture(params=[1,2], scope="class") 2711 def param1(request): 2712 return request.param 2713 2714 values = [] 2715 2716 class TestClass(object): 2717 @classmethod 2718 @pytest.fixture(scope="class", autouse=True) 2719 def setup1(self, request, param1): 2720 values.append(1) 2721 request.addfinalizer(self.teardown1) 2722 @classmethod 2723 def teardown1(self): 2724 assert values.pop() == 1 2725 @pytest.fixture(scope="class", autouse=True) 2726 def setup2(self, request, param1): 2727 values.append(2) 2728 request.addfinalizer(self.teardown2) 2729 @classmethod 2730 def teardown2(self): 2731 assert values.pop() == 2 2732 def test(self): 2733 pass 2734 2735 def test_finish(): 2736 assert not values 2737 """ 2738 ) 2739 result = testdir.runpytest("-v") 2740 result.stdout.fnmatch_lines( 2741 """ 2742 *3 passed* 2743 """ 2744 ) 2745 assert "error" not in result.stdout.str() 2746 2747 def test_fixture_finalizer(self, testdir): 2748 testdir.makeconftest( 2749 """ 2750 import pytest 2751 import sys 2752 2753 @pytest.fixture 2754 def browser(request): 2755 2756 def finalize(): 2757 sys.stdout.write('Finalized') 2758 request.addfinalizer(finalize) 2759 return {} 2760 """ 2761 ) 2762 b = testdir.mkdir("subdir") 2763 b.join("test_overridden_fixture_finalizer.py").write( 2764 dedent( 2765 """ 2766 import pytest 2767 @pytest.fixture 2768 def browser(browser): 2769 browser['visited'] = True 2770 return browser 2771 2772 def test_browser(browser): 2773 assert browser['visited'] is True 2774 """ 2775 ) 2776 ) 2777 reprec = testdir.runpytest("-s") 2778 for test in ["test_browser"]: 2779 reprec.stdout.fnmatch_lines("*Finalized*") 2780 2781 def test_class_scope_with_normal_tests(self, testdir): 2782 testpath = testdir.makepyfile( 2783 """ 2784 import pytest 2785 2786 class Box(object): 2787 value = 0 2788 2789 @pytest.fixture(scope='class') 2790 def a(request): 2791 Box.value += 1 2792 return Box.value 2793 2794 def test_a(a): 2795 assert a == 1 2796 2797 class Test1(object): 2798 def test_b(self, a): 2799 assert a == 2 2800 2801 class Test2(object): 2802 def test_c(self, a): 2803 assert a == 3""" 2804 ) 2805 reprec = testdir.inline_run(testpath) 2806 for test in ["test_a", "test_b", "test_c"]: 2807 assert reprec.matchreport(test).passed 2808 2809 def test_request_is_clean(self, testdir): 2810 testdir.makepyfile( 2811 """ 2812 import pytest 2813 values = [] 2814 @pytest.fixture(params=[1, 2]) 2815 def fix(request): 2816 request.addfinalizer(lambda: values.append(request.param)) 2817 def test_fix(fix): 2818 pass 2819 """ 2820 ) 2821 reprec = testdir.inline_run("-s") 2822 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values 2823 assert values == [1, 2] 2824 2825 def test_parametrize_separated_lifecycle(self, testdir): 2826 testdir.makepyfile( 2827 """ 2828 import pytest 2829 2830 values = [] 2831 @pytest.fixture(scope="module", params=[1, 2]) 2832 def arg(request): 2833 x = request.param 2834 request.addfinalizer(lambda: values.append("fin%s" % x)) 2835 return request.param 2836 def test_1(arg): 2837 values.append(arg) 2838 def test_2(arg): 2839 values.append(arg) 2840 """ 2841 ) 2842 reprec = testdir.inline_run("-vs") 2843 reprec.assertoutcome(passed=4) 2844 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values 2845 import pprint 2846 2847 pprint.pprint(values) 2848 # assert len(values) == 6 2849 assert values[0] == values[1] == 1 2850 assert values[2] == "fin1" 2851 assert values[3] == values[4] == 2 2852 assert values[5] == "fin2" 2853 2854 def test_parametrize_function_scoped_finalizers_called(self, testdir): 2855 testdir.makepyfile( 2856 """ 2857 import pytest 2858 2859 @pytest.fixture(scope="function", params=[1, 2]) 2860 def arg(request): 2861 x = request.param 2862 request.addfinalizer(lambda: values.append("fin%s" % x)) 2863 return request.param 2864 2865 values = [] 2866 def test_1(arg): 2867 values.append(arg) 2868 def test_2(arg): 2869 values.append(arg) 2870 def test_3(): 2871 assert len(values) == 8 2872 assert values == [1, "fin1", 2, "fin2", 1, "fin1", 2, "fin2"] 2873 """ 2874 ) 2875 reprec = testdir.inline_run("-v") 2876 reprec.assertoutcome(passed=5) 2877 2878 @pytest.mark.issue246 2879 @pytest.mark.parametrize("scope", ["session", "function", "module"]) 2880 def test_finalizer_order_on_parametrization(self, scope, testdir): 2881 testdir.makepyfile( 2882 """ 2883 import pytest 2884 values = [] 2885 2886 @pytest.fixture(scope=%(scope)r, params=["1"]) 2887 def fix1(request): 2888 return request.param 2889 2890 @pytest.fixture(scope=%(scope)r) 2891 def fix2(request, base): 2892 def cleanup_fix2(): 2893 assert not values, "base should not have been finalized" 2894 request.addfinalizer(cleanup_fix2) 2895 2896 @pytest.fixture(scope=%(scope)r) 2897 def base(request, fix1): 2898 def cleanup_base(): 2899 values.append("fin_base") 2900 print ("finalizing base") 2901 request.addfinalizer(cleanup_base) 2902 2903 def test_begin(): 2904 pass 2905 def test_baz(base, fix2): 2906 pass 2907 def test_other(): 2908 pass 2909 """ 2910 % {"scope": scope} 2911 ) 2912 reprec = testdir.inline_run("-lvs") 2913 reprec.assertoutcome(passed=3) 2914 2915 @pytest.mark.issue396 2916 def test_class_scope_parametrization_ordering(self, testdir): 2917 testdir.makepyfile( 2918 """ 2919 import pytest 2920 values = [] 2921 @pytest.fixture(params=["John", "Doe"], scope="class") 2922 def human(request): 2923 request.addfinalizer(lambda: values.append("fin %s" % request.param)) 2924 return request.param 2925 2926 class TestGreetings(object): 2927 def test_hello(self, human): 2928 values.append("test_hello") 2929 2930 class TestMetrics(object): 2931 def test_name(self, human): 2932 values.append("test_name") 2933 2934 def test_population(self, human): 2935 values.append("test_population") 2936 """ 2937 ) 2938 reprec = testdir.inline_run() 2939 reprec.assertoutcome(passed=6) 2940 values = reprec.getcalls("pytest_runtest_call")[0].item.module.values 2941 assert ( 2942 values 2943 == [ 2944 "test_hello", 2945 "fin John", 2946 "test_hello", 2947 "fin Doe", 2948 "test_name", 2949 "test_population", 2950 "fin John", 2951 "test_name", 2952 "test_population", 2953 "fin Doe", 2954 ] 2955 ) 2956 2957 def test_parametrize_setup_function(self, testdir): 2958 testdir.makepyfile( 2959 """ 2960 import pytest 2961 2962 @pytest.fixture(scope="module", params=[1, 2]) 2963 def arg(request): 2964 return request.param 2965 2966 @pytest.fixture(scope="module", autouse=True) 2967 def mysetup(request, arg): 2968 request.addfinalizer(lambda: values.append("fin%s" % arg)) 2969 values.append("setup%s" % arg) 2970 2971 values = [] 2972 def test_1(arg): 2973 values.append(arg) 2974 def test_2(arg): 2975 values.append(arg) 2976 def test_3(): 2977 import pprint 2978 pprint.pprint(values) 2979 if arg == 1: 2980 assert values == ["setup1", 1, 1, ] 2981 elif arg == 2: 2982 assert values == ["setup1", 1, 1, "fin1", 2983 "setup2", 2, 2, ] 2984 2985 """ 2986 ) 2987 reprec = testdir.inline_run("-v") 2988 reprec.assertoutcome(passed=6) 2989 2990 def test_fixture_marked_function_not_collected_as_test(self, testdir): 2991 testdir.makepyfile( 2992 """ 2993 import pytest 2994 @pytest.fixture 2995 def test_app(): 2996 return 1 2997 2998 def test_something(test_app): 2999 assert test_app == 1 3000 """ 3001 ) 3002 reprec = testdir.inline_run() 3003 reprec.assertoutcome(passed=1) 3004 3005 def test_params_and_ids(self, testdir): 3006 testdir.makepyfile( 3007 """ 3008 import pytest 3009 3010 @pytest.fixture(params=[object(), object()], 3011 ids=['alpha', 'beta']) 3012 def fix(request): 3013 return request.param 3014 3015 def test_foo(fix): 3016 assert 1 3017 """ 3018 ) 3019 res = testdir.runpytest("-v") 3020 res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"]) 3021 3022 def test_params_and_ids_yieldfixture(self, testdir): 3023 testdir.makepyfile( 3024 """ 3025 import pytest 3026 3027 @pytest.yield_fixture(params=[object(), object()], 3028 ids=['alpha', 'beta']) 3029 def fix(request): 3030 yield request.param 3031 3032 def test_foo(fix): 3033 assert 1 3034 """ 3035 ) 3036 res = testdir.runpytest("-v") 3037 res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"]) 3038 3039 @pytest.mark.issue920 3040 def test_deterministic_fixture_collection(self, testdir, monkeypatch): 3041 testdir.makepyfile( 3042 """ 3043 import pytest 3044 3045 @pytest.fixture(scope="module", 3046 params=["A", 3047 "B", 3048 "C"]) 3049 def A(request): 3050 return request.param 3051 3052 @pytest.fixture(scope="module", 3053 params=["DDDDDDDDD", "EEEEEEEEEEEE", "FFFFFFFFFFF", "banansda"]) 3054 def B(request, A): 3055 return request.param 3056 3057 def test_foo(B): 3058 # Something funky is going on here. 3059 # Despite specified seeds, on what is collected, 3060 # sometimes we get unexpected passes. hashing B seems 3061 # to help? 3062 assert hash(B) or True 3063 """ 3064 ) 3065 monkeypatch.setenv("PYTHONHASHSEED", "1") 3066 out1 = testdir.runpytest_subprocess("-v") 3067 monkeypatch.setenv("PYTHONHASHSEED", "2") 3068 out2 = testdir.runpytest_subprocess("-v") 3069 out1 = [ 3070 line 3071 for line in out1.outlines 3072 if line.startswith("test_deterministic_fixture_collection.py::test_foo") 3073 ] 3074 out2 = [ 3075 line 3076 for line in out2.outlines 3077 if line.startswith("test_deterministic_fixture_collection.py::test_foo") 3078 ] 3079 assert len(out1) == 12 3080 assert out1 == out2 3081 3082 3083class TestRequestScopeAccess(object): 3084 pytestmark = pytest.mark.parametrize( 3085 ("scope", "ok", "error"), 3086 [ 3087 ["session", "", "fspath class function module"], 3088 ["module", "module fspath", "cls function"], 3089 ["class", "module fspath cls", "function"], 3090 ["function", "module fspath cls function", ""], 3091 ], 3092 ) 3093 3094 def test_setup(self, testdir, scope, ok, error): 3095 testdir.makepyfile( 3096 """ 3097 import pytest 3098 @pytest.fixture(scope=%r, autouse=True) 3099 def myscoped(request): 3100 for x in %r: 3101 assert hasattr(request, x) 3102 for x in %r: 3103 pytest.raises(AttributeError, lambda: 3104 getattr(request, x)) 3105 assert request.session 3106 assert request.config 3107 def test_func(): 3108 pass 3109 """ 3110 % (scope, ok.split(), error.split()) 3111 ) 3112 reprec = testdir.inline_run("-l") 3113 reprec.assertoutcome(passed=1) 3114 3115 def test_funcarg(self, testdir, scope, ok, error): 3116 testdir.makepyfile( 3117 """ 3118 import pytest 3119 @pytest.fixture(scope=%r) 3120 def arg(request): 3121 for x in %r: 3122 assert hasattr(request, x) 3123 for x in %r: 3124 pytest.raises(AttributeError, lambda: 3125 getattr(request, x)) 3126 assert request.session 3127 assert request.config 3128 def test_func(arg): 3129 pass 3130 """ 3131 % (scope, ok.split(), error.split()) 3132 ) 3133 reprec = testdir.inline_run() 3134 reprec.assertoutcome(passed=1) 3135 3136 3137class TestErrors(object): 3138 3139 def test_subfactory_missing_funcarg(self, testdir): 3140 testdir.makepyfile( 3141 """ 3142 import pytest 3143 @pytest.fixture() 3144 def gen(qwe123): 3145 return 1 3146 def test_something(gen): 3147 pass 3148 """ 3149 ) 3150 result = testdir.runpytest() 3151 assert result.ret != 0 3152 result.stdout.fnmatch_lines( 3153 ["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"] 3154 ) 3155 3156 def test_issue498_fixture_finalizer_failing(self, testdir): 3157 testdir.makepyfile( 3158 """ 3159 import pytest 3160 @pytest.fixture 3161 def fix1(request): 3162 def f(): 3163 raise KeyError 3164 request.addfinalizer(f) 3165 return object() 3166 3167 values = [] 3168 def test_1(fix1): 3169 values.append(fix1) 3170 def test_2(fix1): 3171 values.append(fix1) 3172 def test_3(): 3173 assert values[0] != values[1] 3174 """ 3175 ) 3176 result = testdir.runpytest() 3177 result.stdout.fnmatch_lines( 3178 """ 3179 *ERROR*teardown*test_1* 3180 *KeyError* 3181 *ERROR*teardown*test_2* 3182 *KeyError* 3183 *3 pass*2 error* 3184 """ 3185 ) 3186 3187 def test_setupfunc_missing_funcarg(self, testdir): 3188 testdir.makepyfile( 3189 """ 3190 import pytest 3191 @pytest.fixture(autouse=True) 3192 def gen(qwe123): 3193 return 1 3194 def test_something(): 3195 pass 3196 """ 3197 ) 3198 result = testdir.runpytest() 3199 assert result.ret != 0 3200 result.stdout.fnmatch_lines( 3201 ["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"] 3202 ) 3203 3204 3205class TestShowFixtures(object): 3206 3207 def test_funcarg_compat(self, testdir): 3208 config = testdir.parseconfigure("--funcargs") 3209 assert config.option.showfixtures 3210 3211 def test_show_fixtures(self, testdir): 3212 result = testdir.runpytest("--fixtures") 3213 result.stdout.fnmatch_lines(["*tmpdir*", "*temporary directory*"]) 3214 3215 def test_show_fixtures_verbose(self, testdir): 3216 result = testdir.runpytest("--fixtures", "-v") 3217 result.stdout.fnmatch_lines(["*tmpdir*--*tmpdir.py*", "*temporary directory*"]) 3218 3219 def test_show_fixtures_testmodule(self, testdir): 3220 p = testdir.makepyfile( 3221 ''' 3222 import pytest 3223 @pytest.fixture 3224 def _arg0(): 3225 """ hidden """ 3226 @pytest.fixture 3227 def arg1(): 3228 """ hello world """ 3229 ''' 3230 ) 3231 result = testdir.runpytest("--fixtures", p) 3232 result.stdout.fnmatch_lines( 3233 """ 3234 *tmpdir 3235 *fixtures defined from* 3236 *arg1* 3237 *hello world* 3238 """ 3239 ) 3240 assert "arg0" not in result.stdout.str() 3241 3242 @pytest.mark.parametrize("testmod", [True, False]) 3243 def test_show_fixtures_conftest(self, testdir, testmod): 3244 testdir.makeconftest( 3245 ''' 3246 import pytest 3247 @pytest.fixture 3248 def arg1(): 3249 """ hello world """ 3250 ''' 3251 ) 3252 if testmod: 3253 testdir.makepyfile( 3254 """ 3255 def test_hello(): 3256 pass 3257 """ 3258 ) 3259 result = testdir.runpytest("--fixtures") 3260 result.stdout.fnmatch_lines( 3261 """ 3262 *tmpdir* 3263 *fixtures defined from*conftest* 3264 *arg1* 3265 *hello world* 3266 """ 3267 ) 3268 3269 def test_show_fixtures_trimmed_doc(self, testdir): 3270 p = testdir.makepyfile( 3271 dedent( 3272 ''' 3273 import pytest 3274 @pytest.fixture 3275 def arg1(): 3276 """ 3277 line1 3278 line2 3279 3280 """ 3281 @pytest.fixture 3282 def arg2(): 3283 """ 3284 line1 3285 line2 3286 3287 """ 3288 ''' 3289 ) 3290 ) 3291 result = testdir.runpytest("--fixtures", p) 3292 result.stdout.fnmatch_lines( 3293 dedent( 3294 """ 3295 * fixtures defined from test_show_fixtures_trimmed_doc * 3296 arg2 3297 line1 3298 line2 3299 arg1 3300 line1 3301 line2 3302 3303 """ 3304 ) 3305 ) 3306 3307 def test_show_fixtures_indented_doc(self, testdir): 3308 p = testdir.makepyfile( 3309 dedent( 3310 ''' 3311 import pytest 3312 @pytest.fixture 3313 def fixture1(): 3314 """ 3315 line1 3316 indented line 3317 """ 3318 ''' 3319 ) 3320 ) 3321 result = testdir.runpytest("--fixtures", p) 3322 result.stdout.fnmatch_lines( 3323 dedent( 3324 """ 3325 * fixtures defined from test_show_fixtures_indented_doc * 3326 fixture1 3327 line1 3328 indented line 3329 """ 3330 ) 3331 ) 3332 3333 def test_show_fixtures_indented_doc_first_line_unindented(self, testdir): 3334 p = testdir.makepyfile( 3335 dedent( 3336 ''' 3337 import pytest 3338 @pytest.fixture 3339 def fixture1(): 3340 """line1 3341 line2 3342 indented line 3343 """ 3344 ''' 3345 ) 3346 ) 3347 result = testdir.runpytest("--fixtures", p) 3348 result.stdout.fnmatch_lines( 3349 dedent( 3350 """ 3351 * fixtures defined from test_show_fixtures_indented_doc_first_line_unindented * 3352 fixture1 3353 line1 3354 line2 3355 indented line 3356 """ 3357 ) 3358 ) 3359 3360 def test_show_fixtures_indented_in_class(self, testdir): 3361 p = testdir.makepyfile( 3362 dedent( 3363 ''' 3364 import pytest 3365 class TestClass(object): 3366 @pytest.fixture 3367 def fixture1(self): 3368 """line1 3369 line2 3370 indented line 3371 """ 3372 ''' 3373 ) 3374 ) 3375 result = testdir.runpytest("--fixtures", p) 3376 result.stdout.fnmatch_lines( 3377 dedent( 3378 """ 3379 * fixtures defined from test_show_fixtures_indented_in_class * 3380 fixture1 3381 line1 3382 line2 3383 indented line 3384 """ 3385 ) 3386 ) 3387 3388 def test_show_fixtures_different_files(self, testdir): 3389 """ 3390 #833: --fixtures only shows fixtures from first file 3391 """ 3392 testdir.makepyfile( 3393 test_a=''' 3394 import pytest 3395 3396 @pytest.fixture 3397 def fix_a(): 3398 """Fixture A""" 3399 pass 3400 3401 def test_a(fix_a): 3402 pass 3403 ''' 3404 ) 3405 testdir.makepyfile( 3406 test_b=''' 3407 import pytest 3408 3409 @pytest.fixture 3410 def fix_b(): 3411 """Fixture B""" 3412 pass 3413 3414 def test_b(fix_b): 3415 pass 3416 ''' 3417 ) 3418 result = testdir.runpytest("--fixtures") 3419 result.stdout.fnmatch_lines( 3420 """ 3421 * fixtures defined from test_a * 3422 fix_a 3423 Fixture A 3424 3425 * fixtures defined from test_b * 3426 fix_b 3427 Fixture B 3428 """ 3429 ) 3430 3431 def test_show_fixtures_with_same_name(self, testdir): 3432 testdir.makeconftest( 3433 ''' 3434 import pytest 3435 @pytest.fixture 3436 def arg1(): 3437 """Hello World in conftest.py""" 3438 return "Hello World" 3439 ''' 3440 ) 3441 testdir.makepyfile( 3442 """ 3443 def test_foo(arg1): 3444 assert arg1 == "Hello World" 3445 """ 3446 ) 3447 testdir.makepyfile( 3448 ''' 3449 import pytest 3450 @pytest.fixture 3451 def arg1(): 3452 """Hi from test module""" 3453 return "Hi" 3454 def test_bar(arg1): 3455 assert arg1 == "Hi" 3456 ''' 3457 ) 3458 result = testdir.runpytest("--fixtures") 3459 result.stdout.fnmatch_lines( 3460 """ 3461 * fixtures defined from conftest * 3462 arg1 3463 Hello World in conftest.py 3464 3465 * fixtures defined from test_show_fixtures_with_same_name * 3466 arg1 3467 Hi from test module 3468 """ 3469 ) 3470 3471 def test_fixture_disallow_twice(self): 3472 """Test that applying @pytest.fixture twice generates an error (#2334).""" 3473 with pytest.raises(ValueError): 3474 3475 @pytest.fixture 3476 @pytest.fixture 3477 def foo(): 3478 pass 3479 3480 3481@pytest.mark.parametrize("flavor", ["fixture", "yield_fixture"]) 3482class TestContextManagerFixtureFuncs(object): 3483 3484 def test_simple(self, testdir, flavor): 3485 testdir.makepyfile( 3486 """ 3487 import pytest 3488 @pytest.{flavor} 3489 def arg1(): 3490 print ("setup") 3491 yield 1 3492 print ("teardown") 3493 def test_1(arg1): 3494 print ("test1 %s" % arg1) 3495 def test_2(arg1): 3496 print ("test2 %s" % arg1) 3497 assert 0 3498 """.format( 3499 flavor=flavor 3500 ) 3501 ) 3502 result = testdir.runpytest("-s") 3503 result.stdout.fnmatch_lines( 3504 """ 3505 *setup* 3506 *test1 1* 3507 *teardown* 3508 *setup* 3509 *test2 1* 3510 *teardown* 3511 """ 3512 ) 3513 3514 def test_scoped(self, testdir, flavor): 3515 testdir.makepyfile( 3516 """ 3517 import pytest 3518 @pytest.{flavor}(scope="module") 3519 def arg1(): 3520 print ("setup") 3521 yield 1 3522 print ("teardown") 3523 def test_1(arg1): 3524 print ("test1 %s" % arg1) 3525 def test_2(arg1): 3526 print ("test2 %s" % arg1) 3527 """.format( 3528 flavor=flavor 3529 ) 3530 ) 3531 result = testdir.runpytest("-s") 3532 result.stdout.fnmatch_lines( 3533 """ 3534 *setup* 3535 *test1 1* 3536 *test2 1* 3537 *teardown* 3538 """ 3539 ) 3540 3541 def test_setup_exception(self, testdir, flavor): 3542 testdir.makepyfile( 3543 """ 3544 import pytest 3545 @pytest.{flavor}(scope="module") 3546 def arg1(): 3547 pytest.fail("setup") 3548 yield 1 3549 def test_1(arg1): 3550 pass 3551 """.format( 3552 flavor=flavor 3553 ) 3554 ) 3555 result = testdir.runpytest("-s") 3556 result.stdout.fnmatch_lines( 3557 """ 3558 *pytest.fail*setup* 3559 *1 error* 3560 """ 3561 ) 3562 3563 def test_teardown_exception(self, testdir, flavor): 3564 testdir.makepyfile( 3565 """ 3566 import pytest 3567 @pytest.{flavor}(scope="module") 3568 def arg1(): 3569 yield 1 3570 pytest.fail("teardown") 3571 def test_1(arg1): 3572 pass 3573 """.format( 3574 flavor=flavor 3575 ) 3576 ) 3577 result = testdir.runpytest("-s") 3578 result.stdout.fnmatch_lines( 3579 """ 3580 *pytest.fail*teardown* 3581 *1 passed*1 error* 3582 """ 3583 ) 3584 3585 def test_yields_more_than_one(self, testdir, flavor): 3586 testdir.makepyfile( 3587 """ 3588 import pytest 3589 @pytest.{flavor}(scope="module") 3590 def arg1(): 3591 yield 1 3592 yield 2 3593 def test_1(arg1): 3594 pass 3595 """.format( 3596 flavor=flavor 3597 ) 3598 ) 3599 result = testdir.runpytest("-s") 3600 result.stdout.fnmatch_lines( 3601 """ 3602 *fixture function* 3603 *test_yields*:2* 3604 """ 3605 ) 3606 3607 def test_custom_name(self, testdir, flavor): 3608 testdir.makepyfile( 3609 """ 3610 import pytest 3611 @pytest.{flavor}(name='meow') 3612 def arg1(): 3613 return 'mew' 3614 def test_1(meow): 3615 print(meow) 3616 """.format( 3617 flavor=flavor 3618 ) 3619 ) 3620 result = testdir.runpytest("-s") 3621 result.stdout.fnmatch_lines("*mew*") 3622 3623 3624class TestParameterizedSubRequest(object): 3625 3626 def test_call_from_fixture(self, testdir): 3627 testfile = testdir.makepyfile( 3628 """ 3629 import pytest 3630 3631 @pytest.fixture(params=[0, 1, 2]) 3632 def fix_with_param(request): 3633 return request.param 3634 3635 @pytest.fixture 3636 def get_named_fixture(request): 3637 return request.getfixturevalue('fix_with_param') 3638 3639 def test_foo(request, get_named_fixture): 3640 pass 3641 """ 3642 ) 3643 result = testdir.runpytest() 3644 result.stdout.fnmatch_lines( 3645 """ 3646 E*Failed: The requested fixture has no parameter defined for the current test. 3647 E* 3648 E*Requested fixture 'fix_with_param' defined in: 3649 E*{}:4 3650 E*Requested here: 3651 E*{}:9 3652 *1 error* 3653 """.format( 3654 testfile.basename, testfile.basename 3655 ) 3656 ) 3657 3658 def test_call_from_test(self, testdir): 3659 testfile = testdir.makepyfile( 3660 """ 3661 import pytest 3662 3663 @pytest.fixture(params=[0, 1, 2]) 3664 def fix_with_param(request): 3665 return request.param 3666 3667 def test_foo(request): 3668 request.getfixturevalue('fix_with_param') 3669 """ 3670 ) 3671 result = testdir.runpytest() 3672 result.stdout.fnmatch_lines( 3673 """ 3674 E*Failed: The requested fixture has no parameter defined for the current test. 3675 E* 3676 E*Requested fixture 'fix_with_param' defined in: 3677 E*{}:4 3678 E*Requested here: 3679 E*{}:8 3680 *1 failed* 3681 """.format( 3682 testfile.basename, testfile.basename 3683 ) 3684 ) 3685 3686 def test_external_fixture(self, testdir): 3687 conffile = testdir.makeconftest( 3688 """ 3689 import pytest 3690 3691 @pytest.fixture(params=[0, 1, 2]) 3692 def fix_with_param(request): 3693 return request.param 3694 """ 3695 ) 3696 3697 testfile = testdir.makepyfile( 3698 """ 3699 def test_foo(request): 3700 request.getfixturevalue('fix_with_param') 3701 """ 3702 ) 3703 result = testdir.runpytest() 3704 result.stdout.fnmatch_lines( 3705 """ 3706 E*Failed: The requested fixture has no parameter defined for the current test. 3707 E* 3708 E*Requested fixture 'fix_with_param' defined in: 3709 E*{}:4 3710 E*Requested here: 3711 E*{}:2 3712 *1 failed* 3713 """.format( 3714 conffile.basename, testfile.basename 3715 ) 3716 ) 3717 3718 def test_non_relative_path(self, testdir): 3719 tests_dir = testdir.mkdir("tests") 3720 fixdir = testdir.mkdir("fixtures") 3721 fixfile = fixdir.join("fix.py") 3722 fixfile.write( 3723 _pytest._code.Source( 3724 """ 3725 import pytest 3726 3727 @pytest.fixture(params=[0, 1, 2]) 3728 def fix_with_param(request): 3729 return request.param 3730 """ 3731 ) 3732 ) 3733 3734 testfile = tests_dir.join("test_foos.py") 3735 testfile.write( 3736 _pytest._code.Source( 3737 """ 3738 from fix import fix_with_param 3739 3740 def test_foo(request): 3741 request.getfixturevalue('fix_with_param') 3742 """ 3743 ) 3744 ) 3745 3746 tests_dir.chdir() 3747 testdir.syspathinsert(fixdir) 3748 result = testdir.runpytest() 3749 result.stdout.fnmatch_lines( 3750 """ 3751 E*Failed: The requested fixture has no parameter defined for the current test. 3752 E* 3753 E*Requested fixture 'fix_with_param' defined in: 3754 E*{}:5 3755 E*Requested here: 3756 E*{}:5 3757 *1 failed* 3758 """.format( 3759 fixfile.strpath, testfile.basename 3760 ) 3761 ) 3762 3763 3764def test_pytest_fixture_setup_and_post_finalizer_hook(testdir): 3765 testdir.makeconftest( 3766 """ 3767 from __future__ import print_function 3768 def pytest_fixture_setup(fixturedef, request): 3769 print('ROOT setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name)) 3770 def pytest_fixture_post_finalizer(fixturedef, request): 3771 print('ROOT finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name)) 3772 """ 3773 ) 3774 testdir.makepyfile( 3775 **{ 3776 "tests/conftest.py": """ 3777 from __future__ import print_function 3778 def pytest_fixture_setup(fixturedef, request): 3779 print('TESTS setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name)) 3780 def pytest_fixture_post_finalizer(fixturedef, request): 3781 print('TESTS finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name)) 3782 """, 3783 "tests/test_hooks.py": """ 3784 from __future__ import print_function 3785 import pytest 3786 3787 @pytest.fixture() 3788 def my_fixture(): 3789 return 'some' 3790 3791 def test_func(my_fixture): 3792 print('TEST test_func') 3793 assert my_fixture == 'some' 3794 """, 3795 } 3796 ) 3797 result = testdir.runpytest("-s") 3798 assert result.ret == 0 3799 result.stdout.fnmatch_lines( 3800 [ 3801 "*TESTS setup hook called for my_fixture from test_func*", 3802 "*ROOT setup hook called for my_fixture from test_func*", 3803 "*TEST test_func*", 3804 "*TESTS finalizer hook called for my_fixture from test_func*", 3805 "*ROOT finalizer hook called for my_fixture from test_func*", 3806 ] 3807 ) 3808 3809 3810class TestScopeOrdering(object): 3811 """Class of tests that ensure fixtures are ordered based on their scopes (#2405)""" 3812 3813 @pytest.mark.parametrize("use_mark", [True, False]) 3814 def test_func_closure_module_auto(self, testdir, use_mark): 3815 """Semantically identical to the example posted in #2405 when ``use_mark=True``""" 3816 testdir.makepyfile( 3817 """ 3818 import pytest 3819 3820 @pytest.fixture(scope='module', autouse={autouse}) 3821 def m1(): pass 3822 3823 if {use_mark}: 3824 pytestmark = pytest.mark.usefixtures('m1') 3825 3826 @pytest.fixture(scope='function', autouse=True) 3827 def f1(): pass 3828 3829 def test_func(m1): 3830 pass 3831 """.format( 3832 autouse=not use_mark, use_mark=use_mark 3833 ) 3834 ) 3835 items, _ = testdir.inline_genitems() 3836 request = FixtureRequest(items[0]) 3837 assert request.fixturenames == "m1 f1".split() 3838 3839 def test_func_closure_with_native_fixtures(self, testdir, monkeypatch): 3840 """Sanity check that verifies the order returned by the closures and the actual fixture execution order: 3841 The execution order may differ because of fixture inter-dependencies. 3842 """ 3843 monkeypatch.setattr(pytest, "FIXTURE_ORDER", [], raising=False) 3844 testdir.makepyfile( 3845 """ 3846 import pytest 3847 3848 FIXTURE_ORDER = pytest.FIXTURE_ORDER 3849 3850 @pytest.fixture(scope="session") 3851 def s1(): 3852 FIXTURE_ORDER.append('s1') 3853 3854 @pytest.fixture(scope="module") 3855 def m1(): 3856 FIXTURE_ORDER.append('m1') 3857 3858 @pytest.fixture(scope='session') 3859 def my_tmpdir_factory(): 3860 FIXTURE_ORDER.append('my_tmpdir_factory') 3861 3862 @pytest.fixture 3863 def my_tmpdir(my_tmpdir_factory): 3864 FIXTURE_ORDER.append('my_tmpdir') 3865 3866 @pytest.fixture 3867 def f1(my_tmpdir): 3868 FIXTURE_ORDER.append('f1') 3869 3870 @pytest.fixture 3871 def f2(): 3872 FIXTURE_ORDER.append('f2') 3873 3874 def test_foo(f1, m1, f2, s1): pass 3875 """ 3876 ) 3877 items, _ = testdir.inline_genitems() 3878 request = FixtureRequest(items[0]) 3879 # order of fixtures based on their scope and position in the parameter list 3880 assert request.fixturenames == "s1 my_tmpdir_factory m1 f1 f2 my_tmpdir".split() 3881 testdir.runpytest() 3882 # actual fixture execution differs: dependent fixtures must be created first ("my_tmpdir") 3883 assert pytest.FIXTURE_ORDER == "s1 my_tmpdir_factory m1 my_tmpdir f1 f2".split() 3884 3885 def test_func_closure_module(self, testdir): 3886 testdir.makepyfile( 3887 """ 3888 import pytest 3889 3890 @pytest.fixture(scope='module') 3891 def m1(): pass 3892 3893 @pytest.fixture(scope='function') 3894 def f1(): pass 3895 3896 def test_func(f1, m1): 3897 pass 3898 """ 3899 ) 3900 items, _ = testdir.inline_genitems() 3901 request = FixtureRequest(items[0]) 3902 assert request.fixturenames == "m1 f1".split() 3903 3904 def test_func_closure_scopes_reordered(self, testdir): 3905 """Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although 3906 fixtures of same scope keep the declared order 3907 """ 3908 testdir.makepyfile( 3909 """ 3910 import pytest 3911 3912 @pytest.fixture(scope='session') 3913 def s1(): pass 3914 3915 @pytest.fixture(scope='module') 3916 def m1(): pass 3917 3918 @pytest.fixture(scope='function') 3919 def f1(): pass 3920 3921 @pytest.fixture(scope='function') 3922 def f2(): pass 3923 3924 class Test: 3925 3926 @pytest.fixture(scope='class') 3927 def c1(cls): pass 3928 3929 def test_func(self, f2, f1, c1, m1, s1): 3930 pass 3931 """ 3932 ) 3933 items, _ = testdir.inline_genitems() 3934 request = FixtureRequest(items[0]) 3935 assert request.fixturenames == "s1 m1 c1 f2 f1".split() 3936 3937 def test_func_closure_same_scope_closer_root_first(self, testdir): 3938 """Auto-use fixtures of same scope are ordered by closer-to-root first""" 3939 testdir.makeconftest( 3940 """ 3941 import pytest 3942 3943 @pytest.fixture(scope='module', autouse=True) 3944 def m_conf(): pass 3945 """ 3946 ) 3947 testdir.makepyfile( 3948 **{ 3949 "sub/conftest.py": """ 3950 import pytest 3951 3952 @pytest.fixture(scope='module', autouse=True) 3953 def m_sub(): pass 3954 """, 3955 "sub/test_func.py": """ 3956 import pytest 3957 3958 @pytest.fixture(scope='module', autouse=True) 3959 def m_test(): pass 3960 3961 @pytest.fixture(scope='function') 3962 def f1(): pass 3963 3964 def test_func(m_test, f1): 3965 pass 3966 """, 3967 } 3968 ) 3969 items, _ = testdir.inline_genitems() 3970 request = FixtureRequest(items[0]) 3971 assert request.fixturenames == "m_conf m_sub m_test f1".split() 3972 3973 def test_func_closure_all_scopes_complex(self, testdir): 3974 """Complex test involving all scopes and mixing autouse with normal fixtures""" 3975 testdir.makeconftest( 3976 """ 3977 import pytest 3978 3979 @pytest.fixture(scope='session') 3980 def s1(): pass 3981 """ 3982 ) 3983 testdir.makepyfile( 3984 """ 3985 import pytest 3986 3987 @pytest.fixture(scope='module', autouse=True) 3988 def m1(): pass 3989 3990 @pytest.fixture(scope='module') 3991 def m2(s1): pass 3992 3993 @pytest.fixture(scope='function') 3994 def f1(): pass 3995 3996 @pytest.fixture(scope='function') 3997 def f2(): pass 3998 3999 class Test: 4000 4001 @pytest.fixture(scope='class', autouse=True) 4002 def c1(self): 4003 pass 4004 4005 def test_func(self, f2, f1, m2): 4006 pass 4007 """ 4008 ) 4009 items, _ = testdir.inline_genitems() 4010 request = FixtureRequest(items[0]) 4011 assert request.fixturenames == "s1 m1 m2 c1 f2 f1".split() 4012