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