Best Python code snippet using behave
fixture.py
Source:fixture.py
...30 return 4231 def test_func(some):32 pass33 """)34 result = testdir.runpytest() # "--collect-only")35 assert result.ret != 036 result.stdout.fnmatch_lines([37 "*def test_func(some)*",38 "*fixture*some*not found*",39 "*xyzsomething*",40 ])41 def test_funcarg_basic(self, testdir):42 item = testdir.getitem("""43 def pytest_funcarg__some(request):44 return request.function.__name__45 def pytest_funcarg__other(request):46 return 4247 def test_func(some, other):48 pass49 """)50 funcargs.fillfixtures(item)51 del item.funcargs["request"]52 assert len(get_public_names(item.funcargs)) == 253 assert item.funcargs['some'] == "test_func"54 assert item.funcargs['other'] == 4255 def test_funcarg_lookup_modulelevel(self, testdir):56 testdir.makepyfile("""57 def pytest_funcarg__something(request):58 return request.function.__name__59 class TestClass:60 def test_method(self, something):61 assert something == "test_method"62 def test_func(something):63 assert something == "test_func"64 """)65 reprec = testdir.inline_run()66 reprec.assertoutcome(passed=2)67 def test_funcarg_lookup_classlevel(self, testdir):68 p = testdir.makepyfile("""69 class TestClass:70 def pytest_funcarg__something(self, request):71 return request.instance72 def test_method(self, something):73 assert something is self74 """)75 result = testdir.runpytest(p)76 result.stdout.fnmatch_lines([77 "*1 passed*"78 ])79 def test_conftest_funcargs_only_available_in_subdir(self, testdir):80 sub1 = testdir.mkpydir("sub1")81 sub2 = testdir.mkpydir("sub2")82 sub1.join("conftest.py").write(_pytest._code.Source("""83 import pytest84 def pytest_funcarg__arg1(request):85 pytest.raises(Exception, "request.getfuncargvalue('arg2')")86 """))87 sub2.join("conftest.py").write(_pytest._code.Source("""88 import pytest89 def pytest_funcarg__arg2(request):90 pytest.raises(Exception, "request.getfuncargvalue('arg1')")91 """))92 sub1.join("test_in_sub1.py").write("def test_1(arg1): pass")93 sub2.join("test_in_sub2.py").write("def test_2(arg2): pass")94 result = testdir.runpytest("-v")95 result.assert_outcomes(passed=2)96 def test_extend_fixture_module_class(self, testdir):97 testfile = testdir.makepyfile("""98 import pytest99 @pytest.fixture100 def spam():101 return 'spam'102 class TestSpam:103 @pytest.fixture104 def spam(self, spam):105 return spam * 2106 def test_spam(self, spam):107 assert spam == 'spamspam'108 """)109 result = testdir.runpytest()110 result.stdout.fnmatch_lines(["*1 passed*"])111 result = testdir.runpytest(testfile)112 result.stdout.fnmatch_lines(["*1 passed*"])113 def test_extend_fixture_conftest_module(self, testdir):114 testdir.makeconftest("""115 import pytest116 @pytest.fixture117 def spam():118 return 'spam'119 """)120 testfile = testdir.makepyfile("""121 import pytest122 @pytest.fixture123 def spam(spam):124 return spam * 2125 def test_spam(spam):126 assert spam == 'spamspam'127 """)128 result = testdir.runpytest()129 result.stdout.fnmatch_lines(["*1 passed*"])130 result = testdir.runpytest(testfile)131 result.stdout.fnmatch_lines(["*1 passed*"])132 def test_extend_fixture_conftest_conftest(self, testdir):133 testdir.makeconftest("""134 import pytest135 @pytest.fixture136 def spam():137 return 'spam'138 """)139 pkg = testdir.mkpydir("pkg")140 pkg.join("conftest.py").write(_pytest._code.Source("""141 import pytest142 @pytest.fixture143 def spam(spam):144 return spam * 2145 """))146 testfile = pkg.join("test_spam.py")147 testfile.write(_pytest._code.Source("""148 def test_spam(spam):149 assert spam == "spamspam"150 """))151 result = testdir.runpytest()152 result.stdout.fnmatch_lines(["*1 passed*"])153 result = testdir.runpytest(testfile)154 result.stdout.fnmatch_lines(["*1 passed*"])155 def test_extend_fixture_conftest_plugin(self, testdir):156 testdir.makepyfile(testplugin="""157 import pytest158 @pytest.fixture159 def foo():160 return 7161 """)162 testdir.syspathinsert()163 testdir.makeconftest("""164 import pytest165 pytest_plugins = 'testplugin'166 @pytest.fixture167 def foo(foo):168 return foo + 7169 """)170 testdir.makepyfile("""171 def test_foo(foo):172 assert foo == 14173 """)174 result = testdir.runpytest('-s')175 assert result.ret == 0176 def test_extend_fixture_plugin_plugin(self, testdir):177 # Two plugins should extend each order in loading order178 testdir.makepyfile(testplugin0="""179 import pytest180 @pytest.fixture181 def foo():182 return 7183 """)184 testdir.makepyfile(testplugin1="""185 import pytest186 @pytest.fixture187 def foo(foo):188 return foo + 7189 """)190 testdir.syspathinsert()191 testdir.makepyfile("""192 pytest_plugins = ['testplugin0', 'testplugin1']193 def test_foo(foo):194 assert foo == 14195 """)196 result = testdir.runpytest()197 assert result.ret == 0198 def test_override_parametrized_fixture_conftest_module(self, testdir):199 """Test override of the parametrized fixture with non-parametrized one on the test module level."""200 testdir.makeconftest("""201 import pytest202 @pytest.fixture(params=[1, 2, 3])203 def spam(request):204 return request.param205 """)206 testfile = testdir.makepyfile("""207 import pytest208 @pytest.fixture209 def spam():210 return 'spam'211 def test_spam(spam):212 assert spam == 'spam'213 """)214 result = testdir.runpytest()215 result.stdout.fnmatch_lines(["*1 passed*"])216 result = testdir.runpytest(testfile)217 result.stdout.fnmatch_lines(["*1 passed*"])218 def test_override_parametrized_fixture_conftest_conftest(self, testdir):219 """Test override of the parametrized fixture with non-parametrized one on the conftest level."""220 testdir.makeconftest("""221 import pytest222 @pytest.fixture(params=[1, 2, 3])223 def spam(request):224 return request.param225 """)226 subdir = testdir.mkpydir('subdir')227 subdir.join("conftest.py").write(_pytest._code.Source("""228 import pytest229 @pytest.fixture230 def spam():231 return 'spam'232 """))233 testfile = subdir.join("test_spam.py")234 testfile.write(_pytest._code.Source("""235 def test_spam(spam):236 assert spam == "spam"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 def test_override_non_parametrized_fixture_conftest_module(self, testdir):243 """Test override of the non-parametrized fixture with parametrized one on the test module level."""244 testdir.makeconftest("""245 import pytest246 @pytest.fixture247 def spam():248 return 'spam'249 """)250 testfile = testdir.makepyfile("""251 import pytest252 @pytest.fixture(params=[1, 2, 3])253 def spam(request):254 return request.param255 params = {'spam': 1}256 def test_spam(spam):257 assert spam == params['spam']258 params['spam'] += 1259 """)260 result = testdir.runpytest()261 result.stdout.fnmatch_lines(["*3 passed*"])262 result = testdir.runpytest(testfile)263 result.stdout.fnmatch_lines(["*3 passed*"])264 def test_override_non_parametrized_fixture_conftest_conftest(self, testdir):265 """Test override of the non-parametrized fixture with parametrized one on the conftest level."""266 testdir.makeconftest("""267 import pytest268 @pytest.fixture269 def spam():270 return 'spam'271 """)272 subdir = testdir.mkpydir('subdir')273 subdir.join("conftest.py").write(_pytest._code.Source("""274 import pytest275 @pytest.fixture(params=[1, 2, 3])276 def spam(request):277 return request.param278 """))279 testfile = subdir.join("test_spam.py")280 testfile.write(_pytest._code.Source("""281 params = {'spam': 1}282 def test_spam(spam):283 assert spam == params['spam']284 params['spam'] += 1285 """))286 result = testdir.runpytest()287 result.stdout.fnmatch_lines(["*3 passed*"])288 result = testdir.runpytest(testfile)289 result.stdout.fnmatch_lines(["*3 passed*"])290 def test_autouse_fixture_plugin(self, testdir):291 # A fixture from a plugin has no baseid set, which screwed up292 # the autouse fixture handling.293 testdir.makepyfile(testplugin="""294 import pytest295 @pytest.fixture(autouse=True)296 def foo(request):297 request.function.foo = 7298 """)299 testdir.syspathinsert()300 testdir.makepyfile("""301 pytest_plugins = 'testplugin'302 def test_foo(request):303 assert request.function.foo == 7304 """)305 result = testdir.runpytest()306 assert result.ret == 0307 def test_funcarg_lookup_error(self, testdir):308 testdir.makepyfile("""309 def test_lookup_error(unknown):310 pass311 """)312 result = testdir.runpytest()313 result.stdout.fnmatch_lines([314 "*ERROR*test_lookup_error*",315 "*def test_lookup_error(unknown):*",316 "*fixture*unknown*not found*",317 "*available fixtures*",318 "*1 error*",319 ])320 assert "INTERNAL" not in result.stdout.str()321 def test_fixture_excinfo_leak(self, testdir):322 # on python2 sys.excinfo would leak into fixture executions323 testdir.makepyfile("""324 import sys325 import traceback326 import pytest327 @pytest.fixture328 def leak():329 if sys.exc_info()[0]: # python3 bug :)330 traceback.print_exc()331 #fails332 assert sys.exc_info() == (None, None, None)333 def test_leak(leak):334 if sys.exc_info()[0]: # python3 bug :)335 traceback.print_exc()336 assert sys.exc_info() == (None, None, None)337 """)338 result = testdir.runpytest()339 assert result.ret == 0340class TestRequestBasic:341 def test_request_attributes(self, testdir):342 item = testdir.getitem("""343 def pytest_funcarg__something(request): pass344 def test_func(something): pass345 """)346 req = funcargs.FixtureRequest(item)347 assert req.function == item.obj348 assert req.keywords == item.keywords349 assert hasattr(req.module, 'test_func')350 assert req.cls is None351 assert req.function.__name__ == "test_func"352 assert req.config == item.config353 assert repr(req).find(req.function.__name__) != -1354 def test_request_attributes_method(self, testdir):355 item, = testdir.getitems("""356 class TestB:357 def pytest_funcarg__something(self, request):358 return 1359 def test_func(self, something):360 pass361 """)362 req = item._request363 assert req.cls.__name__ == "TestB"364 assert req.instance.__class__ == req.cls365 def XXXtest_request_contains_funcarg_arg2fixturedefs(self, testdir):366 modcol = testdir.getmodulecol("""367 def pytest_funcarg__something(request):368 pass369 class TestClass:370 def test_method(self, something):371 pass372 """)373 item1, = testdir.genitems([modcol])374 assert item1.name == "test_method"375 arg2fixturedefs = funcargs.FixtureRequest(item1)._arg2fixturedefs376 assert len(arg2fixturedefs) == 1377 assert arg2fixturedefs[0].__name__ == "pytest_funcarg__something"378 def test_getfuncargvalue_recursive(self, testdir):379 testdir.makeconftest("""380 def pytest_funcarg__something(request):381 return 1382 """)383 testdir.makepyfile("""384 def pytest_funcarg__something(request):385 return request.getfuncargvalue("something") + 1386 def test_func(something):387 assert something == 2388 """)389 reprec = testdir.inline_run()390 reprec.assertoutcome(passed=1)391 def test_getfuncargvalue(self, testdir):392 item = testdir.getitem("""393 l = [2]394 def pytest_funcarg__something(request): return 1395 def pytest_funcarg__other(request):396 return l.pop()397 def test_func(something): pass398 """)399 req = item._request400 pytest.raises(FixtureLookupError, req.getfuncargvalue, "notexists")401 val = req.getfuncargvalue("something")402 assert val == 1403 val = req.getfuncargvalue("something")404 assert val == 1405 val2 = req.getfuncargvalue("other")406 assert val2 == 2407 val2 = req.getfuncargvalue("other") # see about caching408 assert val2 == 2409 pytest._fillfuncargs(item)410 assert item.funcargs["something"] == 1411 assert len(get_public_names(item.funcargs)) == 2412 assert "request" in item.funcargs413 #assert item.funcargs == {'something': 1, "other": 2}414 def test_request_addfinalizer(self, testdir):415 item = testdir.getitem("""416 teardownlist = []417 def pytest_funcarg__something(request):418 request.addfinalizer(lambda: teardownlist.append(1))419 def test_func(something): pass420 """)421 item.session._setupstate.prepare(item)422 pytest._fillfuncargs(item)423 # successively check finalization calls424 teardownlist = item.getparent(pytest.Module).obj.teardownlist425 ss = item.session._setupstate426 assert not teardownlist427 ss.teardown_exact(item, None)428 print(ss.stack)429 assert teardownlist == [1]430 def test_request_addfinalizer_failing_setup(self, testdir):431 testdir.makepyfile("""432 import pytest433 l = [1]434 @pytest.fixture435 def myfix(request):436 request.addfinalizer(l.pop)437 assert 0438 def test_fix(myfix):439 pass440 def test_finalizer_ran():441 assert not l442 """)443 reprec = testdir.inline_run("-s")444 reprec.assertoutcome(failed=1, passed=1)445 def test_request_addfinalizer_failing_setup_module(self, testdir):446 testdir.makepyfile("""447 import pytest448 l = [1, 2]449 @pytest.fixture(scope="module")450 def myfix(request):451 request.addfinalizer(l.pop)452 request.addfinalizer(l.pop)453 assert 0454 def test_fix(myfix):455 pass456 """)457 reprec = testdir.inline_run("-s")458 mod = reprec.getcalls("pytest_runtest_setup")[0].item.module459 assert not mod.l460 def test_request_addfinalizer_partial_setup_failure(self, testdir):461 p = testdir.makepyfile("""462 l = []463 def pytest_funcarg__something(request):464 request.addfinalizer(lambda: l.append(None))465 def test_func(something, missingarg):466 pass467 def test_second():468 assert len(l) == 1469 """)470 result = testdir.runpytest(p)471 result.stdout.fnmatch_lines([472 "*1 error*" # XXX the whole module collection fails473 ])474 def test_request_getmodulepath(self, testdir):475 modcol = testdir.getmodulecol("def test_somefunc(): pass")476 item, = testdir.genitems([modcol])477 req = funcargs.FixtureRequest(item)478 assert req.fspath == modcol.fspath479 def test_request_fixturenames(self, testdir):480 testdir.makepyfile("""481 import pytest482 from _pytest.pytester import get_public_names483 @pytest.fixture()484 def arg1():485 pass486 @pytest.fixture()487 def farg(arg1):488 pass489 @pytest.fixture(autouse=True)490 def sarg(tmpdir):491 pass492 def test_function(request, farg):493 assert set(get_public_names(request.fixturenames)) == \494 set(["tmpdir", "sarg", "arg1", "request", "farg",495 "tmpdir_factory"])496 """)497 reprec = testdir.inline_run()498 reprec.assertoutcome(passed=1)499 def test_funcargnames_compatattr(self, testdir):500 testdir.makepyfile("""501 def pytest_generate_tests(metafunc):502 assert metafunc.funcargnames == metafunc.fixturenames503 def pytest_funcarg__fn(request):504 assert request._pyfuncitem.funcargnames == \505 request._pyfuncitem.fixturenames506 return request.funcargnames, request.fixturenames507 def test_hello(fn):508 assert fn[0] == fn[1]509 """)510 reprec = testdir.inline_run()511 reprec.assertoutcome(passed=1)512 def test_setupdecorator_and_xunit(self, testdir):513 testdir.makepyfile("""514 import pytest515 l = []516 @pytest.fixture(scope='module', autouse=True)517 def setup_module():518 l.append("module")519 @pytest.fixture(autouse=True)520 def setup_function():521 l.append("function")522 def test_func():523 pass524 class TestClass:525 @pytest.fixture(scope="class", autouse=True)526 def setup_class(self):527 l.append("class")528 @pytest.fixture(autouse=True)529 def setup_method(self):530 l.append("method")531 def test_method(self):532 pass533 def test_all():534 assert l == ["module", "function", "class",535 "function", "method", "function"]536 """)537 reprec = testdir.inline_run("-v")538 reprec.assertoutcome(passed=3)539 def test_fixtures_sub_subdir_normalize_sep(self, testdir):540 # this tests that normalization of nodeids takes place541 b = testdir.mkdir("tests").mkdir("unit")542 b.join("conftest.py").write(_pytest._code.Source("""543 def pytest_funcarg__arg1():544 pass545 """))546 p = b.join("test_module.py")547 p.write("def test_func(arg1): pass")548 result = testdir.runpytest(p, "--fixtures")549 assert result.ret == 0550 result.stdout.fnmatch_lines("""551 *fixtures defined*conftest*552 *arg1*553 """)554 def test_show_fixtures_color_yes(self, testdir):555 testdir.makepyfile("def test_this(): assert 1")556 result = testdir.runpytest('--color=yes', '--fixtures')557 assert '\x1b[32mtmpdir' in result.stdout.str()558 def test_newstyle_with_request(self, testdir):559 testdir.makepyfile("""560 import pytest561 @pytest.fixture()562 def arg(request):563 pass564 def test_1(arg):565 pass566 """)567 reprec = testdir.inline_run()568 reprec.assertoutcome(passed=1)569 def test_setupcontext_no_param(self, testdir):570 testdir.makepyfile("""571 import pytest572 @pytest.fixture(params=[1,2])573 def arg(request):574 return request.param575 @pytest.fixture(autouse=True)576 def mysetup(request, arg):577 assert not hasattr(request, "param")578 def test_1(arg):579 assert arg in (1,2)580 """)581 reprec = testdir.inline_run()582 reprec.assertoutcome(passed=2)583class TestRequestMarking:584 def test_applymarker(self, testdir):585 item1,item2 = testdir.getitems("""586 def pytest_funcarg__something(request):587 pass588 class TestClass:589 def test_func1(self, something):590 pass591 def test_func2(self, something):592 pass593 """)594 req1 = funcargs.FixtureRequest(item1)595 assert 'xfail' not in item1.keywords596 req1.applymarker(pytest.mark.xfail)597 assert 'xfail' in item1.keywords598 assert 'skipif' not in item1.keywords599 req1.applymarker(pytest.mark.skipif)600 assert 'skipif' in item1.keywords601 pytest.raises(ValueError, "req1.applymarker(42)")602 def test_accesskeywords(self, testdir):603 testdir.makepyfile("""604 import pytest605 @pytest.fixture()606 def keywords(request):607 return request.keywords608 @pytest.mark.XYZ609 def test_function(keywords):610 assert keywords["XYZ"]611 assert "abc" not in keywords612 """)613 reprec = testdir.inline_run()614 reprec.assertoutcome(passed=1)615 def test_accessmarker_dynamic(self, testdir):616 testdir.makeconftest("""617 import pytest618 @pytest.fixture()619 def keywords(request):620 return request.keywords621 @pytest.fixture(scope="class", autouse=True)622 def marking(request):623 request.applymarker(pytest.mark.XYZ("hello"))624 """)625 testdir.makepyfile("""626 import pytest627 def test_fun1(keywords):628 assert keywords["XYZ"] is not None629 assert "abc" not in keywords630 def test_fun2(keywords):631 assert keywords["XYZ"] is not None632 assert "abc" not in keywords633 """)634 reprec = testdir.inline_run()635 reprec.assertoutcome(passed=2)636class TestRequestCachedSetup:637 def test_request_cachedsetup_defaultmodule(self, testdir):638 reprec = testdir.inline_runsource("""639 mysetup = ["hello",].pop640 def pytest_funcarg__something(request):641 return request.cached_setup(mysetup, scope="module")642 def test_func1(something):643 assert something == "hello"644 class TestClass:645 def test_func1a(self, something):646 assert something == "hello"647 """)648 reprec.assertoutcome(passed=2)649 def test_request_cachedsetup_class(self, testdir):650 reprec = testdir.inline_runsource("""651 mysetup = ["hello", "hello2", "hello3"].pop652 def pytest_funcarg__something(request):653 return request.cached_setup(mysetup, scope="class")654 def test_func1(something):655 assert something == "hello3"656 def test_func2(something):657 assert something == "hello2"658 class TestClass:659 def test_func1a(self, something):660 assert something == "hello"661 def test_func2b(self, something):662 assert something == "hello"663 """)664 reprec.assertoutcome(passed=4)665 def test_request_cachedsetup_extrakey(self, testdir):666 item1 = testdir.getitem("def test_func(): pass")667 req1 = funcargs.FixtureRequest(item1)668 l = ["hello", "world"]669 def setup():670 return l.pop()671 ret1 = req1.cached_setup(setup, extrakey=1)672 ret2 = req1.cached_setup(setup, extrakey=2)673 assert ret2 == "hello"674 assert ret1 == "world"675 ret1b = req1.cached_setup(setup, extrakey=1)676 ret2b = req1.cached_setup(setup, extrakey=2)677 assert ret1 == ret1b678 assert ret2 == ret2b679 def test_request_cachedsetup_cache_deletion(self, testdir):680 item1 = testdir.getitem("def test_func(): pass")681 req1 = funcargs.FixtureRequest(item1)682 l = []683 def setup():684 l.append("setup")685 def teardown(val):686 l.append("teardown")687 req1.cached_setup(setup, teardown, scope="function")688 assert l == ['setup']689 # artificial call of finalizer690 setupstate = req1._pyfuncitem.session._setupstate691 setupstate._callfinalizers(item1)692 assert l == ["setup", "teardown"]693 req1.cached_setup(setup, teardown, scope="function")694 assert l == ["setup", "teardown", "setup"]695 setupstate._callfinalizers(item1)696 assert l == ["setup", "teardown", "setup", "teardown"]697 def test_request_cached_setup_two_args(self, testdir):698 testdir.makepyfile("""699 def pytest_funcarg__arg1(request):700 return request.cached_setup(lambda: 42)701 def pytest_funcarg__arg2(request):702 return request.cached_setup(lambda: 17)703 def test_two_different_setups(arg1, arg2):704 assert arg1 != arg2705 """)706 result = testdir.runpytest("-v")707 result.stdout.fnmatch_lines([708 "*1 passed*"709 ])710 def test_request_cached_setup_getfuncargvalue(self, testdir):711 testdir.makepyfile("""712 def pytest_funcarg__arg1(request):713 arg1 = request.getfuncargvalue("arg2")714 return request.cached_setup(lambda: arg1 + 1)715 def pytest_funcarg__arg2(request):716 return request.cached_setup(lambda: 10)717 def test_two_funcarg(arg1):718 assert arg1 == 11719 """)720 result = testdir.runpytest("-v")721 result.stdout.fnmatch_lines([722 "*1 passed*"723 ])724 def test_request_cached_setup_functional(self, testdir):725 testdir.makepyfile(test_0="""726 l = []727 def pytest_funcarg__something(request):728 val = request.cached_setup(fsetup, fteardown)729 return val730 def fsetup(mycache=[1]):731 l.append(mycache.pop())732 return l733 def fteardown(something):734 l.remove(something[0])735 l.append(2)736 def test_list_once(something):737 assert something == [1]738 def test_list_twice(something):739 assert something == [1]740 """)741 testdir.makepyfile(test_1="""742 import test_0 # should have run already743 def test_check_test0_has_teardown_correct():744 assert test_0.l == [2]745 """)746 result = testdir.runpytest("-v")747 result.stdout.fnmatch_lines([748 "*3 passed*"749 ])750 def test_issue117_sessionscopeteardown(self, testdir):751 testdir.makepyfile("""752 def pytest_funcarg__app(request):753 app = request.cached_setup(754 scope='session',755 setup=lambda: 0,756 teardown=lambda x: 3/x)757 return app758 def test_func(app):759 pass760 """)761 result = testdir.runpytest()762 assert result.ret != 0763 result.stdout.fnmatch_lines([764 "*3/x*",765 "*ZeroDivisionError*",766 ])767class TestFixtureUsages:768 def test_noargfixturedec(self, testdir):769 testdir.makepyfile("""770 import pytest771 @pytest.fixture772 def arg1():773 return 1774 def test_func(arg1):775 assert arg1 == 1776 """)777 reprec = testdir.inline_run()778 reprec.assertoutcome(passed=1)779 def test_receives_funcargs(self, testdir):780 testdir.makepyfile("""781 import pytest782 @pytest.fixture()783 def arg1():784 return 1785 @pytest.fixture()786 def arg2(arg1):787 return arg1 + 1788 def test_add(arg2):789 assert arg2 == 2790 def test_all(arg1, arg2):791 assert arg1 == 1792 assert arg2 == 2793 """)794 reprec = testdir.inline_run()795 reprec.assertoutcome(passed=2)796 def test_receives_funcargs_scope_mismatch(self, testdir):797 testdir.makepyfile("""798 import pytest799 @pytest.fixture(scope="function")800 def arg1():801 return 1802 @pytest.fixture(scope="module")803 def arg2(arg1):804 return arg1 + 1805 def test_add(arg2):806 assert arg2 == 2807 """)808 result = testdir.runpytest()809 result.stdout.fnmatch_lines([810 "*ScopeMismatch*involved factories*",811 "* def arg2*",812 "* def arg1*",813 "*1 error*"814 ])815 def test_receives_funcargs_scope_mismatch_issue660(self, testdir):816 testdir.makepyfile("""817 import pytest818 @pytest.fixture(scope="function")819 def arg1():820 return 1821 @pytest.fixture(scope="module")822 def arg2(arg1):823 return arg1 + 1824 def test_add(arg1, arg2):825 assert arg2 == 2826 """)827 result = testdir.runpytest()828 result.stdout.fnmatch_lines([829 "*ScopeMismatch*involved factories*",830 "* def arg2*",831 "*1 error*"832 ])833 def test_funcarg_parametrized_and_used_twice(self, testdir):834 testdir.makepyfile("""835 import pytest836 l = []837 @pytest.fixture(params=[1,2])838 def arg1(request):839 l.append(1)840 return request.param841 @pytest.fixture()842 def arg2(arg1):843 return arg1 + 1844 def test_add(arg1, arg2):845 assert arg2 == arg1 + 1846 assert len(l) == arg1847 """)848 result = testdir.runpytest()849 result.stdout.fnmatch_lines([850 "*2 passed*"851 ])852 def test_factory_uses_unknown_funcarg_as_dependency_error(self, testdir):853 testdir.makepyfile("""854 import pytest855 @pytest.fixture()856 def fail(missing):857 return858 @pytest.fixture()859 def call_fail(fail):860 return861 def test_missing(call_fail):862 pass863 """)864 result = testdir.runpytest()865 result.stdout.fnmatch_lines("""866 *pytest.fixture()*867 *def call_fail(fail)*868 *pytest.fixture()*869 *def fail*870 *fixture*'missing'*not found*871 """)872 def test_factory_setup_as_classes_fails(self, testdir):873 testdir.makepyfile("""874 import pytest875 class arg1:876 def __init__(self, request):877 self.x = 1878 arg1 = pytest.fixture()(arg1)879 """)880 reprec = testdir.inline_run()881 l = reprec.getfailedcollections()882 assert len(l) == 1883 def test_request_can_be_overridden(self, testdir):884 testdir.makepyfile("""885 import pytest886 @pytest.fixture()887 def request(request):888 request.a = 1889 return request890 def test_request(request):891 assert request.a == 1892 """)893 reprec = testdir.inline_run()894 reprec.assertoutcome(passed=1)895 def test_usefixtures_marker(self, testdir):896 testdir.makepyfile("""897 import pytest898 l = []899 @pytest.fixture(scope="class")900 def myfix(request):901 request.cls.hello = "world"902 l.append(1)903 class TestClass:904 def test_one(self):905 assert self.hello == "world"906 assert len(l) == 1907 def test_two(self):908 assert self.hello == "world"909 assert len(l) == 1910 pytest.mark.usefixtures("myfix")(TestClass)911 """)912 reprec = testdir.inline_run()913 reprec.assertoutcome(passed=2)914 def test_usefixtures_ini(self, testdir):915 testdir.makeini("""916 [pytest]917 usefixtures = myfix918 """)919 testdir.makeconftest("""920 import pytest921 @pytest.fixture(scope="class")922 def myfix(request):923 request.cls.hello = "world"924 """)925 testdir.makepyfile("""926 class TestClass:927 def test_one(self):928 assert self.hello == "world"929 def test_two(self):930 assert self.hello == "world"931 """)932 reprec = testdir.inline_run()933 reprec.assertoutcome(passed=2)934 def test_usefixtures_seen_in_showmarkers(self, testdir):935 result = testdir.runpytest("--markers")936 result.stdout.fnmatch_lines("""937 *usefixtures(fixturename1*mark tests*fixtures*938 """)939 def test_request_instance_issue203(self, testdir):940 testdir.makepyfile("""941 import pytest942 class TestClass:943 @pytest.fixture944 def setup1(self, request):945 assert self == request.instance946 self.arg1 = 1947 def test_hello(self, setup1):948 assert self.arg1 == 1949 """)950 reprec = testdir.inline_run()951 reprec.assertoutcome(passed=1)952 def test_fixture_parametrized_with_iterator(self, testdir):953 testdir.makepyfile("""954 import pytest955 l = []956 def f():957 yield 1958 yield 2959 dec = pytest.fixture(scope="module", params=f())960 @dec961 def arg(request):962 return request.param963 @dec964 def arg2(request):965 return request.param966 def test_1(arg):967 l.append(arg)968 def test_2(arg2):969 l.append(arg2*10)970 """)971 reprec = testdir.inline_run("-v")972 reprec.assertoutcome(passed=4)973 l = reprec.getcalls("pytest_runtest_call")[0].item.module.l974 assert l == [1,2, 10,20]975class TestFixtureManagerParseFactories:976 def pytest_funcarg__testdir(self, request):977 testdir = request.getfuncargvalue("testdir")978 testdir.makeconftest("""979 def pytest_funcarg__hello(request):980 return "conftest"981 def pytest_funcarg__fm(request):982 return request._fixturemanager983 def pytest_funcarg__item(request):984 return request._pyfuncitem985 """)986 return testdir987 def test_parsefactories_evil_objects_issue214(self, testdir):988 testdir.makepyfile("""989 class A:990 def __call__(self):991 pass992 def __getattr__(self, name):993 raise RuntimeError()994 a = A()995 def test_hello():996 pass997 """)998 reprec = testdir.inline_run()999 reprec.assertoutcome(passed=1, failed=0)1000 def test_parsefactories_conftest(self, testdir):1001 testdir.makepyfile("""1002 def test_hello(item, fm):1003 for name in ("fm", "hello", "item"):1004 faclist = fm.getfixturedefs(name, item.nodeid)1005 assert len(faclist) == 11006 fac = faclist[0]1007 assert fac.func.__name__ == "pytest_funcarg__" + name1008 """)1009 reprec = testdir.inline_run("-s")1010 reprec.assertoutcome(passed=1)1011 def test_parsefactories_conftest_and_module_and_class(self, testdir):1012 testdir.makepyfile("""1013 def pytest_funcarg__hello(request):1014 return "module"1015 class TestClass:1016 def pytest_funcarg__hello(self, request):1017 return "class"1018 def test_hello(self, item, fm):1019 faclist = fm.getfixturedefs("hello", item.nodeid)1020 print (faclist)1021 assert len(faclist) == 31022 assert faclist[0].func(item._request) == "conftest"1023 assert faclist[1].func(item._request) == "module"1024 assert faclist[2].func(item._request) == "class"1025 """)1026 reprec = testdir.inline_run("-s")1027 reprec.assertoutcome(passed=1)1028 def test_parsefactories_relative_node_ids(self, testdir):1029 # example mostly taken from:1030 # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html1031 runner = testdir.mkdir("runner")1032 package = testdir.mkdir("package")1033 package.join("conftest.py").write(dedent("""\1034 import pytest1035 @pytest.fixture1036 def one():1037 return 11038 """))1039 package.join("test_x.py").write(dedent("""\1040 def test_x(one):1041 assert one == 11042 """))1043 sub = package.mkdir("sub")1044 sub.join("__init__.py").ensure()1045 sub.join("conftest.py").write(dedent("""\1046 import pytest1047 @pytest.fixture1048 def one():1049 return 21050 """))1051 sub.join("test_y.py").write(dedent("""\1052 def test_x(one):1053 assert one == 21054 """))1055 reprec = testdir.inline_run()1056 reprec.assertoutcome(passed=2)1057 with runner.as_cwd():1058 reprec = testdir.inline_run("..")1059 reprec.assertoutcome(passed=2)1060class TestAutouseDiscovery:1061 def pytest_funcarg__testdir(self, testdir):1062 testdir.makeconftest("""1063 import pytest1064 @pytest.fixture(autouse=True)1065 def perfunction(request, tmpdir):1066 pass1067 @pytest.fixture()1068 def arg1(tmpdir):1069 pass1070 @pytest.fixture(autouse=True)1071 def perfunction2(arg1):1072 pass1073 def pytest_funcarg__fm(request):1074 return request._fixturemanager1075 def pytest_funcarg__item(request):1076 return request._pyfuncitem1077 """)1078 return testdir1079 def test_parsefactories_conftest(self, testdir):1080 testdir.makepyfile("""1081 from _pytest.pytester import get_public_names1082 def test_check_setup(item, fm):1083 autousenames = fm._getautousenames(item.nodeid)1084 assert len(get_public_names(autousenames)) == 21085 assert "perfunction2" in autousenames1086 assert "perfunction" in autousenames1087 """)1088 reprec = testdir.inline_run("-s")1089 reprec.assertoutcome(passed=1)1090 def test_two_classes_separated_autouse(self, testdir):1091 testdir.makepyfile("""1092 import pytest1093 class TestA:1094 l = []1095 @pytest.fixture(autouse=True)1096 def setup1(self):1097 self.l.append(1)1098 def test_setup1(self):1099 assert self.l == [1]1100 class TestB:1101 l = []1102 @pytest.fixture(autouse=True)1103 def setup2(self):1104 self.l.append(1)1105 def test_setup2(self):1106 assert self.l == [1]1107 """)1108 reprec = testdir.inline_run()1109 reprec.assertoutcome(passed=2)1110 def test_setup_at_classlevel(self, testdir):1111 testdir.makepyfile("""1112 import pytest1113 class TestClass:1114 @pytest.fixture(autouse=True)1115 def permethod(self, request):1116 request.instance.funcname = request.function.__name__1117 def test_method1(self):1118 assert self.funcname == "test_method1"1119 def test_method2(self):1120 assert self.funcname == "test_method2"1121 """)1122 reprec = testdir.inline_run("-s")1123 reprec.assertoutcome(passed=2)1124 @pytest.mark.xfail(reason="'enabled' feature not implemented")1125 def test_setup_enabled_functionnode(self, testdir):1126 testdir.makepyfile("""1127 import pytest1128 def enabled(parentnode, markers):1129 return "needsdb" in markers1130 @pytest.fixture(params=[1,2])1131 def db(request):1132 return request.param1133 @pytest.fixture(enabled=enabled, autouse=True)1134 def createdb(db):1135 pass1136 def test_func1(request):1137 assert "db" not in request.fixturenames1138 @pytest.mark.needsdb1139 def test_func2(request):1140 assert "db" in request.fixturenames1141 """)1142 reprec = testdir.inline_run("-s")1143 reprec.assertoutcome(passed=2)1144 def test_callables_nocode(self, testdir):1145 """1146 a imported mock.call would break setup/factory discovery1147 due to it being callable and __code__ not being a code object1148 """1149 testdir.makepyfile("""1150 class _call(tuple):1151 def __call__(self, *k, **kw):1152 pass1153 def __getattr__(self, k):1154 return self1155 call = _call()1156 """)1157 reprec = testdir.inline_run("-s")1158 reprec.assertoutcome(failed=0, passed=0)1159 def test_autouse_in_conftests(self, testdir):1160 a = testdir.mkdir("a")1161 b = testdir.mkdir("a1")1162 conftest = testdir.makeconftest("""1163 import pytest1164 @pytest.fixture(autouse=True)1165 def hello():1166 xxx1167 """)1168 conftest.move(a.join(conftest.basename))1169 a.join("test_something.py").write("def test_func(): pass")1170 b.join("test_otherthing.py").write("def test_func(): pass")1171 result = testdir.runpytest()1172 result.stdout.fnmatch_lines("""1173 *1 passed*1 error*1174 """)1175 def test_autouse_in_module_and_two_classes(self, testdir):1176 testdir.makepyfile("""1177 import pytest1178 l = []1179 @pytest.fixture(autouse=True)1180 def append1():1181 l.append("module")1182 def test_x():1183 assert l == ["module"]1184 class TestA:1185 @pytest.fixture(autouse=True)1186 def append2(self):1187 l.append("A")1188 def test_hello(self):1189 assert l == ["module", "module", "A"], l1190 class TestA2:1191 def test_world(self):1192 assert l == ["module", "module", "A", "module"], l1193 """)1194 reprec = testdir.inline_run()1195 reprec.assertoutcome(passed=3)1196class TestAutouseManagement:1197 def test_autouse_conftest_mid_directory(self, testdir):1198 pkgdir = testdir.mkpydir("xyz123")1199 pkgdir.join("conftest.py").write(_pytest._code.Source("""1200 import pytest1201 @pytest.fixture(autouse=True)1202 def app():1203 import sys1204 sys._myapp = "hello"1205 """))1206 t = pkgdir.ensure("tests", "test_app.py")1207 t.write(_pytest._code.Source("""1208 import sys1209 def test_app():1210 assert sys._myapp == "hello"1211 """))1212 reprec = testdir.inline_run("-s")1213 reprec.assertoutcome(passed=1)1214 def test_autouse_honored_for_yield(self, testdir):1215 testdir.makepyfile("""1216 import pytest1217 @pytest.fixture(autouse=True)1218 def tst():1219 global x1220 x = 31221 def test_gen():1222 def f(hello):1223 assert x == abs(hello)1224 yield f, 31225 yield f, -31226 """)1227 reprec = testdir.inline_run()1228 reprec.assertoutcome(passed=2)1229 def test_funcarg_and_setup(self, testdir):1230 testdir.makepyfile("""1231 import pytest1232 l = []1233 @pytest.fixture(scope="module")1234 def arg():1235 l.append(1)1236 return 01237 @pytest.fixture(scope="module", autouse=True)1238 def something(arg):1239 l.append(2)1240 def test_hello(arg):1241 assert len(l) == 21242 assert l == [1,2]1243 assert arg == 01244 def test_hello2(arg):1245 assert len(l) == 21246 assert l == [1,2]1247 assert arg == 01248 """)1249 reprec = testdir.inline_run()1250 reprec.assertoutcome(passed=2)1251 def test_uses_parametrized_resource(self, testdir):1252 testdir.makepyfile("""1253 import pytest1254 l = []1255 @pytest.fixture(params=[1,2])1256 def arg(request):1257 return request.param1258 @pytest.fixture(autouse=True)1259 def something(arg):1260 l.append(arg)1261 def test_hello():1262 if len(l) == 1:1263 assert l == [1]1264 elif len(l) == 2:1265 assert l == [1, 2]1266 else:1267 0/01268 """)1269 reprec = testdir.inline_run("-s")1270 reprec.assertoutcome(passed=2)1271 def test_session_parametrized_function(self, testdir):1272 testdir.makepyfile("""1273 import pytest1274 l = []1275 @pytest.fixture(scope="session", params=[1,2])1276 def arg(request):1277 return request.param1278 @pytest.fixture(scope="function", autouse=True)1279 def append(request, arg):1280 if request.function.__name__ == "test_some":1281 l.append(arg)1282 def test_some():1283 pass1284 def test_result(arg):1285 assert len(l) == arg1286 assert l[:arg] == [1,2][:arg]1287 """)1288 reprec = testdir.inline_run("-v", "-s")1289 reprec.assertoutcome(passed=4)1290 def test_class_function_parametrization_finalization(self, testdir):1291 p = testdir.makeconftest("""1292 import pytest1293 import pprint1294 l = []1295 @pytest.fixture(scope="function", params=[1,2])1296 def farg(request):1297 return request.param1298 @pytest.fixture(scope="class", params=list("ab"))1299 def carg(request):1300 return request.param1301 @pytest.fixture(scope="function", autouse=True)1302 def append(request, farg, carg):1303 def fin():1304 l.append("fin_%s%s" % (carg, farg))1305 request.addfinalizer(fin)1306 """)1307 testdir.makepyfile("""1308 import pytest1309 class TestClass:1310 def test_1(self):1311 pass1312 class TestClass2:1313 def test_2(self):1314 pass1315 """)1316 reprec = testdir.inline_run("-v","-s")1317 reprec.assertoutcome(passed=8)1318 config = reprec.getcalls("pytest_unconfigure")[0].config1319 l = config.pluginmanager._getconftestmodules(p)[0].l1320 assert l == ["fin_a1", "fin_a2", "fin_b1", "fin_b2"] * 21321 def test_scope_ordering(self, testdir):1322 testdir.makepyfile("""1323 import pytest1324 l = []1325 @pytest.fixture(scope="function", autouse=True)1326 def fappend2():1327 l.append(2)1328 @pytest.fixture(scope="class", autouse=True)1329 def classappend3():1330 l.append(3)1331 @pytest.fixture(scope="module", autouse=True)1332 def mappend():1333 l.append(1)1334 class TestHallo:1335 def test_method(self):1336 assert l == [1,3,2]1337 """)1338 reprec = testdir.inline_run()1339 reprec.assertoutcome(passed=1)1340 def test_parametrization_setup_teardown_ordering(self, testdir):1341 testdir.makepyfile("""1342 import pytest1343 l = []1344 def pytest_generate_tests(metafunc):1345 if metafunc.cls is not None:1346 metafunc.parametrize("item", [1,2], scope="class")1347 class TestClass:1348 @pytest.fixture(scope="class", autouse=True)1349 def addteardown(self, item, request):1350 l.append("setup-%d" % item)1351 request.addfinalizer(lambda: l.append("teardown-%d" % item))1352 def test_step1(self, item):1353 l.append("step1-%d" % item)1354 def test_step2(self, item):1355 l.append("step2-%d" % item)1356 def test_finish():1357 print (l)1358 assert l == ["setup-1", "step1-1", "step2-1", "teardown-1",1359 "setup-2", "step1-2", "step2-2", "teardown-2",]1360 """)1361 reprec = testdir.inline_run()1362 reprec.assertoutcome(passed=5)1363 def test_ordering_autouse_before_explicit(self, testdir):1364 testdir.makepyfile("""1365 import pytest1366 l = []1367 @pytest.fixture(autouse=True)1368 def fix1():1369 l.append(1)1370 @pytest.fixture()1371 def arg1():1372 l.append(2)1373 def test_hello(arg1):1374 assert l == [1,2]1375 """)1376 reprec = testdir.inline_run()1377 reprec.assertoutcome(passed=1)1378 @pytest.mark.issue2261379 @pytest.mark.parametrize("param1", ["", "params=[1]"], ids=["p00","p01"])1380 @pytest.mark.parametrize("param2", ["", "params=[1]"], ids=["p10","p11"])1381 def test_ordering_dependencies_torndown_first(self, testdir, param1, param2):1382 testdir.makepyfile("""1383 import pytest1384 l = []1385 @pytest.fixture(%(param1)s)1386 def arg1(request):1387 request.addfinalizer(lambda: l.append("fin1"))1388 l.append("new1")1389 @pytest.fixture(%(param2)s)1390 def arg2(request, arg1):1391 request.addfinalizer(lambda: l.append("fin2"))1392 l.append("new2")1393 def test_arg(arg2):1394 pass1395 def test_check():1396 assert l == ["new1", "new2", "fin2", "fin1"]1397 """ % locals())1398 reprec = testdir.inline_run("-s")1399 reprec.assertoutcome(passed=2)1400class TestFixtureMarker:1401 def test_parametrize(self, testdir):1402 testdir.makepyfile("""1403 import pytest1404 @pytest.fixture(params=["a", "b", "c"])1405 def arg(request):1406 return request.param1407 l = []1408 def test_param(arg):1409 l.append(arg)1410 def test_result():1411 assert l == list("abc")1412 """)1413 reprec = testdir.inline_run()1414 reprec.assertoutcome(passed=4)1415 def test_multiple_parametrization_issue_736(self, testdir):1416 testdir.makepyfile("""1417 import pytest1418 @pytest.fixture(params=[1,2,3])1419 def foo(request):1420 return request.param1421 @pytest.mark.parametrize('foobar', [4,5,6])1422 def test_issue(foo, foobar):1423 assert foo in [1,2,3]1424 assert foobar in [4,5,6]1425 """)1426 reprec = testdir.inline_run()1427 reprec.assertoutcome(passed=9)1428 @pytest.mark.parametrize('param_args', ["'fixt, val'", "'fixt,val'", "['fixt', 'val']", "('fixt', 'val')"])1429 def test_override_parametrized_fixture_issue_979(self, testdir, param_args):1430 """Make sure a parametrized argument can override a parametrized fixture.1431 This was a regression introduced in the fix for #736.1432 """1433 testdir.makepyfile("""1434 import pytest1435 @pytest.fixture(params=[1, 2])1436 def fixt(request):1437 return request.param1438 @pytest.mark.parametrize(%s, [(3, 'x'), (4, 'x')])1439 def test_foo(fixt, val):1440 pass1441 """ % param_args)1442 reprec = testdir.inline_run()1443 reprec.assertoutcome(passed=2)1444 def test_scope_session(self, testdir):1445 testdir.makepyfile("""1446 import pytest1447 l = []1448 @pytest.fixture(scope="module")1449 def arg():1450 l.append(1)1451 return 11452 def test_1(arg):1453 assert arg == 11454 def test_2(arg):1455 assert arg == 11456 assert len(l) == 11457 class TestClass:1458 def test3(self, arg):1459 assert arg == 11460 assert len(l) == 11461 """)1462 reprec = testdir.inline_run()1463 reprec.assertoutcome(passed=3)1464 def test_scope_session_exc(self, testdir):1465 testdir.makepyfile("""1466 import pytest1467 l = []1468 @pytest.fixture(scope="session")1469 def fix():1470 l.append(1)1471 pytest.skip('skipping')1472 def test_1(fix):1473 pass1474 def test_2(fix):1475 pass1476 def test_last():1477 assert l == [1]1478 """)1479 reprec = testdir.inline_run()1480 reprec.assertoutcome(skipped=2, passed=1)1481 def test_scope_session_exc_two_fix(self, testdir):1482 testdir.makepyfile("""1483 import pytest1484 l = []1485 m = []1486 @pytest.fixture(scope="session")1487 def a():1488 l.append(1)1489 pytest.skip('skipping')1490 @pytest.fixture(scope="session")1491 def b(a):1492 m.append(1)1493 def test_1(b):1494 pass1495 def test_2(b):1496 pass1497 def test_last():1498 assert l == [1]1499 assert m == []1500 """)1501 reprec = testdir.inline_run()1502 reprec.assertoutcome(skipped=2, passed=1)1503 def test_scope_exc(self, testdir):1504 testdir.makepyfile(1505 test_foo="""1506 def test_foo(fix):1507 pass1508 """,1509 test_bar="""1510 def test_bar(fix):1511 pass1512 """,1513 conftest="""1514 import pytest1515 reqs = []1516 @pytest.fixture(scope="session")1517 def fix(request):1518 reqs.append(1)1519 pytest.skip()1520 @pytest.fixture1521 def req_list():1522 return reqs1523 """,1524 test_real="""1525 def test_last(req_list):1526 assert req_list == [1]1527 """1528 )1529 reprec = testdir.inline_run()1530 reprec.assertoutcome(skipped=2, passed=1)1531 def test_scope_module_uses_session(self, testdir):1532 testdir.makepyfile("""1533 import pytest1534 l = []1535 @pytest.fixture(scope="module")1536 def arg():1537 l.append(1)1538 return 11539 def test_1(arg):1540 assert arg == 11541 def test_2(arg):1542 assert arg == 11543 assert len(l) == 11544 class TestClass:1545 def test3(self, arg):1546 assert arg == 11547 assert len(l) == 11548 """)1549 reprec = testdir.inline_run()1550 reprec.assertoutcome(passed=3)1551 def test_scope_module_and_finalizer(self, testdir):1552 testdir.makeconftest("""1553 import pytest1554 finalized = []1555 created = []1556 @pytest.fixture(scope="module")1557 def arg(request):1558 created.append(1)1559 assert request.scope == "module"1560 request.addfinalizer(lambda: finalized.append(1))1561 def pytest_funcarg__created(request):1562 return len(created)1563 def pytest_funcarg__finalized(request):1564 return len(finalized)1565 """)1566 testdir.makepyfile(1567 test_mod1="""1568 def test_1(arg, created, finalized):1569 assert created == 11570 assert finalized == 01571 def test_2(arg, created, finalized):1572 assert created == 11573 assert finalized == 0""",1574 test_mod2="""1575 def test_3(arg, created, finalized):1576 assert created == 21577 assert finalized == 1""",1578 test_mode3="""1579 def test_4(arg, created, finalized):1580 assert created == 31581 assert finalized == 21582 """)1583 reprec = testdir.inline_run()1584 reprec.assertoutcome(passed=4)1585 @pytest.mark.parametrize("method", [1586 'request.getfuncargvalue("arg")',1587 'request.cached_setup(lambda: None, scope="function")',1588 ], ids=["getfuncargvalue", "cached_setup"])1589 def test_scope_mismatch_various(self, testdir, method):1590 testdir.makeconftest("""1591 import pytest1592 finalized = []1593 created = []1594 @pytest.fixture(scope="function")1595 def arg(request):1596 pass1597 """)1598 testdir.makepyfile(1599 test_mod1="""1600 import pytest1601 @pytest.fixture(scope="session")1602 def arg(request):1603 %s1604 def test_1(arg):1605 pass1606 """ % method)1607 result = testdir.runpytest()1608 assert result.ret != 01609 result.stdout.fnmatch_lines([1610 "*ScopeMismatch*You tried*function*session*request*",1611 ])1612 def test_register_only_with_mark(self, testdir):1613 testdir.makeconftest("""1614 import pytest1615 @pytest.fixture()1616 def arg():1617 return 11618 """)1619 testdir.makepyfile(1620 test_mod1="""1621 import pytest1622 @pytest.fixture()1623 def arg(arg):1624 return arg + 11625 def test_1(arg):1626 assert arg == 21627 """)1628 reprec = testdir.inline_run()1629 reprec.assertoutcome(passed=1)1630 def test_parametrize_and_scope(self, testdir):1631 testdir.makepyfile("""1632 import pytest1633 @pytest.fixture(scope="module", params=["a", "b", "c"])1634 def arg(request):1635 return request.param1636 l = []1637 def test_param(arg):1638 l.append(arg)1639 """)1640 reprec = testdir.inline_run("-v")1641 reprec.assertoutcome(passed=3)1642 l = reprec.getcalls("pytest_runtest_call")[0].item.module.l1643 assert len(l) == 31644 assert "a" in l1645 assert "b" in l1646 assert "c" in l1647 def test_scope_mismatch(self, testdir):1648 testdir.makeconftest("""1649 import pytest1650 @pytest.fixture(scope="function")1651 def arg(request):1652 pass1653 """)1654 testdir.makepyfile("""1655 import pytest1656 @pytest.fixture(scope="session")1657 def arg(arg):1658 pass1659 def test_mismatch(arg):1660 pass1661 """)1662 result = testdir.runpytest()1663 result.stdout.fnmatch_lines([1664 "*ScopeMismatch*",1665 "*1 error*",1666 ])1667 def test_parametrize_separated_order(self, testdir):1668 testdir.makepyfile("""1669 import pytest1670 @pytest.fixture(scope="module", params=[1, 2])1671 def arg(request):1672 return request.param1673 l = []1674 def test_1(arg):1675 l.append(arg)1676 def test_2(arg):1677 l.append(arg)1678 """)1679 reprec = testdir.inline_run("-v")1680 reprec.assertoutcome(passed=4)1681 l = reprec.getcalls("pytest_runtest_call")[0].item.module.l1682 assert l == [1,1,2,2]1683 def test_module_parametrized_ordering(self, testdir):1684 testdir.makeconftest("""1685 import pytest1686 @pytest.fixture(scope="session", params="s1 s2".split())1687 def sarg():1688 pass1689 @pytest.fixture(scope="module", params="m1 m2".split())1690 def marg():1691 pass1692 """)1693 testdir.makepyfile(test_mod1="""1694 def test_func(sarg):1695 pass1696 def test_func1(marg):1697 pass1698 """, test_mod2="""1699 def test_func2(sarg):1700 pass1701 def test_func3(sarg, marg):1702 pass1703 def test_func3b(sarg, marg):1704 pass1705 def test_func4(marg):1706 pass1707 """)1708 result = testdir.runpytest("-v")1709 result.stdout.fnmatch_lines("""1710 test_mod1.py::test_func[s1] PASSED1711 test_mod2.py::test_func2[s1] PASSED1712 test_mod2.py::test_func3[s1-m1] PASSED1713 test_mod2.py::test_func3b[s1-m1] PASSED1714 test_mod2.py::test_func3[s1-m2] PASSED1715 test_mod2.py::test_func3b[s1-m2] PASSED1716 test_mod1.py::test_func[s2] PASSED1717 test_mod2.py::test_func2[s2] PASSED1718 test_mod2.py::test_func3[s2-m1] PASSED1719 test_mod2.py::test_func3b[s2-m1] PASSED1720 test_mod2.py::test_func4[m1] PASSED1721 test_mod2.py::test_func3[s2-m2] PASSED1722 test_mod2.py::test_func3b[s2-m2] PASSED1723 test_mod2.py::test_func4[m2] PASSED1724 test_mod1.py::test_func1[m1] PASSED1725 test_mod1.py::test_func1[m2] PASSED1726 """)1727 def test_class_ordering(self, testdir):1728 testdir.makeconftest("""1729 import pytest1730 l = []1731 @pytest.fixture(scope="function", params=[1,2])1732 def farg(request):1733 return request.param1734 @pytest.fixture(scope="class", params=list("ab"))1735 def carg(request):1736 return request.param1737 @pytest.fixture(scope="function", autouse=True)1738 def append(request, farg, carg):1739 def fin():1740 l.append("fin_%s%s" % (carg, farg))1741 request.addfinalizer(fin)1742 """)1743 testdir.makepyfile("""1744 import pytest1745 class TestClass2:1746 def test_1(self):1747 pass1748 def test_2(self):1749 pass1750 class TestClass:1751 def test_3(self):1752 pass1753 """)1754 result = testdir.runpytest("-vs")1755 result.stdout.fnmatch_lines("""1756 test_class_ordering.py::TestClass2::test_1[1-a] PASSED1757 test_class_ordering.py::TestClass2::test_1[2-a] PASSED1758 test_class_ordering.py::TestClass2::test_2[1-a] PASSED1759 test_class_ordering.py::TestClass2::test_2[2-a] PASSED1760 test_class_ordering.py::TestClass2::test_1[1-b] PASSED1761 test_class_ordering.py::TestClass2::test_1[2-b] PASSED1762 test_class_ordering.py::TestClass2::test_2[1-b] PASSED1763 test_class_ordering.py::TestClass2::test_2[2-b] PASSED1764 test_class_ordering.py::TestClass::test_3[1-a] PASSED1765 test_class_ordering.py::TestClass::test_3[2-a] PASSED1766 test_class_ordering.py::TestClass::test_3[1-b] PASSED1767 test_class_ordering.py::TestClass::test_3[2-b] PASSED1768 """)1769 def test_parametrize_separated_order_higher_scope_first(self, testdir):1770 testdir.makepyfile("""1771 import pytest1772 @pytest.fixture(scope="function", params=[1, 2])1773 def arg(request):1774 param = request.param1775 request.addfinalizer(lambda: l.append("fin:%s" % param))1776 l.append("create:%s" % param)1777 return request.param1778 @pytest.fixture(scope="module", params=["mod1", "mod2"])1779 def modarg(request):1780 param = request.param1781 request.addfinalizer(lambda: l.append("fin:%s" % param))1782 l.append("create:%s" % param)1783 return request.param1784 l = []1785 def test_1(arg):1786 l.append("test1")1787 def test_2(modarg):1788 l.append("test2")1789 def test_3(arg, modarg):1790 l.append("test3")1791 def test_4(modarg, arg):1792 l.append("test4")1793 """)1794 reprec = testdir.inline_run("-v")1795 reprec.assertoutcome(passed=12)1796 l = reprec.getcalls("pytest_runtest_call")[0].item.module.l1797 expected = [1798 'create:1', 'test1', 'fin:1', 'create:2', 'test1',1799 'fin:2', 'create:mod1', 'test2', 'create:1', 'test3',1800 'fin:1', 'create:2', 'test3', 'fin:2', 'create:1',1801 'test4', 'fin:1', 'create:2', 'test4', 'fin:2',1802 'fin:mod1', 'create:mod2', 'test2', 'create:1', 'test3',1803 'fin:1', 'create:2', 'test3', 'fin:2', 'create:1',1804 'test4', 'fin:1', 'create:2', 'test4', 'fin:2',1805 'fin:mod2']1806 import pprint1807 pprint.pprint(list(zip(l, expected)))1808 assert l == expected1809 def test_parametrized_fixture_teardown_order(self, testdir):1810 testdir.makepyfile("""1811 import pytest1812 @pytest.fixture(params=[1,2], scope="class")1813 def param1(request):1814 return request.param1815 l = []1816 class TestClass:1817 @classmethod1818 @pytest.fixture(scope="class", autouse=True)1819 def setup1(self, request, param1):1820 l.append(1)1821 request.addfinalizer(self.teardown1)1822 @classmethod1823 def teardown1(self):1824 assert l.pop() == 11825 @pytest.fixture(scope="class", autouse=True)1826 def setup2(self, request, param1):1827 l.append(2)1828 request.addfinalizer(self.teardown2)1829 @classmethod1830 def teardown2(self):1831 assert l.pop() == 21832 def test(self):1833 pass1834 def test_finish():1835 assert not l1836 """)1837 result = testdir.runpytest("-v")1838 result.stdout.fnmatch_lines("""1839 *3 passed*1840 """)1841 assert "error" not in result.stdout.str()1842 def test_fixture_finalizer(self, testdir):1843 testdir.makeconftest("""1844 import pytest1845 import sys1846 @pytest.fixture1847 def browser(request):1848 def finalize():1849 sys.stdout.write('Finalized')1850 request.addfinalizer(finalize)1851 return {}1852 """)1853 b = testdir.mkdir("subdir")1854 b.join("test_overriden_fixture_finalizer.py").write(dedent("""1855 import pytest1856 @pytest.fixture1857 def browser(browser):1858 browser['visited'] = True1859 return browser1860 def test_browser(browser):1861 assert browser['visited'] is True1862 """))1863 reprec = testdir.runpytest("-s")1864 for test in ['test_browser']:1865 reprec.stdout.fnmatch_lines('*Finalized*')1866 def test_class_scope_with_normal_tests(self, testdir):1867 testpath = testdir.makepyfile("""1868 import pytest1869 class Box:1870 value = 01871 @pytest.fixture(scope='class')1872 def a(request):1873 Box.value += 11874 return Box.value1875 def test_a(a):1876 assert a == 11877 class Test1:1878 def test_b(self, a):1879 assert a == 21880 class Test2:1881 def test_c(self, a):1882 assert a == 3""")1883 reprec = testdir.inline_run(testpath)1884 for test in ['test_a', 'test_b', 'test_c']:1885 assert reprec.matchreport(test).passed1886 def test_request_is_clean(self, testdir):1887 testdir.makepyfile("""1888 import pytest1889 l = []1890 @pytest.fixture(params=[1, 2])1891 def fix(request):1892 request.addfinalizer(lambda: l.append(request.param))1893 def test_fix(fix):1894 pass1895 """)1896 reprec = testdir.inline_run("-s")1897 l = reprec.getcalls("pytest_runtest_call")[0].item.module.l1898 assert l == [1,2]1899 def test_parametrize_separated_lifecycle(self, testdir):1900 testdir.makepyfile("""1901 import pytest1902 l = []1903 @pytest.fixture(scope="module", params=[1, 2])1904 def arg(request):1905 x = request.param1906 request.addfinalizer(lambda: l.append("fin%s" % x))1907 return request.param1908 def test_1(arg):1909 l.append(arg)1910 def test_2(arg):1911 l.append(arg)1912 """)1913 reprec = testdir.inline_run("-vs")1914 reprec.assertoutcome(passed=4)1915 l = reprec.getcalls("pytest_runtest_call")[0].item.module.l1916 import pprint1917 pprint.pprint(l)1918 #assert len(l) == 61919 assert l[0] == l[1] == 11920 assert l[2] == "fin1"1921 assert l[3] == l[4] == 21922 assert l[5] == "fin2"1923 def test_parametrize_function_scoped_finalizers_called(self, testdir):1924 testdir.makepyfile("""1925 import pytest1926 @pytest.fixture(scope="function", params=[1, 2])1927 def arg(request):1928 x = request.param1929 request.addfinalizer(lambda: l.append("fin%s" % x))1930 return request.param1931 l = []1932 def test_1(arg):1933 l.append(arg)1934 def test_2(arg):1935 l.append(arg)1936 def test_3():1937 assert len(l) == 81938 assert l == [1, "fin1", 2, "fin2", 1, "fin1", 2, "fin2"]1939 """)1940 reprec = testdir.inline_run("-v")1941 reprec.assertoutcome(passed=5)1942 @pytest.mark.issue2461943 @pytest.mark.parametrize("scope", ["session", "function", "module"])1944 def test_finalizer_order_on_parametrization(self, scope, testdir):1945 testdir.makepyfile("""1946 import pytest1947 l = []1948 @pytest.fixture(scope=%(scope)r, params=["1"])1949 def fix1(request):1950 return request.param1951 @pytest.fixture(scope=%(scope)r)1952 def fix2(request, base):1953 def cleanup_fix2():1954 assert not l, "base should not have been finalized"1955 request.addfinalizer(cleanup_fix2)1956 @pytest.fixture(scope=%(scope)r)1957 def base(request, fix1):1958 def cleanup_base():1959 l.append("fin_base")1960 print ("finalizing base")1961 request.addfinalizer(cleanup_base)1962 def test_begin():1963 pass1964 def test_baz(base, fix2):1965 pass1966 def test_other():1967 pass1968 """ % {"scope": scope})1969 reprec = testdir.inline_run("-lvs")1970 reprec.assertoutcome(passed=3)1971 @pytest.mark.issue3961972 def test_class_scope_parametrization_ordering(self, testdir):1973 testdir.makepyfile("""1974 import pytest1975 l = []1976 @pytest.fixture(params=["John", "Doe"], scope="class")1977 def human(request):1978 request.addfinalizer(lambda: l.append("fin %s" % request.param))1979 return request.param1980 class TestGreetings:1981 def test_hello(self, human):1982 l.append("test_hello")1983 class TestMetrics:1984 def test_name(self, human):1985 l.append("test_name")1986 def test_population(self, human):1987 l.append("test_population")1988 """)1989 reprec = testdir.inline_run()1990 reprec.assertoutcome(passed=6)1991 l = reprec.getcalls("pytest_runtest_call")[0].item.module.l1992 assert l == ["test_hello", "fin John", "test_hello", "fin Doe",1993 "test_name", "test_population", "fin John",1994 "test_name", "test_population", "fin Doe"]1995 def test_parametrize_setup_function(self, testdir):1996 testdir.makepyfile("""1997 import pytest1998 @pytest.fixture(scope="module", params=[1, 2])1999 def arg(request):2000 return request.param2001 @pytest.fixture(scope="module", autouse=True)2002 def mysetup(request, arg):2003 request.addfinalizer(lambda: l.append("fin%s" % arg))2004 l.append("setup%s" % arg)2005 l = []2006 def test_1(arg):2007 l.append(arg)2008 def test_2(arg):2009 l.append(arg)2010 def test_3():2011 import pprint2012 pprint.pprint(l)2013 if arg == 1:2014 assert l == ["setup1", 1, 1, ]2015 elif arg == 2:2016 assert l == ["setup1", 1, 1, "fin1",2017 "setup2", 2, 2, ]2018 """)2019 reprec = testdir.inline_run("-v")2020 reprec.assertoutcome(passed=6)2021 def test_fixture_marked_function_not_collected_as_test(self, testdir):2022 testdir.makepyfile("""2023 import pytest2024 @pytest.fixture2025 def test_app():2026 return 12027 def test_something(test_app):2028 assert test_app == 12029 """)2030 reprec = testdir.inline_run()2031 reprec.assertoutcome(passed=1)2032 def test_params_and_ids(self, testdir):2033 testdir.makepyfile("""2034 import pytest2035 @pytest.fixture(params=[object(), object()],2036 ids=['alpha', 'beta'])2037 def fix(request):2038 return request.param2039 def test_foo(fix):2040 assert 12041 """)2042 res = testdir.runpytest('-v')2043 res.stdout.fnmatch_lines([2044 '*test_foo*alpha*',2045 '*test_foo*beta*'])2046 def test_params_and_ids_yieldfixture(self, testdir):2047 testdir.makepyfile("""2048 import pytest2049 @pytest.yield_fixture(params=[object(), object()],2050 ids=['alpha', 'beta'])2051 def fix(request):2052 yield request.param2053 def test_foo(fix):2054 assert 12055 """)2056 res = testdir.runpytest('-v')2057 res.stdout.fnmatch_lines([2058 '*test_foo*alpha*',2059 '*test_foo*beta*'])2060class TestRequestScopeAccess:2061 pytestmark = pytest.mark.parametrize(("scope", "ok", "error"),[2062 ["session", "", "fspath class function module"],2063 ["module", "module fspath", "cls function"],2064 ["class", "module fspath cls", "function"],2065 ["function", "module fspath cls function", ""]2066 ])2067 def test_setup(self, testdir, scope, ok, error):2068 testdir.makepyfile("""2069 import pytest2070 @pytest.fixture(scope=%r, autouse=True)2071 def myscoped(request):2072 for x in %r:2073 assert hasattr(request, x)2074 for x in %r:2075 pytest.raises(AttributeError, lambda:2076 getattr(request, x))2077 assert request.session2078 assert request.config2079 def test_func():2080 pass2081 """ %(scope, ok.split(), error.split()))2082 reprec = testdir.inline_run("-l")2083 reprec.assertoutcome(passed=1)2084 def test_funcarg(self, testdir, scope, ok, error):2085 testdir.makepyfile("""2086 import pytest2087 @pytest.fixture(scope=%r)2088 def arg(request):2089 for x in %r:2090 assert hasattr(request, x)2091 for x in %r:2092 pytest.raises(AttributeError, lambda:2093 getattr(request, x))2094 assert request.session2095 assert request.config2096 def test_func(arg):2097 pass2098 """ %(scope, ok.split(), error.split()))2099 reprec = testdir.inline_run()2100 reprec.assertoutcome(passed=1)2101class TestErrors:2102 def test_subfactory_missing_funcarg(self, testdir):2103 testdir.makepyfile("""2104 import pytest2105 @pytest.fixture()2106 def gen(qwe123):2107 return 12108 def test_something(gen):2109 pass2110 """)2111 result = testdir.runpytest()2112 assert result.ret != 02113 result.stdout.fnmatch_lines([2114 "*def gen(qwe123):*",2115 "*fixture*qwe123*not found*",2116 "*1 error*",2117 ])2118 def test_issue498_fixture_finalizer_failing(self, testdir):2119 testdir.makepyfile("""2120 import pytest2121 @pytest.fixture2122 def fix1(request):2123 def f():2124 raise KeyError2125 request.addfinalizer(f)2126 return object()2127 l = []2128 def test_1(fix1):2129 l.append(fix1)2130 def test_2(fix1):2131 l.append(fix1)2132 def test_3():2133 assert l[0] != l[1]2134 """)2135 result = testdir.runpytest()2136 result.stdout.fnmatch_lines("""2137 *ERROR*teardown*test_1*2138 *KeyError*2139 *ERROR*teardown*test_2*2140 *KeyError*2141 *3 pass*2 error*2142 """)2143 def test_setupfunc_missing_funcarg(self, testdir):2144 testdir.makepyfile("""2145 import pytest2146 @pytest.fixture(autouse=True)2147 def gen(qwe123):2148 return 12149 def test_something():2150 pass2151 """)2152 result = testdir.runpytest()2153 assert result.ret != 02154 result.stdout.fnmatch_lines([2155 "*def gen(qwe123):*",2156 "*fixture*qwe123*not found*",2157 "*1 error*",2158 ])2159class TestShowFixtures:2160 def test_funcarg_compat(self, testdir):2161 config = testdir.parseconfigure("--funcargs")2162 assert config.option.showfixtures2163 def test_show_fixtures(self, testdir):2164 result = testdir.runpytest("--fixtures")2165 result.stdout.fnmatch_lines([2166 "*tmpdir*",2167 "*temporary directory*",2168 ]2169 )2170 def test_show_fixtures_verbose(self, testdir):2171 result = testdir.runpytest("--fixtures", "-v")2172 result.stdout.fnmatch_lines([2173 "*tmpdir*--*tmpdir.py*",2174 "*temporary directory*",2175 ]2176 )2177 def test_show_fixtures_testmodule(self, testdir):2178 p = testdir.makepyfile('''2179 import pytest2180 @pytest.fixture2181 def _arg0():2182 """ hidden """2183 @pytest.fixture2184 def arg1():2185 """ hello world """2186 ''')2187 result = testdir.runpytest("--fixtures", p)2188 result.stdout.fnmatch_lines("""2189 *tmpdir2190 *fixtures defined from*2191 *arg1*2192 *hello world*2193 """)2194 assert "arg0" not in result.stdout.str()2195 @pytest.mark.parametrize("testmod", [True, False])2196 def test_show_fixtures_conftest(self, testdir, testmod):2197 testdir.makeconftest('''2198 import pytest2199 @pytest.fixture2200 def arg1():2201 """ hello world """2202 ''')2203 if testmod:2204 testdir.makepyfile("""2205 def test_hello():2206 pass2207 """)2208 result = testdir.runpytest("--fixtures")2209 result.stdout.fnmatch_lines("""2210 *tmpdir*2211 *fixtures defined from*conftest*2212 *arg1*2213 *hello world*2214 """)2215 def test_show_fixtures_trimmed_doc(self, testdir):2216 p = testdir.makepyfile('''2217 import pytest2218 @pytest.fixture2219 def arg1():2220 """2221 line12222 line22223 """2224 @pytest.fixture2225 def arg2():2226 """2227 line12228 line22229 """2230 ''')2231 result = testdir.runpytest("--fixtures", p)2232 result.stdout.fnmatch_lines("""2233 * fixtures defined from test_show_fixtures_trimmed_doc *2234 arg22235 line12236 line22237 arg12238 line12239 line22240 """)2241 def test_show_fixtures_different_files(self, testdir):2242 """2243 #833: --fixtures only shows fixtures from first file2244 """2245 testdir.makepyfile(test_a='''2246 import pytest2247 @pytest.fixture2248 def fix_a():2249 """Fixture A"""2250 pass2251 def test_a(fix_a):2252 pass2253 ''')2254 testdir.makepyfile(test_b='''2255 import pytest2256 @pytest.fixture2257 def fix_b():2258 """Fixture B"""2259 pass2260 def test_b(fix_b):2261 pass2262 ''')2263 result = testdir.runpytest("--fixtures")2264 result.stdout.fnmatch_lines("""2265 * fixtures defined from test_a *2266 fix_a2267 Fixture A2268 * fixtures defined from test_b *2269 fix_b2270 Fixture B2271 """)2272class TestContextManagerFixtureFuncs:2273 def test_simple(self, testdir):2274 testdir.makepyfile("""2275 import pytest2276 @pytest.yield_fixture2277 def arg1():2278 print ("setup")2279 yield 12280 print ("teardown")2281 def test_1(arg1):2282 print ("test1 %s" % arg1)2283 def test_2(arg1):2284 print ("test2 %s" % arg1)2285 assert 02286 """)2287 result = testdir.runpytest("-s")2288 result.stdout.fnmatch_lines("""2289 *setup*2290 *test1 1*2291 *teardown*2292 *setup*2293 *test2 1*2294 *teardown*2295 """)2296 def test_scoped(self, testdir):2297 testdir.makepyfile("""2298 import pytest2299 @pytest.yield_fixture(scope="module")2300 def arg1():2301 print ("setup")2302 yield 12303 print ("teardown")2304 def test_1(arg1):2305 print ("test1 %s" % arg1)2306 def test_2(arg1):2307 print ("test2 %s" % arg1)2308 """)2309 result = testdir.runpytest("-s")2310 result.stdout.fnmatch_lines("""2311 *setup*2312 *test1 1*2313 *test2 1*2314 *teardown*2315 """)2316 def test_setup_exception(self, testdir):2317 testdir.makepyfile("""2318 import pytest2319 @pytest.yield_fixture(scope="module")2320 def arg1():2321 pytest.fail("setup")2322 yield 12323 def test_1(arg1):2324 pass2325 """)2326 result = testdir.runpytest("-s")2327 result.stdout.fnmatch_lines("""2328 *pytest.fail*setup*2329 *1 error*2330 """)2331 def test_teardown_exception(self, testdir):2332 testdir.makepyfile("""2333 import pytest2334 @pytest.yield_fixture(scope="module")2335 def arg1():2336 yield 12337 pytest.fail("teardown")2338 def test_1(arg1):2339 pass2340 """)2341 result = testdir.runpytest("-s")2342 result.stdout.fnmatch_lines("""2343 *pytest.fail*teardown*2344 *1 passed*1 error*2345 """)2346 def test_yields_more_than_one(self, testdir):2347 testdir.makepyfile("""2348 import pytest2349 @pytest.yield_fixture(scope="module")2350 def arg1():2351 yield 12352 yield 22353 def test_1(arg1):2354 pass2355 """)2356 result = testdir.runpytest("-s")2357 result.stdout.fnmatch_lines("""2358 *fixture function*2359 *test_yields*:2*2360 """)2361 def test_no_yield(self, testdir):2362 testdir.makepyfile("""2363 import pytest2364 @pytest.yield_fixture(scope="module")2365 def arg1():2366 return 12367 def test_1(arg1):2368 pass2369 """)2370 result = testdir.runpytest("-s")2371 result.stdout.fnmatch_lines("""2372 *yield_fixture*requires*yield*2373 *yield_fixture*2374 *def arg1*2375 """)2376 def test_yield_not_allowed_in_non_yield(self, testdir):2377 testdir.makepyfile("""2378 import pytest2379 @pytest.fixture(scope="module")2380 def arg1():2381 yield 12382 def test_1(arg1):2383 pass2384 """)2385 result = testdir.runpytest("-s")2386 result.stdout.fnmatch_lines("""2387 *fixture*cannot use*yield*2388 *def arg1*...
test_skipping.py
Source:test_skipping.py
...147 assert 0148 def test_func2():149 pytest.xfail("hello")150 """)151 result = testdir.runpytest("--runxfail")152 result.stdout.fnmatch_lines([153 "*def test_func():*",154 "*assert 0*",155 "*1 failed*1 pass*",156 ])157 def test_xfail_evalfalse_but_fails(self, testdir):158 item = testdir.getitem("""159 import pytest160 @pytest.mark.xfail('False')161 def test_func():162 assert 0163 """)164 reports = runtestprotocol(item, log=False)165 callreport = reports[1]166 assert callreport.failed167 assert not hasattr(callreport, "wasxfail")168 assert 'xfail' in callreport.keywords169 def test_xfail_not_report_default(self, testdir):170 p = testdir.makepyfile(test_one="""171 import pytest172 @pytest.mark.xfail173 def test_this():174 assert 0175 """)176 testdir.runpytest(p, '-v')177 #result.stdout.fnmatch_lines([178 # "*HINT*use*-r*"179 #])180 def test_xfail_not_run_xfail_reporting(self, testdir):181 p = testdir.makepyfile(test_one="""182 import pytest183 @pytest.mark.xfail(run=False, reason="noway")184 def test_this():185 assert 0186 @pytest.mark.xfail("True", run=False)187 def test_this_true():188 assert 0189 @pytest.mark.xfail("False", run=False, reason="huh")190 def test_this_false():191 assert 1192 """)193 result = testdir.runpytest(p, '--report=xfailed', )194 result.stdout.fnmatch_lines([195 "*test_one*test_this*",196 "*NOTRUN*noway",197 "*test_one*test_this_true*",198 "*NOTRUN*condition:*True*",199 "*1 passed*",200 ])201 def test_xfail_not_run_no_setup_run(self, testdir):202 p = testdir.makepyfile(test_one="""203 import pytest204 @pytest.mark.xfail(run=False, reason="hello")205 def test_this():206 assert 0207 def setup_module(mod):208 raise ValueError(42)209 """)210 result = testdir.runpytest(p, '--report=xfailed', )211 result.stdout.fnmatch_lines([212 "*test_one*test_this*",213 "*NOTRUN*hello",214 "*1 xfailed*",215 ])216 def test_xfail_xpass(self, testdir):217 p = testdir.makepyfile(test_one="""218 import pytest219 @pytest.mark.xfail220 def test_that():221 assert 1222 """)223 result = testdir.runpytest(p, '-rX')224 result.stdout.fnmatch_lines([225 "*XPASS*test_that*",226 "*1 xpassed*"227 ])228 assert result.ret == 0229 def test_xfail_imperative(self, testdir):230 p = testdir.makepyfile("""231 import pytest232 def test_this():233 pytest.xfail("hello")234 """)235 result = testdir.runpytest(p)236 result.stdout.fnmatch_lines([237 "*1 xfailed*",238 ])239 result = testdir.runpytest(p, "-rx")240 result.stdout.fnmatch_lines([241 "*XFAIL*test_this*",242 "*reason:*hello*",243 ])244 result = testdir.runpytest(p, "--runxfail")245 result.stdout.fnmatch_lines("*1 pass*")246 def test_xfail_imperative_in_setup_function(self, testdir):247 p = testdir.makepyfile("""248 import pytest249 def setup_function(function):250 pytest.xfail("hello")251 def test_this():252 assert 0253 """)254 result = testdir.runpytest(p)255 result.stdout.fnmatch_lines([256 "*1 xfailed*",257 ])258 result = testdir.runpytest(p, "-rx")259 result.stdout.fnmatch_lines([260 "*XFAIL*test_this*",261 "*reason:*hello*",262 ])263 result = testdir.runpytest(p, "--runxfail")264 result.stdout.fnmatch_lines("""265 *def test_this*266 *1 fail*267 """)268 def xtest_dynamic_xfail_set_during_setup(self, testdir):269 p = testdir.makepyfile("""270 import pytest271 def setup_function(function):272 pytest.mark.xfail(function)273 def test_this():274 assert 0275 def test_that():276 assert 1277 """)278 result = testdir.runpytest(p, '-rxX')279 result.stdout.fnmatch_lines([280 "*XFAIL*test_this*",281 "*XPASS*test_that*",282 ])283 def test_dynamic_xfail_no_run(self, testdir):284 p = testdir.makepyfile("""285 import pytest286 def pytest_funcarg__arg(request):287 request.applymarker(pytest.mark.xfail(run=False))288 def test_this(arg):289 assert 0290 """)291 result = testdir.runpytest(p, '-rxX')292 result.stdout.fnmatch_lines([293 "*XFAIL*test_this*",294 "*NOTRUN*",295 ])296 def test_dynamic_xfail_set_during_funcarg_setup(self, testdir):297 p = testdir.makepyfile("""298 import pytest299 def pytest_funcarg__arg(request):300 request.applymarker(pytest.mark.xfail)301 def test_this2(arg):302 assert 0303 """)304 result = testdir.runpytest(p)305 result.stdout.fnmatch_lines([306 "*1 xfailed*",307 ])308 @pytest.mark.parametrize('expected, actual, matchline',309 [('TypeError', 'TypeError', "*1 xfailed*"),310 ('(AttributeError, TypeError)', 'TypeError', "*1 xfailed*"),311 ('TypeError', 'IndexError', "*1 failed*"),312 ('(AttributeError, TypeError)', 'IndexError', "*1 failed*"),313 ])314 def test_xfail_raises(self, expected, actual, matchline, testdir):315 p = testdir.makepyfile("""316 import pytest317 @pytest.mark.xfail(raises=%s)318 def test_raises():319 raise %s()320 """ % (expected, actual))321 result = testdir.runpytest(p)322 result.stdout.fnmatch_lines([323 matchline,324 ])325 def test_strict_sanity(self, testdir):326 """sanity check for xfail(strict=True): a failing test should behave327 exactly like a normal xfail.328 """329 p = testdir.makepyfile("""330 import pytest331 @pytest.mark.xfail(reason='unsupported feature', strict=True)332 def test_foo():333 assert 0334 """)335 result = testdir.runpytest(p, '-rxX')336 result.stdout.fnmatch_lines([337 '*XFAIL*',338 '*unsupported feature*',339 ])340 assert result.ret == 0341 @pytest.mark.parametrize('strict', [True, False])342 def test_strict_xfail(self, testdir, strict):343 p = testdir.makepyfile("""344 import pytest345 @pytest.mark.xfail(reason='unsupported feature', strict=%s)346 def test_foo():347 with open('foo_executed', 'w'): pass # make sure test executes348 """ % strict)349 result = testdir.runpytest(p, '-rxX')350 if strict:351 result.stdout.fnmatch_lines([352 '*test_foo*',353 '*XPASS(strict)*unsupported feature*',354 ])355 else:356 result.stdout.fnmatch_lines([357 '*test_strict_xfail*',358 'XPASS test_strict_xfail.py::test_foo unsupported feature',359 ])360 assert result.ret == (1 if strict else 0)361 assert testdir.tmpdir.join('foo_executed').isfile()362 @pytest.mark.parametrize('strict', [True, False])363 def test_strict_xfail_condition(self, testdir, strict):364 p = testdir.makepyfile("""365 import pytest366 @pytest.mark.xfail(False, reason='unsupported feature', strict=%s)367 def test_foo():368 pass369 """ % strict)370 result = testdir.runpytest(p, '-rxX')371 result.stdout.fnmatch_lines('*1 passed*')372 assert result.ret == 0373 @pytest.mark.parametrize('strict_val', ['true', 'false'])374 def test_strict_xfail_default_from_file(self, testdir, strict_val):375 testdir.makeini('''376 [pytest]377 xfail_strict = %s378 ''' % strict_val)379 p = testdir.makepyfile("""380 import pytest381 @pytest.mark.xfail(reason='unsupported feature')382 def test_foo():383 pass384 """)385 result = testdir.runpytest(p, '-rxX')386 strict = strict_val == 'true'387 result.stdout.fnmatch_lines('*1 failed*' if strict else '*1 xpassed*')388 assert result.ret == (1 if strict else 0)389class TestXFailwithSetupTeardown:390 def test_failing_setup_issue9(self, testdir):391 testdir.makepyfile("""392 import pytest393 def setup_function(func):394 assert 0395 @pytest.mark.xfail396 def test_func():397 pass398 """)399 result = testdir.runpytest()400 result.stdout.fnmatch_lines([401 "*1 xfail*",402 ])403 def test_failing_teardown_issue9(self, testdir):404 testdir.makepyfile("""405 import pytest406 def teardown_function(func):407 assert 0408 @pytest.mark.xfail409 def test_func():410 pass411 """)412 result = testdir.runpytest()413 result.stdout.fnmatch_lines([414 "*1 xfail*",415 ])416class TestSkip:417 def test_skip_class(self, testdir):418 testdir.makepyfile("""419 import pytest420 @pytest.mark.skip421 class TestSomething(object):422 def test_foo(self):423 pass424 def test_bar(self):425 pass426 def test_baz():427 pass428 """)429 rec = testdir.inline_run()430 rec.assertoutcome(skipped=2, passed=1)431 def test_skips_on_false_string(self, testdir):432 testdir.makepyfile("""433 import pytest434 @pytest.mark.skip('False')435 def test_foo():436 pass437 """)438 rec = testdir.inline_run()439 rec.assertoutcome(skipped=1)440 def test_arg_as_reason(self, testdir):441 testdir.makepyfile("""442 import pytest443 @pytest.mark.skip('testing stuff')444 def test_bar():445 pass446 """)447 result = testdir.runpytest('-rs')448 result.stdout.fnmatch_lines([449 "*testing stuff*",450 "*1 skipped*",451 ])452 def test_skip_no_reason(self, testdir):453 testdir.makepyfile("""454 import pytest455 @pytest.mark.skip456 def test_foo():457 pass458 """)459 result = testdir.runpytest('-rs')460 result.stdout.fnmatch_lines([461 "*unconditional skip*",462 "*1 skipped*",463 ])464 def test_skip_with_reason(self, testdir):465 testdir.makepyfile("""466 import pytest467 @pytest.mark.skip(reason="for lolz")468 def test_bar():469 pass470 """)471 result = testdir.runpytest('-rs')472 result.stdout.fnmatch_lines([473 "*for lolz*",474 "*1 skipped*",475 ])476 def test_only_skips_marked_test(self, testdir):477 testdir.makepyfile("""478 import pytest479 @pytest.mark.skip480 def test_foo():481 pass482 @pytest.mark.skip(reason="nothing in particular")483 def test_bar():484 pass485 def test_baz():486 assert True487 """)488 result = testdir.runpytest('-rs')489 result.stdout.fnmatch_lines([490 "*nothing in particular*",491 "*1 passed*2 skipped*",492 ])493class TestSkipif:494 def test_skipif_conditional(self, testdir):495 item = testdir.getitem("""496 import pytest497 @pytest.mark.skipif("hasattr(os, 'sep')")498 def test_func():499 pass500 """) # noqa501 x = pytest.raises(pytest.skip.Exception, lambda:502 pytest_runtest_setup(item))503 assert x.value.msg == "condition: hasattr(os, 'sep')"504 @pytest.mark.parametrize('params', [505 '"hasattr(sys, \'platform\')"',506 'True, reason="invalid platform"',507 ])508 def test_skipif_reporting(self, testdir, params):509 p = testdir.makepyfile(test_foo="""510 import pytest511 @pytest.mark.skipif(%(params)s)512 def test_that():513 assert 0514 """ % dict(params=params))515 result = testdir.runpytest(p, '-s', '-rs')516 result.stdout.fnmatch_lines([517 "*SKIP*1*test_foo.py*platform*",518 "*1 skipped*"519 ])520 assert result.ret == 0521 @pytest.mark.parametrize('marker, msg1, msg2', [522 ('skipif', 'SKIP', 'skipped'),523 ('xfail', 'XPASS', 'xpassed'),524 ])525 def test_skipif_reporting_multiple(self, testdir, marker, msg1, msg2):526 testdir.makepyfile(test_foo="""527 import pytest528 @pytest.mark.{marker}(False, reason='first_condition')529 @pytest.mark.{marker}(True, reason='second_condition')530 def test_foobar():531 assert 1532 """.format(marker=marker))533 result = testdir.runpytest('-s', '-rsxX')534 result.stdout.fnmatch_lines([535 "*{msg1}*test_foo.py*second_condition*".format(msg1=msg1),536 "*1 {msg2}*".format(msg2=msg2),537 ])538 assert result.ret == 0539def test_skip_not_report_default(testdir):540 p = testdir.makepyfile(test_one="""541 import pytest542 def test_this():543 pytest.skip("hello")544 """)545 result = testdir.runpytest(p, '-v')546 result.stdout.fnmatch_lines([547 #"*HINT*use*-r*",548 "*1 skipped*",549 ])550def test_skipif_class(testdir):551 p = testdir.makepyfile("""552 import pytest553 class TestClass:554 pytestmark = pytest.mark.skipif("True")555 def test_that(self):556 assert 0557 def test_though(self):558 assert 0559 """)560 result = testdir.runpytest(p)561 result.stdout.fnmatch_lines([562 "*2 skipped*"563 ])564def test_skip_reasons_folding():565 path = 'xyz'566 lineno = 3567 message = "justso"568 longrepr = (path, lineno, message)569 class X:570 pass571 ev1 = X()572 ev1.when = "execute"573 ev1.skipped = True574 ev1.longrepr = longrepr575 ev2 = X()576 ev2.longrepr = longrepr577 ev2.skipped = True578 l = folded_skips([ev1, ev2])579 assert len(l) == 1580 num, fspath, lineno, reason = l[0]581 assert num == 2582 assert fspath == path583 assert lineno == lineno584 assert reason == message585def test_skipped_reasons_functional(testdir):586 testdir.makepyfile(587 test_one="""588 from conftest import doskip589 def setup_function(func):590 doskip()591 def test_func():592 pass593 class TestClass:594 def test_method(self):595 doskip()596 """,597 test_two = """598 from conftest import doskip599 doskip()600 """,601 conftest = """602 import pytest603 def doskip():604 pytest.skip('test')605 """606 )607 result = testdir.runpytest('--report=skipped')608 result.stdout.fnmatch_lines([609 "*SKIP*3*conftest.py:3: test",610 ])611 assert result.ret == 0612def test_reportchars(testdir):613 testdir.makepyfile("""614 import pytest615 def test_1():616 assert 0617 @pytest.mark.xfail618 def test_2():619 assert 0620 @pytest.mark.xfail621 def test_3():622 pass623 def test_4():624 pytest.skip("four")625 """)626 result = testdir.runpytest("-rfxXs")627 result.stdout.fnmatch_lines([628 "FAIL*test_1*",629 "XFAIL*test_2*",630 "XPASS*test_3*",631 "SKIP*four*",632 ])633def test_reportchars_error(testdir):634 testdir.makepyfile(635 conftest="""636 def pytest_runtest_teardown():637 assert 0638 """,639 test_simple="""640 def test_foo():641 pass642 """)643 result = testdir.runpytest('-rE')644 result.stdout.fnmatch_lines([645 'ERROR*test_foo*',646 ])647def test_reportchars_all(testdir):648 testdir.makepyfile("""649 import pytest650 def test_1():651 assert 0652 @pytest.mark.xfail653 def test_2():654 assert 0655 @pytest.mark.xfail656 def test_3():657 pass658 def test_4():659 pytest.skip("four")660 """)661 result = testdir.runpytest("-ra")662 result.stdout.fnmatch_lines([663 "FAIL*test_1*",664 "SKIP*four*",665 "XFAIL*test_2*",666 "XPASS*test_3*",667 ])668def test_reportchars_all_error(testdir):669 testdir.makepyfile(670 conftest="""671 def pytest_runtest_teardown():672 assert 0673 """,674 test_simple="""675 def test_foo():676 pass677 """)678 result = testdir.runpytest('-ra')679 result.stdout.fnmatch_lines([680 'ERROR*test_foo*',681 ])682@pytest.mark.xfail("hasattr(sys, 'pypy_version_info')")683def test_errors_in_xfail_skip_expressions(testdir):684 testdir.makepyfile("""685 import pytest686 @pytest.mark.skipif("asd")687 def test_nameerror():688 pass689 @pytest.mark.xfail("syntax error")690 def test_syntax():691 pass692 def test_func():693 pass694 """)695 result = testdir.runpytest()696 markline = " ^"697 if sys.platform.startswith("java"):698 # XXX report this to java699 markline = "*" + markline[8:]700 result.stdout.fnmatch_lines([701 "*ERROR*test_nameerror*",702 "*evaluating*skipif*expression*",703 "*asd*",704 "*ERROR*test_syntax*",705 "*evaluating*xfail*expression*",706 " syntax error",707 markline,708 "SyntaxError: invalid syntax",709 "*1 pass*2 error*",710 ])711def test_xfail_skipif_with_globals(testdir):712 testdir.makepyfile("""713 import pytest714 x = 3715 @pytest.mark.skipif("x == 3")716 def test_skip1():717 pass718 @pytest.mark.xfail("x == 3")719 def test_boolean():720 assert 0721 """)722 result = testdir.runpytest("-rsx")723 result.stdout.fnmatch_lines([724 "*SKIP*x == 3*",725 "*XFAIL*test_boolean*",726 "*x == 3*",727 ])728def test_direct_gives_error(testdir):729 testdir.makepyfile("""730 import pytest731 @pytest.mark.skipif(True)732 def test_skip1():733 pass734 """)735 result = testdir.runpytest()736 result.stdout.fnmatch_lines([737 "*1 error*",738 ])739def test_default_markers(testdir):740 result = testdir.runpytest("--markers")741 result.stdout.fnmatch_lines([742 "*skipif(*condition)*skip*",743 "*xfail(*condition, reason=None, run=True, raises=None)*expected failure*",744 ])745def test_xfail_test_setup_exception(testdir):746 testdir.makeconftest("""747 def pytest_runtest_setup():748 0 / 0749 """)750 p = testdir.makepyfile("""751 import pytest752 @pytest.mark.xfail753 def test_func():754 assert 0755 """)756 result = testdir.runpytest(p)757 assert result.ret == 0758 assert 'xfailed' in result.stdout.str()759 assert 'xpassed' not in result.stdout.str()760def test_imperativeskip_on_xfail_test(testdir):761 testdir.makepyfile("""762 import pytest763 @pytest.mark.xfail764 def test_that_fails():765 assert 0766 @pytest.mark.skipif("True")767 def test_hello():768 pass769 """)770 testdir.makeconftest("""771 import pytest772 def pytest_runtest_setup(item):773 pytest.skip("abc")774 """)775 result = testdir.runpytest("-rsxX")776 result.stdout.fnmatch_lines_random("""777 *SKIP*abc*778 *SKIP*condition: True*779 *2 skipped*780 """)781class TestBooleanCondition:782 def test_skipif(self, testdir):783 testdir.makepyfile("""784 import pytest785 @pytest.mark.skipif(True, reason="True123")786 def test_func1():787 pass788 @pytest.mark.skipif(False, reason="True123")789 def test_func2():790 pass791 """)792 result = testdir.runpytest()793 result.stdout.fnmatch_lines("""794 *1 passed*1 skipped*795 """)796 def test_skipif_noreason(self, testdir):797 testdir.makepyfile("""798 import pytest799 @pytest.mark.skipif(True)800 def test_func():801 pass802 """)803 result = testdir.runpytest("-rs")804 result.stdout.fnmatch_lines("""805 *1 error*806 """)807 def test_xfail(self, testdir):808 testdir.makepyfile("""809 import pytest810 @pytest.mark.xfail(True, reason="True123")811 def test_func():812 assert 0813 """)814 result = testdir.runpytest("-rxs")815 result.stdout.fnmatch_lines("""816 *XFAIL*817 *True123*818 *1 xfail*819 """)820def test_xfail_item(testdir):821 # Ensure pytest.xfail works with non-Python Item822 testdir.makeconftest("""823 import pytest824 class MyItem(pytest.Item):825 nodeid = 'foo'826 def runtest(self):827 pytest.xfail("Expected Failure")828 def pytest_collect_file(path, parent):...
test_validation__property.py
Source:test_validation__property.py
1#-----------------------------------------------------------------------------2# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.3# All rights reserved.4#5# The full license is in the file LICENSE.txt, distributed with this software.6#-----------------------------------------------------------------------------7#-----------------------------------------------------------------------------8# Boilerplate9#-----------------------------------------------------------------------------10import pytest ; pytest11#-----------------------------------------------------------------------------12# Imports13#-----------------------------------------------------------------------------14# Standard library imports15import re16# External imports17# Bokeh imports18from bokeh.core.property.bases import validation_on19from bokeh.core.has_props import HasProps20from bokeh.core.properties import (21 Angle, AngleSpec, Bool, Color, ColorSpec, ColumnData, Complex, DashPattern, DataDistanceSpec, Date, DistanceSpec, Dict,22 Either, Enum, FontSize, FontSizeSpec, Int, Instance, Interval, Float, List, MarkerType, MinMaxBounds, NumberSpec, Percent,23 Regex, ScreenDistanceSpec, Seq, Size, String, StringSpec, Tuple)24from bokeh._testing.util.api import verify_all25# Module under test26import bokeh.core.property.validation as bcpv27#-----------------------------------------------------------------------------28# Setup29#-----------------------------------------------------------------------------30ALL = (31 'validate',32 'without_property_validation',33)34SPECS = (35 AngleSpec,36 ColorSpec,37 DataDistanceSpec,38 DistanceSpec,39 FontSizeSpec,40 NumberSpec,41 ScreenDistanceSpec,42 StringSpec,43)44#-----------------------------------------------------------------------------45# General API46#-----------------------------------------------------------------------------47class TestValidationControl(object):48 def test_validate(self):49 assert validation_on()50 with bcpv.validate(False):51 assert not validation_on()52 assert validation_on()53 with bcpv.validate(False):54 assert not validation_on()55 with bcpv.validate(True):56 assert validation_on()57 assert not validation_on()58 assert validation_on()59 bcpv.validate(False)60 assert not validation_on()61 bcpv.validate(True)62 assert validation_on()63 def test_without_property_validation(self):64 @bcpv.without_property_validation65 def f():66 assert not validation_on()67 assert validation_on()68 f()69 assert validation_on()70class TestValidateDetailDefault(object):71 # test_Any unecessary (no validation)72 # TODO (bev) test_Image73 def test_Angle(self):74 p = Angle()75 with pytest.raises(ValueError) as e:76 p.validate("junk")77 assert matches(str(e.value), r"expected a value of type Real, got junk of type str")78 def test_Bool(self):79 p = Bool()80 with pytest.raises(ValueError) as e:81 p.validate("junk")82 assert matches(str(e.value), r"expected a value of type bool or bool_, got junk of type str")83 def test_Complex(self):84 p = Complex()85 with pytest.raises(ValueError) as e:86 p.validate("junk")87 assert matches(str(e.value), r"expected a value of type Complex, got junk of type str")88 def test_Float(self):89 p = Float()90 with pytest.raises(ValueError) as e:91 p.validate("junk")92 assert matches(str(e.value), r"expected a value of type Real, got junk of type str")93 def test_Int(self):94 p = Int()95 with pytest.raises(ValueError) as e:96 p.validate("junk")97 assert matches(str(e.value), r"expected a value of type Integral, got junk of type str")98 def test_Interval(self):99 p = Interval(Float, 0.0, 1.0)100 with pytest.raises(ValueError) as e:101 p.validate(2)102 assert matches(str(e.value), r"expected a value of type Float in range \[0.0, 1.0\], got 2")103 def test_Percent(self):104 p = Percent()105 with pytest.raises(ValueError) as e:106 p.validate(10)107 assert matches(str(e.value), r"expected a value in range \[0, 1\], got 10")108 def test_Size(self):109 p = Size()110 with pytest.raises(ValueError) as e:111 p.validate("junk")112 assert matches(str(e.value), r"expected a value of type Real, got junk of type str")113 def test_List(self):114 p = List(Float)115 with pytest.raises(ValueError) as e:116 p.validate("junk")117 assert matches(str(e.value), r"expected an element of List\(Float\), got 'junk'")118 def test_Seq(self):119 p = Seq(Float)120 with pytest.raises(ValueError) as e:121 p.validate("junk")122 assert matches(str(e.value), r"expected an element of Seq\(Float\), got 'junk'")123 def test_Dict(self):124 p = Dict(String, Float)125 with pytest.raises(ValueError) as e:126 p.validate("junk")127 assert matches(str(e.value), r"expected an element of Dict\(String, Float\), got 'junk'")128 def test_Tuple(self):129 p = Tuple(Int, Int)130 with pytest.raises(ValueError) as e:131 p.validate("junk")132 assert matches(str(e.value), r"expected an element of Tuple\(Int, Int\), got 'junk'")133 def test_Color(self):134 p = Color()135 with pytest.raises(ValueError) as e:136 p.validate("junk")137 assert matches(str(e.value), r"expected an element of either Enum\(.*\), .* or RGB, got 'junk'")138 def test_ColumnData(self):139 p = ColumnData(String, Seq(Float))140 with pytest.raises(ValueError) as e:141 p.validate("junk")142 assert matches(str(e.value), r"expected an element of ColumnData\(String, Seq\(Float\)\), got 'junk'")143 def test_Date(self):144 p = Date()145 with pytest.raises(ValueError) as e:146 p.validate(object())147 assert matches(str(e.value), r"expected a date, string or timestamp, got <object object at 0x.*>")148 def test_DashPattern(self):149 p = DashPattern()150 with pytest.raises(ValueError) as e:151 p.validate("junk")152 assert matches(str(e.value), r"expected an element of either Enum\(.*\), Regex\(.*\) or Seq\(Int\), got 'junk'")153 def test_Either(self):154 p = Either(Int, Float)155 with pytest.raises(ValueError) as e:156 p.validate("junk")157 assert matches(str(e.value), r"expected an element of either Int or Float, got 'junk'")158 def test_Enum(self):159 p = Enum("red", "green")160 with pytest.raises(ValueError) as e:161 p.validate("junk")162 assert matches(str(e.value), r"invalid value: 'junk'; allowed values are red or green")163 def test_FontSize(self):164 p = FontSize()165 with pytest.raises(ValueError) as e:166 p.validate("junk")167 assert matches(str(e.value), r"'junk' is not a valid font size value")168 def test_Instance(self):169 p = Instance(HasProps)170 with pytest.raises(ValueError) as e:171 p.validate("junk")172 assert matches(str(e.value), r"expected an instance of type HasProps, got junk of type str")173 def test_MinMaxBounds(self):174 p = MinMaxBounds()175 with pytest.raises(ValueError) as e:176 p.validate(10)177 assert matches(str(e.value), r"expected an element of either Auto, Tuple\(Float, Float\) or Tuple\(TimeDelta, TimeDelta\), got 10")178 def test_Regex(self):179 p = Regex("green")180 with pytest.raises(ValueError) as e:181 p.validate("junk")182 assert matches(str(e.value), r"expected a string matching 'green' pattern, got 'junk'")183 def test_String(self):184 p = String()185 with pytest.raises(ValueError) as e:186 p.validate(10)187 assert matches(str(e.value), r"expected a value of type str, got 10 of type int")188 def test_MarkerType(self):189 p = MarkerType()190 with pytest.raises(ValueError) as e:191 p.validate("foo")192 assert matches(str(e.value), r"invalid value: 'foo'; allowed values are asterisk, .* or x")193 @pytest.mark.parametrize('spec', SPECS)194 def test_Spec(self, spec):195 p = spec(default=None)196 with pytest.raises(ValueError) as e:197 p.validate(dict(bad="junk"))198 assert matches(str(e.value), r"expected an element of either String, .*, got {'bad': 'junk'}")199@pytest.mark.parametrize('detail', [True, False])200class TestValidateDetailExplicit(object):201 # test_Any unecessary (no validation)202 # TODO (bev) test_Image203 def test_Angle(self, detail):204 p = Angle()205 with pytest.raises(ValueError) as e:206 p.validate("junk", detail)207 assert (str(e.value) == "") == (not detail)208 def test_Bool(self, detail):209 p = Bool()210 with pytest.raises(ValueError) as e:211 p.validate("junk", detail)212 assert (str(e.value) == "") == (not detail)213 def test_Complex(self, detail):214 p = Complex()215 with pytest.raises(ValueError) as e:216 p.validate("junk", detail)217 assert (str(e.value) == "") == (not detail)218 def test_Float(self, detail):219 p = Float()220 with pytest.raises(ValueError) as e:221 p.validate("junk", detail)222 assert (str(e.value) == "") == (not detail)223 def test_Int(self, detail):224 p = Int()225 with pytest.raises(ValueError) as e:226 p.validate("junk", detail)227 assert (str(e.value) == "") == (not detail)228 def test_Interval(self, detail):229 p = Interval(Float, 0.0, 1.0)230 with pytest.raises(ValueError) as e:231 p.validate(2, detail)232 assert (str(e.value) == "") == (not detail)233 def test_Percent(self, detail):234 p = Percent()235 with pytest.raises(ValueError) as e:236 p.validate(10, detail)237 assert (str(e.value) == "") == (not detail)238 def test_Size(self, detail):239 p = Size()240 with pytest.raises(ValueError) as e:241 p.validate("junk", detail)242 assert (str(e.value) == "") == (not detail)243 def test_List(self, detail):244 p = List(Float)245 with pytest.raises(ValueError) as e:246 p.validate("junk", detail)247 assert (str(e.value) == "") == (not detail)248 def test_Seq(self, detail):249 p = Seq(Float)250 with pytest.raises(ValueError) as e:251 p.validate("junk", detail)252 assert (str(e.value) == "") == (not detail)253 def test_Dict(self, detail):254 p = Dict(String, Float)255 with pytest.raises(ValueError) as e:256 p.validate("junk", detail)257 assert (str(e.value) == "") == (not detail)258 def test_Tuple(self, detail):259 p = Tuple(Int, Int)260 with pytest.raises(ValueError) as e:261 p.validate("junk", detail)262 assert (str(e.value) == "") == (not detail)263 def test_Color(self, detail):264 p = Color()265 with pytest.raises(ValueError) as e:266 p.validate("junk", detail)267 assert (str(e.value) == "") == (not detail)268 def test_ColumnData(self, detail):269 p = ColumnData(String, Seq(Float))270 with pytest.raises(ValueError) as e:271 p.validate("junk", detail)272 assert (str(e.value) == "") == (not detail)273 def test_Date(self, detail):274 p = Date()275 with pytest.raises(ValueError) as e:276 p.validate(p, detail)277 assert (str(e.value) == "") == (not detail)278 def test_DashPattern(self, detail):279 p = DashPattern()280 with pytest.raises(ValueError) as e:281 p.validate("junk", detail)282 assert (str(e.value) == "") == (not detail)283 def test_Either(self, detail):284 p = Either(Int, Float)285 with pytest.raises(ValueError) as e:286 p.validate("junk", detail)287 assert (str(e.value) == "") == (not detail)288 def test_Enum(self, detail):289 p = Enum("red", "green")290 with pytest.raises(ValueError) as e:291 p.validate("junk", detail)292 assert (str(e.value) == "") == (not detail)293 def test_FontSize(self, detail):294 p = FontSize()295 with pytest.raises(ValueError) as e:296 p.validate("junk", detail)297 assert (str(e.value) == "") == (not detail)298 def test_Instance(self, detail):299 p = Instance(HasProps)300 with pytest.raises(ValueError) as e:301 p.validate("junk", detail)302 assert (str(e.value) == "") == (not detail)303 def test_MinMaxBounds(self, detail):304 p = MinMaxBounds()305 with pytest.raises(ValueError) as e:306 p.validate(10, detail)307 assert (str(e.value) == "") == (not detail)308 def test_Regex(self, detail):309 p = Regex("green")310 with pytest.raises(ValueError) as e:311 p.validate("junk", detail)312 assert (str(e.value) == "") == (not detail)313 def test_String(self, detail):314 p = String()315 with pytest.raises(ValueError) as e:316 p.validate(10, detail)317 assert (str(e.value) == "") == (not detail)318 def test_MarkerType(self, detail):319 p = MarkerType()320 with pytest.raises(ValueError) as e:321 p.validate("foo", detail)322 assert (str(e.value) == "") == (not detail)323 @pytest.mark.parametrize('spec', SPECS)324 def test_Spec(self, detail, spec):325 p = spec(default=None)326 with pytest.raises(ValueError) as e:327 p.validate(dict(bad="junk"), detail)328 assert (str(e.value) == "") == (not detail)329#-----------------------------------------------------------------------------330# Dev API331#-----------------------------------------------------------------------------332#-----------------------------------------------------------------------------333# Private API334#-----------------------------------------------------------------------------335def matches(string, pattern):336 return re.match(pattern, string) is not None337#-----------------------------------------------------------------------------338# Code339#-----------------------------------------------------------------------------...
test_units.py
Source:test_units.py
1# This file is part of narupatools (https://github.com/alexjbinnie/narupatools).2# Copyright (c) Alex Jamieson-Binnie. All rights reserved.3#4# narupatools is free software: you can redistribute it and/or modify5# it under the terms of the GNU General Public License as published by6# the Free Software Foundation, either version 3 of the License, or7# (at your option) any later version.8#9# narupatools is distributed in the hope that it will be useful,10# but WITHOUT ANY WARRANTY; without even the implied warranty of11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12# GNU General Public License for more details.13#14# You should have received a copy of the GNU General Public License15# along with narupatools. If not, see <http://www.gnu.org/licenses/>.16import pytest17lammps = pytest.importorskip("lammps")18from narupatools.core.units import (19 Unit,20 UnitsNarupa,21 amu,22 angstrom,23 atmosphere,24 atomic_time_unit,25 atto,26 bar,27 bohr,28 calorie,29 centi,30 coulomb,31 debye,32 dyne,33 electronvolt,34 elementary_charge,35 erg,36 esu,37 femto,38 gram,39 hartree,40 joule,41 kelvin,42 kilo,43 meter,44 micro,45 mole,46 nano,47 newton,48 pascal,49 pico,50 poise,51 second,52 statcoulomb,53 statvolt,54 volt,55)56from narupatools.lammps.units import (57 UnitsLAMMPSCGS,58 UnitsLAMMPSElectron,59 UnitsLAMMPSMetal,60 UnitsLAMMPSMicro,61 UnitsLAMMPSNano,62 UnitsLAMMPSReal,63 UnitsLAMMPSSI,64)65def test_lammps_real():66 units = UnitsLAMMPSReal67 assert 1.0 * units.mass == pytest.approx(1.0 * gram / mole)68 assert 1.0 * units.length == pytest.approx(1.0 * angstrom)69 assert 1.0 * units.time == pytest.approx(1.0 * femto * second)70 assert 1.0 * units.energy == pytest.approx(1.0 * kilo * calorie / mole)71 assert 1.0 * units.velocity == pytest.approx(1.0 * angstrom / (femto * second))72 assert 1.0 * units.force == pytest.approx(1.0 * kilo * calorie / (mole * angstrom))73 assert 1.0 * units.torque == pytest.approx(1.0 * kilo * calorie / mole)74 assert 1.0 * units.temperature == pytest.approx(1.0 * kelvin)75 assert 1.0 * units.pressure == pytest.approx(1.0 * atmosphere)76 assert 1.0 * units.dynamic_viscosity == pytest.approx(1.0 * poise)77 assert 1.0 * units.charge == pytest.approx(1.0 * elementary_charge)78 assert 1.0 * units.dipole_moment == pytest.approx(79 1.0 * elementary_charge * angstrom80 )81 assert 1.0 * units.electric_field == pytest.approx(1.0 * volt / angstrom)82 assert 1.0 * units.density == pytest.approx(1.0 * gram / ((centi * meter) ** 3))83 assert 1.0 * units.density2d == pytest.approx(1.0 * gram / ((centi * meter) ** 2))84 # Check inconsistency of units85 assert 1.0 * units.energy != pytest.approx(86 1.0 * units.mass * (units.length ** 2) / (units.time ** 2)87 )88def test_lammps_metal():89 units = UnitsLAMMPSMetal90 assert 1.0 * units.mass == pytest.approx(1.0 * gram / mole)91 assert 1.0 * units.length == pytest.approx(1.0 * angstrom)92 assert 1.0 * units.time == pytest.approx(1.0 * pico * second)93 assert 1.0 * units.energy == pytest.approx(1.0 * electronvolt)94 assert 1.0 * units.velocity == pytest.approx(1.0 * angstrom / (pico * second))95 assert 1.0 * units.force == pytest.approx(1.0 * electronvolt / angstrom)96 assert 1.0 * units.torque == pytest.approx(1.0 * electronvolt)97 assert 1.0 * units.temperature == pytest.approx(1.0 * kelvin)98 assert 1.0 * units.pressure == pytest.approx(1.0 * bar)99 assert 1.0 * units.dynamic_viscosity == pytest.approx(1.0 * poise)100 assert 1.0 * units.charge == pytest.approx(1.0 * elementary_charge)101 assert 1.0 * units.dipole_moment == pytest.approx(102 1.0 * elementary_charge * angstrom103 )104 assert 1.0 * units.electric_field == pytest.approx(1.0 * volt / angstrom)105 assert 1.0 * units.density == pytest.approx(1.0 * gram / ((centi * meter) ** 3))106 assert 1.0 * units.density2d == pytest.approx(1.0 * gram / ((centi * meter) ** 2))107 # Check inconsistency of units108 assert 1.0 * units.energy != pytest.approx(109 1.0 * units.mass * (units.length ** 2) / (units.time ** 2)110 )111def test_lammps_si():112 units = UnitsLAMMPSSI113 assert 1.0 * units.mass == pytest.approx(1.0 * kilo * gram)114 assert 1.0 * units.length == pytest.approx(1.0 * meter)115 assert 1.0 * units.time == pytest.approx(1.0 * second)116 assert 1.0 * units.energy == pytest.approx(1.0 * joule)117 assert 1.0 * units.velocity == pytest.approx(1.0 * meter / second)118 assert 1.0 * units.force == pytest.approx(1.0 * newton)119 assert 1.0 * units.torque == pytest.approx(1.0 * newton * meter)120 assert 1.0 * units.temperature == pytest.approx(1.0 * kelvin)121 assert 1.0 * units.pressure == pytest.approx(1.0 * pascal)122 assert 1.0 * units.dynamic_viscosity == pytest.approx(1.0 * pascal * second)123 assert 1.0 * units.charge == pytest.approx(1.0 * coulomb)124 assert 1.0 * units.dipole_moment == pytest.approx(1.0 * coulomb * meter)125 assert 1.0 * units.electric_field == pytest.approx(1.0 * volt / meter)126 assert 1.0 * units.density == pytest.approx(1.0 * kilo * gram / (meter ** 3))127 assert 1.0 * units.density2d == pytest.approx(1.0 * kilo * gram / (meter ** 2))128 # Check consistency of units129 assert 1.0 * units.energy == pytest.approx(130 1.0 * units.mass * (units.length ** 2) / (units.time ** 2)131 )132def test_lammps_cgs():133 units = UnitsLAMMPSCGS134 assert 1.0 * units.mass == pytest.approx(1.0 * gram)135 assert 1.0 * units.length == pytest.approx(1.0 * centi * meter)136 assert 1.0 * units.time == pytest.approx(1.0 * second)137 assert 1.0 * units.energy == pytest.approx(1.0 * erg)138 assert 1.0 * units.velocity == pytest.approx(1.0 * centi * meter / second)139 assert 1.0 * units.force == pytest.approx(1.0 * dyne)140 assert 1.0 * units.torque == pytest.approx(1.0 * dyne * centi * meter)141 assert 1.0 * units.temperature == pytest.approx(1.0 * kelvin)142 assert 1.0 * units.pressure == pytest.approx(1.0 * dyne / ((centi * meter) ** 2))143 assert 1.0 * units.pressure == pytest.approx(1e-6 * bar)144 assert 1.0 * units.dynamic_viscosity == pytest.approx(1.0 * poise)145 assert 1.0 * units.charge == pytest.approx(1.0 * statcoulomb)146 assert 1.0 * units.dipole_moment == pytest.approx(1.0 * statcoulomb * centi * meter)147 assert 1.0 * units.dipole_moment == pytest.approx(1e18 * debye)148 assert 1.0 * units.electric_field == pytest.approx(1.0 * statvolt / (centi * meter))149 assert 1.0 * units.electric_field == pytest.approx(1.0 * dyne / esu)150 assert 1.0 * units.density == pytest.approx(1.0 * gram / ((centi * meter) ** 3))151 assert 1.0 * units.density2d == pytest.approx(1.0 * gram / ((centi * meter) ** 2))152 # Check consistency of units153 assert 1.0 * units.energy == pytest.approx(154 1.0 * units.mass * (units.length ** 2) / (units.time ** 2)155 )156def test_lammps_electron():157 units = UnitsLAMMPSElectron158 assert 1.0 * units.mass == pytest.approx(1.0 * amu)159 assert 1.0 * units.length == pytest.approx(1.0 * bohr)160 assert 1.0 * units.time == pytest.approx(1.0 * femto * second)161 assert 1.0 * units.energy == pytest.approx(1.0 * hartree)162 assert 1.0 * units.velocity == pytest.approx(1.0 * bohr / atomic_time_unit)163 assert 1.0 * units.force == pytest.approx(1.0 * hartree / bohr)164 assert 1.0 * units.temperature == pytest.approx(1.0 * kelvin)165 assert 1.0 * units.pressure == pytest.approx(1.0 * pascal)166 assert 1.0 * units.charge == pytest.approx(1.0 * elementary_charge)167 assert 1.0 * units.dipole_moment == pytest.approx(1.0 * debye)168 assert 1.0 * units.electric_field == pytest.approx(1.0 * volt / (centi * meter))169 # Check inconsistency of units170 assert 1.0 * units.energy != pytest.approx(171 1.0 * units.mass * (units.length ** 2) / (units.time ** 2)172 )173def test_lammps_micro():174 units = UnitsLAMMPSMicro175 assert 1.0 * units.mass == pytest.approx(1.0 * pico * gram)176 assert 1.0 * units.length == pytest.approx(1.0 * micro * meter)177 assert 1.0 * units.time == pytest.approx(1.0 * micro * second)178 assert 1.0 * units.energy == pytest.approx(179 1.0 * pico * gram * ((micro * meter) ** 2) / ((micro * second) ** 2)180 )181 assert 1.0 * units.velocity == pytest.approx(182 1.0 * (micro * meter) / (micro * second)183 )184 assert 1.0 * units.force == pytest.approx(185 1.0 * pico * gram * (micro * meter) / ((micro * second) ** 2)186 )187 assert 1.0 * units.torque == pytest.approx(188 1.0 * pico * gram * ((micro * meter) ** 2) / ((micro * second) ** 2)189 )190 assert 1.0 * units.temperature == pytest.approx(1.0 * kelvin)191 assert 1.0 * units.pressure == pytest.approx(192 1.0 * pico * gram / (micro * meter * ((micro * second) ** 2))193 )194 assert 1.0 * units.dynamic_viscosity == pytest.approx(195 1.0 * (pico * gram) / (micro * meter * micro * second)196 )197 assert 1.0 * units.charge == pytest.approx(1.0 * pico * coulomb)198 assert 1.0 * units.dipole_moment == pytest.approx(199 1.0 * pico * coulomb * micro * meter200 )201 assert 1.0 * units.electric_field == pytest.approx(1.0 * volt / (micro * meter))202 assert 1.0 * units.density == pytest.approx(203 1.0 * pico * gram / ((micro * meter) ** 3)204 )205 assert 1.0 * units.density2d == pytest.approx(206 1.0 * pico * gram / ((micro * meter) ** 2)207 )208 # Check consistency of units209 assert 1.0 * units.energy == pytest.approx(210 1.0 * units.mass * (units.length ** 2) / (units.time ** 2)211 )212def test_lammps_nano():213 units = UnitsLAMMPSNano214 assert 1.0 * units.mass == pytest.approx(1.0 * atto * gram)215 assert 1.0 * units.length == pytest.approx(1.0 * nano * meter)216 assert 1.0 * units.time == pytest.approx(1.0 * nano * second)217 assert 1.0 * units.energy == pytest.approx(218 1.0 * atto * gram * ((nano * meter) ** 2) / ((nano * second) ** 2)219 )220 assert 1.0 * units.velocity == pytest.approx(1.0 * (nano * meter) / (nano * second))221 assert 1.0 * units.force == pytest.approx(222 1.0 * atto * gram * (nano * meter) / ((nano * second) ** 2)223 )224 assert 1.0 * units.torque == pytest.approx(225 1.0 * atto * gram * ((nano * meter) ** 2) / ((nano * second) ** 2)226 )227 assert 1.0 * units.temperature == pytest.approx(1.0 * kelvin)228 assert 1.0 * units.pressure == pytest.approx(229 1.0 * atto * gram / (nano * meter * ((nano * second) ** 2))230 )231 assert 1.0 * units.dynamic_viscosity == pytest.approx(232 1.0 * (atto * gram) / (nano * meter * nano * second)233 )234 assert 1.0 * units.charge == pytest.approx(1.0 * elementary_charge)235 assert 1.0 * units.dipole_moment == pytest.approx(236 1.0 * elementary_charge * nano * meter237 )238 assert 1.0 * units.electric_field == pytest.approx(1.0 * volt / (nano * meter))239 assert 1.0 * units.density == pytest.approx(240 1.0 * atto * gram / ((nano * meter) ** 3)241 )242 assert 1.0 * units.density2d == pytest.approx(243 1.0 * atto * gram / ((nano * meter) ** 2)244 )245 # Check consistency of units246 assert 1.0 * units.energy == pytest.approx(247 1.0 * units.mass * (units.length ** 2) / (units.time ** 2)248 )249@pytest.mark.parametrize(250 "units",251 [252 UnitsLAMMPSSI,253 UnitsLAMMPSNano,254 UnitsLAMMPSMetal,255 UnitsLAMMPSReal,256 UnitsLAMMPSCGS,257 UnitsLAMMPSElectron,258 UnitsLAMMPSMicro,259 ],260)261@pytest.mark.parametrize(262 "quantity",263 [264 "mass",265 "length",266 "time",267 "energy",268 "velocity",269 "force",270 "torque",271 "temperature",272 "pressure",273 "dynamic_viscosity",274 "charge",275 "dipole_moment",276 "density",277 "density2d",278 ],279)280def test_conversion_to_narupa(units, quantity):281 conversion = units >> UnitsNarupa282 conversion2 = UnitsNarupa << units283 assert 1.0 * getattr(conversion, quantity) == pytest.approx(284 1.0 * getattr(units, quantity)285 )286 assert 1.0 * getattr(conversion2, quantity) == pytest.approx(287 1.0 * getattr(units, quantity)288 )289@pytest.mark.parametrize(290 "units",291 [292 UnitsLAMMPSSI,293 UnitsLAMMPSNano,294 UnitsLAMMPSMetal,295 UnitsLAMMPSReal,296 UnitsLAMMPSCGS,297 UnitsLAMMPSElectron,298 UnitsLAMMPSMicro,299 ],300)301@pytest.mark.parametrize(302 "quantity",303 [304 "mass",305 "length",306 "time",307 "energy",308 "velocity",309 "force",310 "torque",311 "temperature",312 "pressure",313 "dynamic_viscosity",314 "charge",315 "dipole_moment",316 "density",317 "density2d",318 ],319)320def test_conversion_from_narupa(units, quantity):321 conversion = UnitsNarupa >> units322 conversion2 = units << UnitsNarupa323 assert 1.0 * getattr(conversion, quantity) == pytest.approx(324 1.0 / getattr(units, quantity)325 )326 assert 1.0 * getattr(conversion2, quantity) == pytest.approx(327 1.0 / getattr(units, quantity)328 )329@pytest.mark.parametrize(330 "units",331 [332 UnitsLAMMPSSI,333 UnitsLAMMPSNano,334 UnitsLAMMPSMetal,335 UnitsLAMMPSReal,336 UnitsLAMMPSCGS,337 UnitsLAMMPSElectron,338 UnitsLAMMPSMicro,339 ],340)341@pytest.mark.parametrize(342 "quantity",343 [344 "mass",345 "length",346 "time",347 "energy",348 "velocity",349 "force",350 "torque",351 "temperature",352 "pressure",353 "dynamic_viscosity",354 "charge",355 "dipole_moment",356 "density",357 "density2d",358 ],359)360def test_unit_system_is_unit(units, quantity):...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!