How to use parametrize method in pytest-play

Best Python code snippet using pytest-play_python

metafunc.py

Source:metafunc.py Github

copy

Full Screen

...71 assert not hasattr(metafunc._calls[1], 'param')72 def test_parametrize_error(self):73 def func(x, y): pass74 metafunc = self.Metafunc(func)75 metafunc.parametrize("x", [1,2])76 pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5,6]))77 pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5,6]))78 metafunc.parametrize("y", [1,2])79 pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5,6]))80 pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5,6]))81 def test_parametrize_and_id(self):82 def func(x, y): pass83 metafunc = self.Metafunc(func)84 metafunc.parametrize("x", [1,2], ids=['basic', 'advanced'])85 metafunc.parametrize("y", ["abc", "def"])86 ids = [x.id for x in metafunc._calls]87 assert ids == ["basic-abc", "basic-def", "advanced-abc", "advanced-def"]88 def test_parametrize_with_wrong_number_of_ids(self, testdir):89 def func(x, y): pass90 metafunc = self.Metafunc(func)91 pytest.raises(ValueError, lambda:92 metafunc.parametrize("x", [1,2], ids=['basic']))93 pytest.raises(ValueError, lambda:94 metafunc.parametrize(("x","y"), [("abc", "def"),95 ("ghi", "jkl")], ids=["one"]))96 def test_parametrize_with_userobjects(self):97 def func(x, y): pass98 metafunc = self.Metafunc(func)99 class A:100 pass101 metafunc.parametrize("x", [A(), A()])102 metafunc.parametrize("y", list("ab"))103 assert metafunc._calls[0].id == "x0-a"104 assert metafunc._calls[1].id == "x0-b"105 assert metafunc._calls[2].id == "x1-a"106 assert metafunc._calls[3].id == "x1-b"107 @pytest.mark.skipif('sys.version_info[0] >= 3')108 def test_unicode_idval_python2(self):109 """unittest for the expected behavior to obtain ids for parametrized110 unicode values in Python 2: if convertible to ascii, they should appear111 as ascii values, otherwise fallback to hide the value behind the name112 of the parametrized variable name. #1086113 """114 from _pytest.python import _idval115 values = [116 (u'', ''),117 (u'ascii', 'ascii'),118 (u'ação', 'a6'),119 (u'josé@blah.com', 'a6'),120 (u'δοκ.ιμή@παράδειγμα.δοκιμή', 'a6'),121 ]122 for val, expected in values:123 assert _idval(val, 'a', 6, None) == expected124 def test_bytes_idval(self):125 """unittest for the expected behavior to obtain ids for parametrized126 bytes values:127 - python2: non-ascii strings are considered bytes and formatted using128 "binary escape", where any byte < 127 is escaped into its hex form.129 - python3: bytes objects are always escaped using "binary escape".130 """131 from _pytest.python import _idval132 values = [133 (b'', ''),134 (b'\xc3\xb4\xff\xe4', '\\xc3\\xb4\\xff\\xe4'),135 (b'ascii', 'ascii'),136 (u'αρά'.encode('utf-8'), '\\xce\\xb1\\xcf\\x81\\xce\\xac'),137 ]138 for val, expected in values:139 assert _idval(val, 'a', 6, None) == expected140 @pytest.mark.issue250141 def test_idmaker_autoname(self):142 from _pytest.python import idmaker143 result = idmaker(("a", "b"), [("string", 1.0),144 ("st-ring", 2.0)])145 assert result == ["string-1.0", "st-ring-2.0"]146 result = idmaker(("a", "b"), [(object(), 1.0),147 (object(), object())])148 assert result == ["a0-1.0", "a1-b1"]149 # unicode mixing, issue250150 result = idmaker((py.builtin._totext("a"), "b"), [({}, b'\xc3\xb4')])151 assert result == ['a0-\\xc3\\xb4']152 def test_idmaker_with_bytes_regex(self):153 from _pytest.python import idmaker154 result = idmaker(("a"), [(re.compile(b'foo'), 1.0)])155 assert result == ["foo"]156 def test_idmaker_native_strings(self):157 from _pytest.python import idmaker158 totext = py.builtin._totext159 result = idmaker(("a", "b"), [(1.0, -1.1),160 (2, -202),161 ("three", "three hundred"),162 (True, False),163 (None, None),164 (re.compile('foo'), re.compile('bar')),165 (str, int),166 (list("six"), [66, 66]),167 (set([7]), set("seven")),168 (tuple("eight"), (8, -8, 8)),169 (b'\xc3\xb4', b"name"),170 (b'\xc3\xb4', totext("other")),171 ])172 assert result == ["1.0--1.1",173 "2--202",174 "three-three hundred",175 "True-False",176 "None-None",177 "foo-bar",178 "str-int",179 "a7-b7",180 "a8-b8",181 "a9-b9",182 "\\xc3\\xb4-name",183 "\\xc3\\xb4-other",184 ]185 def test_idmaker_enum(self):186 from _pytest.python import idmaker187 enum = pytest.importorskip("enum")188 e = enum.Enum("Foo", "one, two")189 result = idmaker(("a", "b"), [(e.one, e.two)])190 assert result == ["Foo.one-Foo.two"]191 @pytest.mark.issue351192 def test_idmaker_idfn(self):193 from _pytest.python import idmaker194 def ids(val):195 if isinstance(val, Exception):196 return repr(val)197 result = idmaker(("a", "b"), [(10.0, IndexError()),198 (20, KeyError()),199 ("three", [1, 2, 3]),200 ], idfn=ids)201 assert result == ["10.0-IndexError()",202 "20-KeyError()",203 "three-b2",204 ]205 @pytest.mark.issue351206 def test_idmaker_idfn_unique_names(self):207 from _pytest.python import idmaker208 def ids(val):209 return 'a'210 result = idmaker(("a", "b"), [(10.0, IndexError()),211 (20, KeyError()),212 ("three", [1, 2, 3]),213 ], idfn=ids)214 assert result == ["0a-a",215 "1a-a",216 "2a-a",217 ]218 @pytest.mark.issue351219 def test_idmaker_idfn_exception(self):220 from _pytest.python import idmaker221 def ids(val):222 raise Exception("bad code")223 result = idmaker(("a", "b"), [(10.0, IndexError()),224 (20, KeyError()),225 ("three", [1, 2, 3]),226 ], idfn=ids)227 assert result == ["10.0-b0",228 "20-b1",229 "three-b2",230 ]231 def test_addcall_and_parametrize(self):232 def func(x, y): pass233 metafunc = self.Metafunc(func)234 metafunc.addcall({'x': 1})235 metafunc.parametrize('y', [2,3])236 assert len(metafunc._calls) == 2237 assert metafunc._calls[0].funcargs == {'x': 1, 'y': 2}238 assert metafunc._calls[1].funcargs == {'x': 1, 'y': 3}239 assert metafunc._calls[0].id == "0-2"240 assert metafunc._calls[1].id == "0-3"241 @pytest.mark.issue714242 def test_parametrize_indirect(self):243 def func(x, y): pass244 metafunc = self.Metafunc(func)245 metafunc.parametrize('x', [1], indirect=True)246 metafunc.parametrize('y', [2,3], indirect=True)247 assert len(metafunc._calls) == 2248 assert metafunc._calls[0].funcargs == {}249 assert metafunc._calls[1].funcargs == {}250 assert metafunc._calls[0].params == dict(x=1,y=2)251 assert metafunc._calls[1].params == dict(x=1,y=3)252 @pytest.mark.issue714253 def test_parametrize_indirect_list(self):254 def func(x, y): pass255 metafunc = self.Metafunc(func)256 metafunc.parametrize('x, y', [('a', 'b')], indirect=['x'])257 assert metafunc._calls[0].funcargs == dict(y='b')258 assert metafunc._calls[0].params == dict(x='a')259 @pytest.mark.issue714260 def test_parametrize_indirect_list_all(self):261 def func(x, y): pass262 metafunc = self.Metafunc(func)263 metafunc.parametrize('x, y', [('a', 'b')], indirect=['x', 'y'])264 assert metafunc._calls[0].funcargs == {}265 assert metafunc._calls[0].params == dict(x='a', y='b')266 @pytest.mark.issue714267 def test_parametrize_indirect_list_empty(self):268 def func(x, y): pass269 metafunc = self.Metafunc(func)270 metafunc.parametrize('x, y', [('a', 'b')], indirect=[])271 assert metafunc._calls[0].funcargs == dict(x='a', y='b')272 assert metafunc._calls[0].params == {}273 @pytest.mark.issue714274 def test_parametrize_indirect_list_functional(self, testdir):275 """276 Test parametrization with 'indirect' parameter applied on277 particular arguments. As y is is direct, its value should278 be used directly rather than being passed to the fixture279 y.280 :param testdir: the instance of Testdir class, a temporary281 test directory.282 """283 testdir.makepyfile("""284 import pytest285 @pytest.fixture(scope='function')286 def x(request):287 return request.param * 3288 @pytest.fixture(scope='function')289 def y(request):290 return request.param * 2291 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])292 def test_simple(x,y):293 assert len(x) == 3294 assert len(y) == 1295 """)296 result = testdir.runpytest("-v")297 result.stdout.fnmatch_lines([298 "*test_simple*a-b*",299 "*1 passed*",300 ])301 @pytest.mark.issue714302 def test_parametrize_indirect_list_error(self, testdir):303 def func(x, y): pass304 metafunc = self.Metafunc(func)305 with pytest.raises(ValueError):306 metafunc.parametrize('x, y', [('a', 'b')], indirect=['x', 'z'])307 @pytest.mark.issue714308 def test_parametrize_uses_no_fixture_error_indirect_false(self, testdir):309 """The 'uses no fixture' error tells the user at collection time310 that the parametrize data they've set up doesn't correspond to the311 fixtures in their test function, rather than silently ignoring this312 and letting the test potentially pass.313 """314 testdir.makepyfile("""315 import pytest316 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=False)317 def test_simple(x):318 assert len(x) == 3319 """)320 result = testdir.runpytest("--collect-only")321 result.stdout.fnmatch_lines([322 "*uses no fixture 'y'*",323 ])324 @pytest.mark.issue714325 def test_parametrize_uses_no_fixture_error_indirect_true(self, testdir):326 testdir.makepyfile("""327 import pytest328 @pytest.fixture(scope='function')329 def x(request):330 return request.param * 3331 @pytest.fixture(scope='function')332 def y(request):333 return request.param * 2334 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=True)335 def test_simple(x):336 assert len(x) == 3337 """)338 result = testdir.runpytest("--collect-only")339 result.stdout.fnmatch_lines([340 "*uses no fixture 'y'*",341 ])342 @pytest.mark.issue714343 def test_parametrize_indirect_uses_no_fixture_error_indirect_list(self, testdir):344 testdir.makepyfile("""345 import pytest346 @pytest.fixture(scope='function')347 def x(request):348 return request.param * 3349 @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])350 def test_simple(x):351 assert len(x) == 3352 """)353 result = testdir.runpytest("--collect-only")354 result.stdout.fnmatch_lines([355 "*uses no fixture 'y'*",356 ])357 def test_addcalls_and_parametrize_indirect(self):358 def func(x, y): pass359 metafunc = self.Metafunc(func)360 metafunc.addcall(param="123")361 metafunc.parametrize('x', [1], indirect=True)362 metafunc.parametrize('y', [2,3], indirect=True)363 assert len(metafunc._calls) == 2364 assert metafunc._calls[0].funcargs == {}365 assert metafunc._calls[1].funcargs == {}366 assert metafunc._calls[0].params == dict(x=1,y=2)367 assert metafunc._calls[1].params == dict(x=1,y=3)368 def test_parametrize_functional(self, testdir):369 testdir.makepyfile("""370 def pytest_generate_tests(metafunc):371 metafunc.parametrize('x', [1,2], indirect=True)372 metafunc.parametrize('y', [2])373 def pytest_funcarg__x(request):374 return request.param * 10375 #def pytest_funcarg__y(request):376 # return request.param377 def test_simple(x,y):378 assert x in (10,20)379 assert y == 2380 """)381 result = testdir.runpytest("-v")382 result.stdout.fnmatch_lines([383 "*test_simple*1-2*",384 "*test_simple*2-2*",385 "*2 passed*",386 ])387 def test_parametrize_onearg(self):388 metafunc = self.Metafunc(lambda x: None)389 metafunc.parametrize("x", [1,2])390 assert len(metafunc._calls) == 2391 assert metafunc._calls[0].funcargs == dict(x=1)392 assert metafunc._calls[0].id == "1"393 assert metafunc._calls[1].funcargs == dict(x=2)394 assert metafunc._calls[1].id == "2"395 def test_parametrize_onearg_indirect(self):396 metafunc = self.Metafunc(lambda x: None)397 metafunc.parametrize("x", [1,2], indirect=True)398 assert metafunc._calls[0].params == dict(x=1)399 assert metafunc._calls[0].id == "1"400 assert metafunc._calls[1].params == dict(x=2)401 assert metafunc._calls[1].id == "2"402 def test_parametrize_twoargs(self):403 metafunc = self.Metafunc(lambda x,y: None)404 metafunc.parametrize(("x", "y"), [(1,2), (3,4)])405 assert len(metafunc._calls) == 2406 assert metafunc._calls[0].funcargs == dict(x=1, y=2)407 assert metafunc._calls[0].id == "1-2"408 assert metafunc._calls[1].funcargs == dict(x=3, y=4)409 assert metafunc._calls[1].id == "3-4"410 def test_parametrize_multiple_times(self, testdir):411 testdir.makepyfile("""412 import pytest413 pytestmark = pytest.mark.parametrize("x", [1,2])414 def test_func(x):415 assert 0, x416 class TestClass:417 pytestmark = pytest.mark.parametrize("y", [3,4])418 def test_meth(self, x, y):419 assert 0, x420 """)421 result = testdir.runpytest()422 assert result.ret == 1423 result.assert_outcomes(failed=6)424 def test_parametrize_CSV(self, testdir):425 testdir.makepyfile("""426 import pytest427 @pytest.mark.parametrize("x, y,", [(1,2), (2,3)])428 def test_func(x, y):429 assert x+1 == y430 """)431 reprec = testdir.inline_run()432 reprec.assertoutcome(passed=2)433 def test_parametrize_class_scenarios(self, testdir):434 testdir.makepyfile("""435 # same as doc/en/example/parametrize scenario example436 def pytest_generate_tests(metafunc):437 idlist = []438 argvalues = []439 for scenario in metafunc.cls.scenarios:440 idlist.append(scenario[0])441 items = scenario[1].items()442 argnames = [x[0] for x in items]443 argvalues.append(([x[1] for x in items]))444 metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")445 class Test(object):446 scenarios = [['1', {'arg': {1: 2}, "arg2": "value2"}],447 ['2', {'arg':'value2', "arg2": "value2"}]]448 def test_1(self, arg, arg2):449 pass450 def test_2(self, arg2, arg):451 pass452 def test_3(self, arg, arg2):453 pass454 """)455 result = testdir.runpytest("-v")456 assert result.ret == 0457 result.stdout.fnmatch_lines("""458 *test_1*1*459 *test_2*1*460 *test_3*1*461 *test_1*2*462 *test_2*2*463 *test_3*2*464 *6 passed*465 """)466 def test_format_args(self):467 def function1(): pass468 assert funcargs._format_args(function1) == '()'469 def function2(arg1): pass470 assert funcargs._format_args(function2) == "(arg1)"471 def function3(arg1, arg2="qwe"): pass472 assert funcargs._format_args(function3) == "(arg1, arg2='qwe')"473 def function4(arg1, *args, **kwargs): pass474 assert funcargs._format_args(function4) == "(arg1, *args, **kwargs)"475class TestMetafuncFunctional:476 def test_attributes(self, testdir):477 p = testdir.makepyfile("""478 # assumes that generate/provide runs in the same process479 import py, pytest480 def pytest_generate_tests(metafunc):481 metafunc.addcall(param=metafunc)482 def pytest_funcarg__metafunc(request):483 assert request._pyfuncitem._genid == "0"484 return request.param485 def test_function(metafunc, pytestconfig):486 assert metafunc.config == pytestconfig487 assert metafunc.module.__name__ == __name__488 assert metafunc.function == test_function489 assert metafunc.cls is None490 class TestClass:491 def test_method(self, metafunc, pytestconfig):492 assert metafunc.config == pytestconfig493 assert metafunc.module.__name__ == __name__494 if py.std.sys.version_info > (3, 0):495 unbound = TestClass.test_method496 else:497 unbound = TestClass.test_method.im_func498 # XXX actually have an unbound test function here?499 assert metafunc.function == unbound500 assert metafunc.cls == TestClass501 """)502 result = testdir.runpytest(p, "-v")503 result.assert_outcomes(passed=2)504 def test_addcall_with_two_funcargs_generators(self, testdir):505 testdir.makeconftest("""506 def pytest_generate_tests(metafunc):507 assert "arg1" in metafunc.fixturenames508 metafunc.addcall(funcargs=dict(arg1=1, arg2=2))509 """)510 p = testdir.makepyfile("""511 def pytest_generate_tests(metafunc):512 metafunc.addcall(funcargs=dict(arg1=1, arg2=1))513 class TestClass:514 def test_myfunc(self, arg1, arg2):515 assert arg1 == arg2516 """)517 result = testdir.runpytest("-v", p)518 result.stdout.fnmatch_lines([519 "*test_myfunc*0*PASS*",520 "*test_myfunc*1*FAIL*",521 "*1 failed, 1 passed*"522 ])523 def test_two_functions(self, testdir):524 p = testdir.makepyfile("""525 def pytest_generate_tests(metafunc):526 metafunc.addcall(param=10)527 metafunc.addcall(param=20)528 def pytest_funcarg__arg1(request):529 return request.param530 def test_func1(arg1):531 assert arg1 == 10532 def test_func2(arg1):533 assert arg1 in (10, 20)534 """)535 result = testdir.runpytest("-v", p)536 result.stdout.fnmatch_lines([537 "*test_func1*0*PASS*",538 "*test_func1*1*FAIL*",539 "*test_func2*PASS*",540 "*1 failed, 3 passed*"541 ])542 def test_noself_in_method(self, testdir):543 p = testdir.makepyfile("""544 def pytest_generate_tests(metafunc):545 assert 'xyz' not in metafunc.fixturenames546 class TestHello:547 def test_hello(xyz):548 pass549 """)550 result = testdir.runpytest(p)551 result.assert_outcomes(passed=1)552 def test_generate_plugin_and_module(self, testdir):553 testdir.makeconftest("""554 def pytest_generate_tests(metafunc):555 assert "arg1" in metafunc.fixturenames556 metafunc.addcall(id="world", param=(2,100))557 """)558 p = testdir.makepyfile("""559 def pytest_generate_tests(metafunc):560 metafunc.addcall(param=(1,1), id="hello")561 def pytest_funcarg__arg1(request):562 return request.param[0]563 def pytest_funcarg__arg2(request):564 return request.param[1]565 class TestClass:566 def test_myfunc(self, arg1, arg2):567 assert arg1 == arg2568 """)569 result = testdir.runpytest("-v", p)570 result.stdout.fnmatch_lines([571 "*test_myfunc*hello*PASS*",572 "*test_myfunc*world*FAIL*",573 "*1 failed, 1 passed*"574 ])575 def test_generate_tests_in_class(self, testdir):576 p = testdir.makepyfile("""577 class TestClass:578 def pytest_generate_tests(self, metafunc):579 metafunc.addcall(funcargs={'hello': 'world'}, id="hello")580 def test_myfunc(self, hello):581 assert hello == "world"582 """)583 result = testdir.runpytest("-v", p)584 result.stdout.fnmatch_lines([585 "*test_myfunc*hello*PASS*",586 "*1 passed*"587 ])588 def test_two_functions_not_same_instance(self, testdir):589 p = testdir.makepyfile("""590 def pytest_generate_tests(metafunc):591 metafunc.addcall({'arg1': 10})592 metafunc.addcall({'arg1': 20})593 class TestClass:594 def test_func(self, arg1):595 assert not hasattr(self, 'x')596 self.x = 1597 """)598 result = testdir.runpytest("-v", p)599 result.stdout.fnmatch_lines([600 "*test_func*0*PASS*",601 "*test_func*1*PASS*",602 "*2 pass*",603 ])604 def test_issue28_setup_method_in_generate_tests(self, testdir):605 p = testdir.makepyfile("""606 def pytest_generate_tests(metafunc):607 metafunc.addcall({'arg1': 1})608 class TestClass:609 def test_method(self, arg1):610 assert arg1 == self.val611 def setup_method(self, func):612 self.val = 1613 """)614 result = testdir.runpytest(p)615 result.assert_outcomes(passed=1)616 def test_parametrize_functional2(self, testdir):617 testdir.makepyfile("""618 def pytest_generate_tests(metafunc):619 metafunc.parametrize("arg1", [1,2])620 metafunc.parametrize("arg2", [4,5])621 def test_hello(arg1, arg2):622 assert 0, (arg1, arg2)623 """)624 result = testdir.runpytest()625 result.stdout.fnmatch_lines([626 "*(1, 4)*",627 "*(1, 5)*",628 "*(2, 4)*",629 "*(2, 5)*",630 "*4 failed*",631 ])632 def test_parametrize_and_inner_getfuncargvalue(self, testdir):633 p = testdir.makepyfile("""634 def pytest_generate_tests(metafunc):635 metafunc.parametrize("arg1", [1], indirect=True)636 metafunc.parametrize("arg2", [10], indirect=True)637 def pytest_funcarg__arg1(request):638 x = request.getfuncargvalue("arg2")639 return x + request.param640 def pytest_funcarg__arg2(request):641 return request.param642 def test_func1(arg1, arg2):643 assert arg1 == 11644 """)645 result = testdir.runpytest("-v", p)646 result.stdout.fnmatch_lines([647 "*test_func1*1*PASS*",648 "*1 passed*"649 ])650 def test_parametrize_on_setup_arg(self, testdir):651 p = testdir.makepyfile("""652 def pytest_generate_tests(metafunc):653 assert "arg1" in metafunc.fixturenames654 metafunc.parametrize("arg1", [1], indirect=True)655 def pytest_funcarg__arg1(request):656 return request.param657 def pytest_funcarg__arg2(request, arg1):658 return 10 * arg1659 def test_func(arg2):660 assert arg2 == 10661 """)662 result = testdir.runpytest("-v", p)663 result.stdout.fnmatch_lines([664 "*test_func*1*PASS*",665 "*1 passed*"666 ])667 def test_parametrize_with_ids(self, testdir):668 testdir.makepyfile("""669 import pytest670 def pytest_generate_tests(metafunc):671 metafunc.parametrize(("a", "b"), [(1,1), (1,2)],672 ids=["basic", "advanced"])673 def test_function(a, b):674 assert a == b675 """)676 result = testdir.runpytest("-v")677 assert result.ret == 1678 result.stdout.fnmatch_lines_random([679 "*test_function*basic*PASSED",680 "*test_function*advanced*FAILED",681 ])682 def test_parametrize_without_ids(self, testdir):683 testdir.makepyfile("""684 import pytest685 def pytest_generate_tests(metafunc):686 metafunc.parametrize(("a", "b"),687 [(1,object()), (1.3,object())])688 def test_function(a, b):689 assert 1690 """)691 result = testdir.runpytest("-v")692 result.stdout.fnmatch_lines("""693 *test_function*1-b0*694 *test_function*1.3-b1*695 """)696 @pytest.mark.parametrize(("scope", "length"),697 [("module", 2), ("function", 4)])698 def test_parametrize_scope_overrides(self, testdir, scope, length):699 testdir.makepyfile("""700 import pytest701 l = []702 def pytest_generate_tests(metafunc):703 if "arg" in metafunc.funcargnames:704 metafunc.parametrize("arg", [1,2], indirect=True,705 scope=%r)706 def pytest_funcarg__arg(request):707 l.append(request.param)708 return request.param709 def test_hello(arg):710 assert arg in (1,2)711 def test_world(arg):712 assert arg in (1,2)713 def test_checklength():714 assert len(l) == %d715 """ % (scope, length))716 reprec = testdir.inline_run()717 reprec.assertoutcome(passed=5)718 def test_parametrize_issue323(self, testdir):719 testdir.makepyfile("""720 import pytest721 @pytest.fixture(scope='module', params=range(966))722 def foo(request):723 return request.param724 def test_it(foo):725 pass726 def test_it2(foo):727 pass728 """)729 reprec = testdir.inline_run("--collect-only")730 assert not reprec.getcalls("pytest_internalerror")731 def test_usefixtures_seen_in_generate_tests(self, testdir):732 testdir.makepyfile("""733 import pytest734 def pytest_generate_tests(metafunc):735 assert "abc" in metafunc.fixturenames736 metafunc.parametrize("abc", [1])737 @pytest.mark.usefixtures("abc")738 def test_function():739 pass740 """)741 reprec = testdir.runpytest()742 reprec.assert_outcomes(passed=1)743 def test_generate_tests_only_done_in_subdir(self, testdir):744 sub1 = testdir.mkpydir("sub1")745 sub2 = testdir.mkpydir("sub2")746 sub1.join("conftest.py").write(_pytest._code.Source("""747 def pytest_generate_tests(metafunc):748 assert metafunc.function.__name__ == "test_1"749 """))750 sub2.join("conftest.py").write(_pytest._code.Source("""751 def pytest_generate_tests(metafunc):752 assert metafunc.function.__name__ == "test_2"753 """))754 sub1.join("test_in_sub1.py").write("def test_1(): pass")755 sub2.join("test_in_sub2.py").write("def test_2(): pass")756 result = testdir.runpytest("-v", "-s", sub1, sub2, sub1)757 result.assert_outcomes(passed=3)758 def test_generate_same_function_names_issue403(self, testdir):759 testdir.makepyfile("""760 import pytest761 def make_tests():762 @pytest.mark.parametrize("x", range(2))763 def test_foo(x):764 pass765 return test_foo766 test_x = make_tests()767 test_y = make_tests()768 """)769 reprec = testdir.runpytest()770 reprec.assert_outcomes(passed=4)771 @pytest.mark.issue463772 @pytest.mark.parametrize('attr', ['parametrise', 'parameterize',773 'parameterise'])774 def test_parametrize_misspelling(self, testdir, attr):775 testdir.makepyfile("""776 import pytest777 @pytest.mark.{0}("x", range(2))778 def test_foo(x):779 pass780 """.format(attr))781 reprec = testdir.inline_run('--collectonly')782 failures = reprec.getfailures()783 assert len(failures) == 1784 expectederror = "MarkerError: test_foo has '{0}', spelling should be 'parametrize'".format(attr)785 assert expectederror in failures[0].longrepr.reprcrash.message786class TestMarkersWithParametrization:787 pytestmark = pytest.mark.issue308788 def test_simple_mark(self, testdir):789 s = """790 import pytest791 @pytest.mark.foo792 @pytest.mark.parametrize(("n", "expected"), [793 (1, 2),794 pytest.mark.bar((1, 3)),795 (2, 3),796 ])797 def test_increment(n, expected):798 assert n + 1 == expected799 """800 items = testdir.getitems(s)801 assert len(items) == 3802 for item in items:803 assert 'foo' in item.keywords804 assert 'bar' not in items[0].keywords805 assert 'bar' in items[1].keywords806 assert 'bar' not in items[2].keywords807 def test_select_based_on_mark(self, testdir):808 s = """809 import pytest810 @pytest.mark.parametrize(("n", "expected"), [811 (1, 2),812 pytest.mark.foo((2, 3)),813 (3, 4),814 ])815 def test_increment(n, expected):816 assert n + 1 == expected817 """818 testdir.makepyfile(s)819 rec = testdir.inline_run("-m", 'foo')820 passed, skipped, fail = rec.listoutcomes()821 assert len(passed) == 1822 assert len(skipped) == 0823 assert len(fail) == 0824 @pytest.mark.xfail(reason="is this important to support??")825 def test_nested_marks(self, testdir):826 s = """827 import pytest828 mastermark = pytest.mark.foo(pytest.mark.bar)829 @pytest.mark.parametrize(("n", "expected"), [830 (1, 2),831 mastermark((1, 3)),832 (2, 3),833 ])834 def test_increment(n, expected):835 assert n + 1 == expected836 """837 items = testdir.getitems(s)838 assert len(items) == 3839 for mark in ['foo', 'bar']:840 assert mark not in items[0].keywords841 assert mark in items[1].keywords842 assert mark not in items[2].keywords843 def test_simple_xfail(self, testdir):844 s = """845 import pytest846 @pytest.mark.parametrize(("n", "expected"), [847 (1, 2),848 pytest.mark.xfail((1, 3)),849 (2, 3),850 ])851 def test_increment(n, expected):852 assert n + 1 == expected853 """854 testdir.makepyfile(s)855 reprec = testdir.inline_run()856 # xfail is skip??857 reprec.assertoutcome(passed=2, skipped=1)858 def test_simple_xfail_single_argname(self, testdir):859 s = """860 import pytest861 @pytest.mark.parametrize("n", [862 2,863 pytest.mark.xfail(3),864 4,865 ])866 def test_isEven(n):867 assert n % 2 == 0868 """869 testdir.makepyfile(s)870 reprec = testdir.inline_run()871 reprec.assertoutcome(passed=2, skipped=1)872 def test_xfail_with_arg(self, testdir):873 s = """874 import pytest875 @pytest.mark.parametrize(("n", "expected"), [876 (1, 2),877 pytest.mark.xfail("True")((1, 3)),878 (2, 3),879 ])880 def test_increment(n, expected):881 assert n + 1 == expected882 """883 testdir.makepyfile(s)884 reprec = testdir.inline_run()885 reprec.assertoutcome(passed=2, skipped=1)886 def test_xfail_with_kwarg(self, testdir):887 s = """888 import pytest889 @pytest.mark.parametrize(("n", "expected"), [890 (1, 2),891 pytest.mark.xfail(reason="some bug")((1, 3)),892 (2, 3),893 ])894 def test_increment(n, expected):895 assert n + 1 == expected896 """897 testdir.makepyfile(s)898 reprec = testdir.inline_run()899 reprec.assertoutcome(passed=2, skipped=1)900 def test_xfail_with_arg_and_kwarg(self, testdir):901 s = """902 import pytest903 @pytest.mark.parametrize(("n", "expected"), [904 (1, 2),905 pytest.mark.xfail("True", reason="some bug")((1, 3)),906 (2, 3),907 ])908 def test_increment(n, expected):909 assert n + 1 == expected910 """911 testdir.makepyfile(s)912 reprec = testdir.inline_run()913 reprec.assertoutcome(passed=2, skipped=1)914 def test_xfail_passing_is_xpass(self, testdir):915 s = """916 import pytest917 @pytest.mark.parametrize(("n", "expected"), [918 (1, 2),919 pytest.mark.xfail("sys.version > 0", reason="some bug")((2, 3)),920 (3, 4),921 ])922 def test_increment(n, expected):923 assert n + 1 == expected924 """925 testdir.makepyfile(s)926 reprec = testdir.inline_run()927 # xpass is fail, obviously :)928 reprec.assertoutcome(passed=2, failed=1)929 def test_parametrize_called_in_generate_tests(self, testdir):930 s = """931 import pytest932 def pytest_generate_tests(metafunc):933 passingTestData = [(1, 2),934 (2, 3)]935 failingTestData = [(1, 3),936 (2, 2)]937 testData = passingTestData + [pytest.mark.xfail(d)938 for d in failingTestData]939 metafunc.parametrize(("n", "expected"), testData)940 def test_increment(n, expected):941 assert n + 1 == expected942 """943 testdir.makepyfile(s)944 reprec = testdir.inline_run()945 reprec.assertoutcome(passed=2, skipped=2)946 @pytest.mark.issue290947 def test_parametrize_ID_generation_string_int_works(self, testdir):948 testdir.makepyfile("""949 import pytest950 @pytest.fixture951 def myfixture():952 return 'example'953 @pytest.mark.parametrize(954 'limit', (0, '0'))955 def test_limit(limit, myfixture):956 return957 """)958 reprec = testdir.inline_run()...

Full Screen

Full Screen

test.py

Source:test.py Github

copy

Full Screen

...11c = Value(3.1264e2, 1.268)12A = np.array([[a, a], [b, b], [c, c]])13B = Value([a.x] * 5, a.ux)14C = Value([b.x] * 5, [b.ux] * 5)15@pytest.mark.parametrize('v, x', [16 (a, a.x),17 (A, np.array([[a.x, a.x], [b.x, b.x], [c.x, c.x]])),18 (B, a.x),19 (a.x, a.x)],20 ids=['Single', 'Array of values', 'Value array', 'Number'])21def test_val(v, x):22 assert np.all(val(v) == x)23@pytest.mark.parametrize('v, x', [24 (a, a.ux),25 (A, np.array([[a.ux, a.ux], [b.ux, b.ux], [c.ux, c.ux]])),26 (B, a.ux),27 (a.x, 0)],28 ids=['Single', 'Array of values', 'Value array', 'Number'])29def test_unc(v, x):30 assert np.all(unc(v) == x)31def test_set_unc():32 v = set_unc(0.234, 0.0052)33 assert isinstance(v, Value)34 assert v.x == 0.23435 assert v.ux == 0.005236 v = set_unc(a, 0.0052)37 assert isinstance(v, Value)38 assert v.x == a.x39 assert v.ux == 0.005240 v = set_unc([0.234] * 8, 0.0052)41 assert isinstance(v, np.ndarray)42 assert v.shape == (8, )43 assert np.mean(unc(v)) == 0.005244 v = set_unc([0.234] * 8, [0.0052] * 8)45 assert isinstance(v, np.ndarray)46 assert v.shape == (8, )47 assert np.mean(unc(v)) == 0.005248 with pytest.raises(ValueError):49 set_unc(np.random.random((3, 2, 1)), np.random.random((4, 2, 1)))50def test_constructor():51 v = Value(3.1415, 0.0012)52 assert v.x == 3.1415 == v.val53 assert v.ux == 0.0012 == v.unc54 with pytest.raises(ValueError):55 Value(3.14, -0.28)56 V = Value([3.1415] * 8, 0.0012)57 assert V.x.shape == (8, )58 assert V.ux.shape == (8, )59 assert np.mean(V.ux) == 0.001260 V = Value([3.1415] * 8, [0.0012] * 8)61 assert V.x.shape == (8, )62 assert V.ux.shape == (8, )63 assert np.mean(V.ux) == 0.001264 with pytest.raises(ValueError):65 Value(np.random.random((3, 2, 1)), np.random.random((4, 2, 1)))66 with pytest.raises(ValueError):67 Value(1j, 0)68 Value(1, 2j)69@pytest.mark.parametrize('x, y, r', [70 (a.x, a, False),71 (a, a.x, False),72 (a, Value(a.x, a.ux * 5), False),73 (b, a, True),74 (a, a - 0.0001, False),75 (A, A, False),76 (B, C, False)],77 ids=['Right', 'Left', 'Both', 'Different', 'Within unc', 'Array eq', 'Array dif'])78def test_smaller(x, y, r):79 assert np.all((x < y) == r)80@pytest.mark.parametrize('x, y, r', [81 (1, a, Value(a.x + 1, a.ux)),82 (a, 1, Value(a.x + 1, a.ux)),83 (a, b, Value(a.x + b.x, np.hypot(a.ux, b.ux))),84 (1, A, np.array([[a+1, a+1], [b+1, b+1], [c+1, c+1]])),85 (a, A, np.array([[a+a, a+a], [b+a, b+a], [c+a, c+a]])),86 (1, B, Value(1 + B.x, B.ux)),87 (a, B, Value(a.x + B.x, np.hypot(a.ux, B.ux))),88 (A, A, np.array([[a+a, a+a], [b+b, b+b], [c+c, c+c]])),89 (B, C, Value(B.x + C.x, np.hypot(B.ux, C.ux))),90 ],91 ids=['Right', 'Left', 'Both', 'Number + Array', 'Value + Array', 'Array of values',92 'Number + Valued array', 'Value + Valued array', 'Valued array'])93def test_add(x, y, r):94 z = x + y95 assert np.all(val(z) == val(r))96 assert np.all(unc(z) == unc(r))97@pytest.mark.parametrize('x, y, r', [98 (1, a, Value(a.x + 1, a.ux)),99 (a.copy(), 1, Value(a.x + 1, a.ux)),100 (a.copy(), b, Value(a.x + b.x, np.hypot(a.ux, b.ux))),101 (B.copy(), C, Value(B.x + C.x, np.hypot(B.ux, C.ux))),102 ],103 ids=['Right', 'Left', 'Both', 'Array'])104def test_iadd(x, y, r):105 x += y106 assert isinstance(x, Value)107 assert np.all(x.x == r.x)108 assert np.all(x.ux == r.ux)109@pytest.mark.parametrize('x, y, r', [110 (1, a, Value(1 - a.x, a.ux)),111 (a, 1, Value(a.x - 1, a.ux)),112 (a, b, Value(a.x - b.x, np.hypot(a.ux, b.ux))),113 (A, A, np.array([[a-a, a-a], [b-b, b-b], [c-c, c-c]])),114 (B, C, Value(B.x - C.x, np.hypot(B.ux, C.ux))),115 ],116 ids=['Right', 'Left', 'Both', 'Array of values', 'Valued array'])117def test_sub(x, y, r):118 z = x - y119 assert np.all(val(z) == val(r))120 assert np.all(unc(z) == unc(r))121@pytest.mark.parametrize('x, y, r', [122 (1, a, Value(1 - a.x, a.ux)),123 (a.copy(), 1, Value(a.x - 1, a.ux)),124 (a.copy(), b, Value(a.x - b.x, np.hypot(a.ux, b.ux))),125 (B.copy(), C, Value(B.x - C.x, np.hypot(B.ux, C.ux))),126 ],127 ids=['Right', 'Left', 'Both', 'Array'])128def test_isub(x, y, r):129 x -= y130 assert isinstance(x, Value)131 assert np.all(x.x == r.x)132 assert np.all(x.ux == r.ux)133@pytest.mark.parametrize('x, y, r', [134 (2, a, Value(2 * a.x, 2 * a.ux)),135 (a, 2, Value(a.x * 2, 2 * a.ux)),136 (a, b, Value(a.x * b.x, np.hypot(a.ux * b.x, a.x * b.ux))),137 (A, A, np.array([[a*a, a*a], [b*b, b*b], [c*c, c*c]])),138 (B, C, Value(B.x * C.x, np.hypot(B.ux * C.x, B.x * C.ux))),139 ],140 ids=['Right', 'Left', 'Both', 'Array of values', 'Valued array'])141def test_mul(x, y, r):142 z = x * y143 assert np.all(val(z) == val(r))144 assert np.all(unc(z) == unc(r))145@pytest.mark.parametrize('x, y, r', [146 (2, a, Value(2 * a.x, 2 * a.ux)),147 (a.copy(), 2, Value(a.x * 2, 2 * a.ux)),148 (a.copy(), b, Value(a.x * b.x, np.hypot(a.ux * b.x, a.x * b.ux))),149 (B.copy(), C, Value(B.x * C.x, np.hypot(B.ux * C.x, B.x * C.ux))),150 ],151 ids=['Right', 'Left', 'Both', 'Array'])152def test_imul(x, y, r):153 x *= y154 assert isinstance(x, Value)155 assert np.all(x.x == r.x)156 assert np.all(x.ux == r.ux)157@pytest.mark.parametrize('x, y, r', [158 (2, a, Value(2 / a.x, 2 * a.ux / a.x**2)),159 (a, 2, Value(a.x / 2, a.ux / 2)),160 (a, b, Value(a.x / b.x, np.hypot(a.ux / b.x, a.x * b.ux / b.x**2))),161 (B, C, Value(B.x / C.x, np.hypot(B.ux / C.x, B.x * C.ux / C.x**2))),162 ],163 ids=['Right', 'Left', 'Both', 'Array'])164def test_div(x, y, r):165 z = x / y166 assert isinstance(z, Value)167 assert np.all(z.x == r.x)168 assert np.all(z.ux == r.ux)169@pytest.mark.parametrize('x, y, r', [170 (2, a, Value(2 // a.x, 2 * a.ux // a.x**2)),171 (a, 2, Value(a.x // 2, a.ux // 2)),172 (a, b, Value(a.x // b.x, np.hypot(a.ux // b.x, a.x * b.ux // b.x**2))),173 (B, C, Value(B.x // C.x, np.hypot(B.ux // C.x, B.x * C.ux // C.x**2))),174 ],175 ids=['Right', 'Left', 'Both', 'Array'])176def test_floordiv(x, y, r):177 z = x // y178 assert isinstance(z, Value)179 assert np.all(z.x == r.x)180 assert np.all(z.ux == r.ux)181@pytest.mark.parametrize('x, y, r', [182 (2, a, Value(2 / a.x, 2 * a.ux / a.x**2)),183 (a.copy(), 2, Value(a.x / 2, a.ux / 2)),184 (a.copy(), b, Value(a.x / b.x, np.hypot(a.ux / b.x, a.x * b.ux / b.x**2))),185 (B.copy(), C, Value(B.x / C.x, np.hypot(B.ux / C.x, B.x * C.ux / C.x**2))),186 ],187 ids=['Right', 'Left', 'Both', 'Array'])188def test_idiv(x, y, r):189 x /= y190 assert isinstance(x, Value)191 assert np.all(x.x == r.x)192 assert np.all(x.ux == r.ux)193@pytest.mark.parametrize('x, y, r', [194 (2, a, Value(2 ** a.x, abs(2**a.x * np.log(2) * a.ux))),195 (a, 2, Value(a.x ** 2, abs(2 * a.x**(2 - 1)) * a.ux)),196 (a, b, Value(a.x ** b.x, np.hypot(b.x * a.x**(b.x-1) * a.ux, a.x**b.x * np.log(np.abs(a.x)) * b.ux))),197 (B, C, Value(B.x ** C.x, np.hypot(C.x * B.x**(C.x-1) * B.ux, B.x**C.x * np.log(np.abs(B.x)) * C.ux)))198 ],199 ids=['Right', 'Left', 'Both', 'Array'])200def test_pow(x, y, r):201 z = x**y202 assert isinstance(z, Value)203 assert np.all(z.x == r.x)204 assert np.all(z.ux == r.ux)205@pytest.mark.parametrize('x, r', [206 (a, Value(-a.x, a.ux)),207 (A, np.array([[-a, -a], [-b, -b], [-c, -c]])),208 (B, Value(-B.x, B.ux))209 ], ids=['Value', 'Array of values', 'Value array'])210def test_neg(x, r):211 z = -x212 assert np.all(val(z) == val(r))213 assert np.all(unc(z) == unc(r))214@pytest.mark.parametrize('x, r', [215 (b, Value(abs(b.x), b.ux)),216 (A, np.array([[a, a], [-b, -b], [c, c]])),217 (B, Value(B.x, B.ux))218 ], ids=['Value', 'Array of values', 'Value array'])219def test_abs(x, r):220 z = abs(x)221 assert np.all(val(z) == val(r))222 assert np.all(unc(z) == unc(r))223@pytest.mark.parametrize('x, r', [224 (a, Value(1 / a.x, a.ux / a.x**2)),225 (A, np.array([[1 / a, 1 / a], [1 / b, 1 / b], [1 / c, 1 / c]])),226 (B, Value(1 / B.x, B.ux / B.x**2))227 ], ids=['Value', 'Array of values', 'Value array'])228def test_invert(x, r):229 z = ~x230 assert np.all(val(z) == val(r))231 assert np.all(unc(z) == unc(r))232@pytest.mark.parametrize('x, y, r', [233 (a.x, a, True),234 (a, a.x, True),235 (a, Value(a.x, a.ux * 5), True),236 (a, b, False),237 (a, a + 0.0001, False),238 (A, A, True),239 (B, C, False)],240 ids=['Right', 'Left', 'Both', 'Different', 'Within unc', 'Array eq', 'Array dif'])241def test_equality(x, y, r):242 assert np.all((x == y) == r)243 assert np.all((x != y) != r)244@pytest.mark.parametrize('x, y, r', [245 (a.x, a, True),246 (a, a.x, True),247 (a, Value(a.x, a.ux * 5), True),248 (b, a, False),249 (a, a - 0.0001, True),250 (A, A, True),251 (B, C, True)],252 ids=['Right', 'Left', 'Both', 'Different', 'Within unc', 'Array eq', 'Array dif'])253def test_greater_equal(x, y, r):254 assert np.all((x >= y) == r)255@pytest.mark.parametrize('x, y, r', [256 (a.x, a, False),257 (a, a.x, False),258 (a, Value(a.x, a.ux * 5), False),259 (b, a, False),260 (a, a - 0.0001, True),261 (A, A, False),262 (B, C, True)],263 ids=['Right', 'Left', 'Both', 'Different', 'Within unc', 'Array eq', 'Array dif'])264def test_greater(x, y, r):265 assert np.all((x > y) == r)266@pytest.mark.parametrize('x, y, r', [267 (a.x, a, True),268 (a, a.x, True),269 (a, Value(a.x, a.ux * 5), True),270 (b, a, True),271 (a, a - 0.0001, False),272 (A, A, True),273 (B, C, False)],274 ids=['Right', 'Left', 'Both', 'Different', 'Within unc', 'Array eq', 'Array dif'])275def test_smaller_equal(x, y, r):276 assert np.all((x <= y) == r)277@pytest.mark.parametrize('x, y, r', [278 (1, Value(1, 2), True),279 (1, Value(0.75, 0.05), False),280 (0.8, Value(0.75, 0.08), True),281 (0.8, Value(0.75, 0.05), True),282 (0.7, Value(0.75, 0.05), True),283 (Value(0.8, 0.2), Value(0.7, 0.04), False)],284 ids=['Inside', 'Outside', 'Inside float', 'Over upper limit', 'Over lower limit', 'Outside second value'])285def test_contains(x, y, r):286 assert (x in y) == r287@pytest.mark.parametrize('x, s', [288 (Value(2, 2), '2.0 ± 2.0'),289 (Value(0.2, 2), '0.2 ± 2.0'),290 (Value(0.2, 0.002385), '(200.0 ± 2.4)·10^-3'),291 (Value(0.02414, 0.002345), '(24.1 ± 2.3)·10^-3'),292 (Value(0.02415, 0.002365), '(24.2 ± 2.4)·10^-3')])293def test_print(x, s):294 assert str(x) == s295@pytest.mark.parametrize('x, p, r', [296 (0.145e-6, -8, 0.14e-6),297 (0.001456, -4, 0.0015),298 (0.0006666, -5, 0.00067),299 (0.123, -2, 0.12),300 (1, -1, 1.0),301 (22.22, 0, 22.0),302 (7684.65, 2, 77e2),303 (17.8e8, 8, 18e8)])304def test_round(x, p, r):305 v = Value(x, 10.0**p)306 assert abs(round(v) - r) < ϵ307@pytest.mark.parametrize('x, p, r', [308 (0.145e-6, -8, 0.14e-6),309 (0.001456, -4, 0.0014),310 (0.0006666, -5, 0.00066),311 (0.123, -2, 0.12),312 (1, -1, 1.0),313 (22.22, 0, 22.0),314 (7684.65, 2, 76e2),315 (17.8e8, 8, 17e8)])316def test_trunc(x, p, r):317 v = Value(x, 10.0**p)318 assert abs(trunc(v) - r) < ϵ319@pytest.mark.parametrize('x, p, r', [320 (0.145e-6, -8, 0.14e-6),321 (0.001456, -4, 0.0014),322 (0.0006666, -5, 0.00066),323 (0.123, -2, 0.12),324 (1, -1, 1.0),325 (22.22, 0, 22.0),326 (7684.65, 2, 76e2),327 (17.8e8, 8, 17e8)])328def test_floor(x, p, r):329 v = Value(x, 10.0**p)330 assert abs(floor(v) - r) < ϵ331@pytest.mark.parametrize('x, p, r', [332 (0.145e-6, -8, 0.15e-6),333 (0.001456, -4, 0.0015),334 (0.0006666, -5, 0.00067),335 (0.123, -2, 0.13),336 (1, -1, 1.0),337 (22.22, 0, 23.0),338 (7684.65, 2, 77e2),339 (17.8e8, 8, 18e8)])340def test_ceil(x, p, r):341 v = Value(x, 10.0**p)342 assert abs(ceil(v) - r) < ϵ343def test_convert_to_number():344 assert complex(a) == a.x + 0j345 assert float(a) == a.x346 assert int(a) == 3347 assert bool(a)348 assert not bool(Value(0, 0.0028))349def test_copy():350 v = a.copy()351 assert v.x == a.x352 assert v.ux == a.ux353@pytest.mark.parametrize('ux, acc', [354 (0.145e-6, -7),355 (0.001456, -3),356 (0.0006666, -4),357 (0.123, -1),358 (1, 0),359 (22.22, 1),360 (7684.65, 3),361 (17.8e8, 9)])362def test_precision(ux, acc):363 v = Value(1, ux)364 assert v.precision() == acc365@pytest.mark.parametrize('x', [366 a, abs(A), B367], ids=['Value', 'Array of values', 'Valued array'])368def test_log(x):369 z = np.log(x)370 assert np.all(val(z) == np.log(val(x)))371 assert np.all(unc(z) == unc(x) / val(x))372@pytest.mark.parametrize('x', [373 a, abs(A), B374], ids=['Value', 'Array of values', 'Valued array'])375def test_log2(x):376 z = np.log2(x)377 assert np.all(val(z) == np.log2(val(x)))378 assert np.all(unc(z) == unc(x) / (val(x) * np.log(2)))379@pytest.mark.parametrize('x', [380 a, abs(A), B381], ids=['Value', 'Array of values', 'Valued array'])382def test_log10(x):383 z = np.log10(x)384 assert np.all(val(z) == np.log10(val(x)))385 assert np.all(unc(z) == unc(x) / (val(x) * np.log(10)))386@pytest.mark.parametrize('x', [387 a, abs(A), B388], ids=['Value', 'Array of values', 'Valued array'])389def test_log1p(x):390 z = np.log1p(x)391 assert np.all(val(z) == np.log1p(val(x)))392 assert np.all(unc(z) == unc(x) / (val(x) + 1))393@pytest.mark.parametrize('x', [394 a, b, abs(A), B395], ids=['Value', 'Negative', 'Array of values', 'Valued array'])396def test_exp(x):397 z = np.exp(x)398 assert np.all(val(z) == np.exp(val(x)))399 assert np.all(unc(z) == unc(x) * np.exp(val(x)))400@pytest.mark.parametrize('x', [401 a, b, abs(A), B402], ids=['Value', 'Negative', 'Array of values', 'Valued array'])403def test_exp2(x):404 z = np.exp2(x)405 assert np.all(val(z) == np.exp2(val(x)))406 assert np.all(unc(z) == unc(x) * np.exp2(val(x)) * np.log(2))407@pytest.mark.parametrize('x', [408 a, b, abs(A), B409], ids=['Value', 'Nagetive', 'Array of values', 'Valued array'])410def test_expm1(x):411 z = np.expm1(x)412 assert np.all(val(z) == np.expm1(val(x)))413 assert np.all(unc(z) == unc(x) * np.exp(val(x)))414@pytest.mark.parametrize('x', [415 a, b, abs(A), B416], ids=['Value', 'Negative', 'Array of values', 'Valued array'])417def test_sin(x):418 z = np.sin(x)419 assert np.all(val(z) == np.sin(val(x)))420 assert np.all(unc(z) == np.abs(unc(x) * np.cos(val(x))))421@pytest.mark.parametrize('x', [422 a, b, abs(A), B423], ids=['Value', 'Negative', 'Array of values', 'Valued array'])424def test_cos(x):425 z = np.cos(x)426 assert np.all(val(z) == np.cos(val(x)))427 assert np.all(unc(z) == np.abs(unc(x) * np.sin(val(x))))428@pytest.mark.parametrize('x', [429 a, b, abs(A), B430], ids=['Value', 'Negative', 'Array of values', 'Valued array'])431def test_tan(x):432 z = np.tan(x)433 assert np.all(val(z) == np.tan(val(x)))434 assert np.all(unc(z) == np.abs(unc(x) / np.cos(val(x))**2))435@pytest.mark.parametrize('x', [436 a / 10, b / 10, abs(A) / 1000, B / 10437], ids=['Value', 'Negative', 'Array of values', 'Valued array'])438def test_arcsin(x):439 z = np.arcsin(x)440 assert np.all(val(z) == np.arcsin(val(x)))441 assert np.all(unc(z) == np.abs(unc(x) / np.sqrt(1 - val(x)**2)))442@pytest.mark.parametrize('x', [443 a / 10, b / 10, abs(A) / 1000, B / 10444], ids=['Value', 'Negative', 'Array of values', 'Valued array'])445def test_arccos(x):446 z = np.arccos(x)447 assert np.all(val(z) == np.arccos(val(x)))448 assert np.all(unc(z) == np.abs(unc(x) / np.sqrt(1 - val(x)**2)))449@pytest.mark.parametrize('x', [450 a, b, abs(A), B451], ids=['Value', 'Negative', 'Array of values', 'Valued array'])452def test_arctan(x):453 z = np.arctan(x)454 assert np.all(val(z) == np.arctan(val(x)))455 assert np.all(unc(z) == np.abs(unc(x) / (1 + val(x)**2)))456@pytest.mark.parametrize('x', [457 a, b, abs(A), B458], ids=['Value', 'Negative', 'Array of values', 'Valued array'])459def test_sinh(x):460 z = np.sinh(x)461 assert np.all(val(z) == np.sinh(val(x)))462 assert np.all(unc(z) == np.abs(unc(x) * np.cosh(val(x))))463@pytest.mark.parametrize('x', [464 a, b, abs(A), B465], ids=['Value', 'Negative', 'Array of values', 'Valued array'])466def test_cosh(x):467 z = np.cosh(x)468 assert np.all(val(z) == np.cosh(val(x)))469 assert np.all(unc(z) == np.abs(unc(x) * np.sinh(val(x))))470@pytest.mark.parametrize('x', [471 a, b, abs(A), B472], ids=['Value', 'Negative', 'Array of values', 'Valued array'])473def test_tanh(x):474 z = np.tanh(x)475 assert np.all(val(z) == np.tanh(val(x)))476 assert np.all(unc(z) == np.abs(unc(x) / np.cosh(val(x))**2))477@pytest.mark.parametrize('x', [478 a / 10, b / 10, abs(A) / 1000, B / 10479], ids=['Value', 'Negative', 'Array of values', 'Valued array'])480def test_arcsinh(x):481 z = np.arcsinh(x)482 assert np.all(val(z) == np.arcsinh(val(x)))483 assert np.all(unc(z) == np.abs(unc(x) / np.sqrt(1 + val(x)**2)))484@pytest.mark.parametrize('x', [485 a, abs(A), B486], ids=['Value', 'Array of values', 'Valued array'])487def test_arccosh(x):488 z = np.arccosh(x)489 assert np.all(val(z) == np.arccosh(val(x)))490 assert np.all(unc(z) == np.abs(unc(x) / np.sqrt(val(x)**2 - 1)))491@pytest.mark.parametrize('x', [492 a / 10, b / 10, abs(A) / 1000, B / 10493], ids=['Value', 'Negative', 'Array of values', 'Valued array'])494def test_arctanh(x):495 z = np.arctanh(x)496 assert np.all(val(z) == np.arctanh(val(x)))497 assert np.all(unc(z) == np.abs(unc(x) / (1 - val(x)**2)))498@pytest.mark.parametrize('x', [499 a, abs(A), B500], ids=['Value', 'Array of values', 'Valued array'])501def test_sqrt(x):502 z = np.sqrt(x)503 assert np.all(val(z) == np.sqrt(val(x)))504 assert np.all(unc(z) == np.abs(unc(x) / (2 * np.sqrt(val(x)))))505@pytest.mark.parametrize('x', [506 a, b, abs(A), B507], ids=['Value', 'Negative', 'Array of values', 'Valued array'])508def test_cbrt(x):509 z = np.cbrt(x)510 assert np.all(val(z) == np.cbrt(val(x)))511 assert np.all(unc(z) == np.abs(unc(x) / (3 * np.cbrt(val(x))**2)))512@pytest.mark.parametrize('x, y, res', [513 (2, Value(3, 2), 2),514 (2, Value(1, 0.2), 1),515 (Value(2, 1), Value(1, 0.2), 1)],516 ids=['Number', 'Value', "Two values"])517def test_min(x, y, res):518 assert min(x, y) == res519@pytest.mark.parametrize('x, y, res', [520 (2, Value(3, 2), 3),521 (2, Value(1, 0.2), 2),522 (Value(2, 1), Value(1, 0.2), 2)],523 ids=['Number', 'Value', "Two values"])524def test_max(x, y, res):...

Full Screen

Full Screen

test_int32_find_max.py

Source:test_int32_find_max.py Github

copy

Full Screen

...4def test_0_compile_pymod_test_mod(pmgen_py_compile):5 pmgen_py_compile(__name__)6ndims_to_test = [1, 2, 3, 4]7# for loop, values8@pytest.mark.parametrize("ndim", ndims_to_test)9@pytest.mark.parametrize("nim_test_proc_name", [10 "int32FindMaxForLoopValues",11 "int32FindMaxForLoopValues_m",12])13def test_int32FindMaxForLoopValues(pymod_test_mod, seeded_random_number_generator,14 ndim, nim_test_proc_name):15 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, numpy.int32)16 print ("\nrandom number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \17 (seeded_random_number_generator, ndim, arg.shape, arg))18 expectedRes = arg.max()19 res = getattr(pymod_test_mod, nim_test_proc_name)(arg)20 print ("res = %s" % str(res))21 assert res == expectedRes22# while loop, Forward Iter23@pytest.mark.parametrize("ndim", ndims_to_test)24def test_int32FindMaxWhileLoopForwardIter(pymod_test_mod, seeded_random_number_generator, ndim):25 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, numpy.int32)26 print ("\nrandom number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \27 (seeded_random_number_generator, ndim, arg.shape, arg))28 expectedRes = arg.max()29 res = pymod_test_mod.int32FindMaxWhileLoopForwardIter(arg)30 print ("res = %s" % str(res))31 assert res == expectedRes32# for loop, Forward Iter33@pytest.mark.parametrize("ndim", ndims_to_test)34@pytest.mark.parametrize("nim_test_proc_name", [35 "int32FindMaxForLoopForwardIter",36 "int32FindMaxForLoopForwardIter_m",37 "int32FindMaxForLoopForwardIter_i",38])39def test_int32FindMaxForLoopForwardIter(pymod_test_mod, seeded_random_number_generator,40 ndim, nim_test_proc_name):41 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, numpy.int32)42 print ("\nnim_test_proc_name = %s" % nim_test_proc_name)43 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \44 (seeded_random_number_generator, ndim, arg.shape, arg))45 expectedRes = arg.max()46 res = getattr(pymod_test_mod, nim_test_proc_name)(arg)47 print ("res = %s" % str(res))48 assert res == expectedRes49# while loop, Rand Acc Iter50@pytest.mark.parametrize("ndim", ndims_to_test)51@pytest.mark.parametrize("nim_test_proc_name", [52 "int32FindMaxWhileLoopRandaccIterDeref",53 "int32FindMaxWhileLoopRandaccIterIndex0",54 "int32FindMaxWhileLoopRandaccIterDerefPlusZeroOffset",55 "int32FindMaxWhileLoopRandaccIterDerefMinusZeroOffset",56 "int32FindMaxWhileLoopRandaccIterIndexVsPlusOffset_1",57 "int32FindMaxWhileLoopRandaccIterIndexVsPlusOffset_2",58 "int32FindMaxWhileLoopRandaccIterIndexVsPlusOffset_3",59 "int32FindMaxWhileLoopRandaccIterIndexVsPlusOffset_4",60 "int32FindMaxWhileLoopRandaccIterIndexVsPlusOffset_5",61 "int32FindMaxWhileLoopRandaccIterIndexVsMinusOffset_1",62 "int32FindMaxWhileLoopRandaccIterIndexVsMinusOffset_2",63 "int32FindMaxWhileLoopRandaccIterIndexVsMinusOffset_3",64 "int32FindMaxWhileLoopRandaccIterIndexVsMinusOffset_4",65 "int32FindMaxWhileLoopRandaccIterIndexVsMinusOffset_5",66])67def test_int32FindMaxWhileLoopRandaccIterDerefAlternatives(pymod_test_mod, seeded_random_number_generator,68 ndim, nim_test_proc_name):69 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, numpy.int32)70 print ("\nnim_test_proc_name = %s" % nim_test_proc_name)71 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \72 (seeded_random_number_generator, ndim, arg.shape, arg))73 expectedRes = arg.max()74 res = getattr(pymod_test_mod, nim_test_proc_name)(arg)75 print ("res = %s" % str(res))76 assert res == expectedRes77@pytest.mark.parametrize("ndim", ndims_to_test)78@pytest.mark.parametrize("nim_test_proc_name", [79 "int32FindMaxWhileLoopRandaccIterIndexVsPlusOffsetK",80 "int32FindMaxWhileLoopRandaccIterIndexVsMinusOffsetK",81])82@pytest.mark.parametrize("k", [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5])83def test_int32FindMaxWhileLoopRandaccIterDerefKParamAlternatives(pymod_test_mod, seeded_random_number_generator,84 ndim, nim_test_proc_name, k):85 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, numpy.int32)86 print ("\nnim_test_proc_name = %s, k = %d" % (nim_test_proc_name, k))87 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \88 (seeded_random_number_generator, ndim, arg.shape, arg))89 expectedRes = arg.max()90 res = getattr(pymod_test_mod, nim_test_proc_name)(arg, k)91 print ("res = %s" % str(res))92 assert res == expectedRes93@pytest.mark.parametrize("ndim", ndims_to_test)94@pytest.mark.parametrize("nim_test_proc_name", [95 "int32FindMaxWhileLoopRandaccIterDeltaN_1",96 "int32FindMaxWhileLoopRandaccIterDeltaN_2",97])98@pytest.mark.parametrize("n", [1, 2, 3, 4, 5, 10, 100, 1000])99def test_int32FindMaxWhileLoopRandaccIterDeltaN_1(pymod_test_mod, seeded_random_number_generator,100 ndim, nim_test_proc_name, n):101 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, numpy.int32)102 print ("\nnim_test_proc_name = %s, n = %d" % (nim_test_proc_name, n))103 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \104 (seeded_random_number_generator, ndim, arg.shape, arg))105 argDeltaN = arg.flat[::n]106 print ("arg.flat[::n] =\n%s" % argDeltaN)107 expectedRes = argDeltaN.max()108 res = getattr(pymod_test_mod, nim_test_proc_name)(arg, n)109 print ("res = %s" % str(res))110 assert res == expectedRes111@pytest.mark.parametrize("ndim", ndims_to_test)112@pytest.mark.parametrize("nim_test_proc_name", [113 "int32FindMaxWhileLoopRandaccIterExcludeFirstM_1",114 "int32FindMaxWhileLoopRandaccIterExcludeFirstM_2",115])116@pytest.mark.parametrize("m", [1, 2, 3, 4, 5, 10, 100, 1000])117def test_int32FindMaxWhileLoopRandaccIterExcludeFirstM_1(pymod_test_mod, seeded_random_number_generator,118 ndim, nim_test_proc_name, m):119 dtype = numpy.int32120 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, dtype)121 print ("\nnim_test_proc_name = %s, m = %d" % (nim_test_proc_name, m))122 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \123 (seeded_random_number_generator, ndim, arg.shape, arg))124 argAfterM = arg.flat[m:]125 print ("arg.flat[m:] =\n%s" % argAfterM)126 if argAfterM.size > 0:127 expectedRes = argAfterM.max()128 print ("expectedRes = %s" % str(expectedRes))129 else:130 expectedRes = numpy.iinfo(dtype).min131 print ("expectedRes = %s (int32.min)" % str(expectedRes))132 res = getattr(pymod_test_mod, nim_test_proc_name)(arg, m)133 print ("res = %s" % str(res))134 assert res == expectedRes135@pytest.mark.parametrize("ndim", ndims_to_test)136@pytest.mark.parametrize("nim_test_proc_name", [137 "int32FindMaxWhileLoopRandaccIterExcludeLastM_1",138 "int32FindMaxWhileLoopRandaccIterExcludeLastM_2",139])140@pytest.mark.parametrize("m", [1, 2, 3, 4, 5, 10, 100, 1000])141def test_int32FindMaxWhileLoopRandaccIterExcludeLastM_1(pymod_test_mod, seeded_random_number_generator,142 ndim, nim_test_proc_name, m):143 dtype = numpy.int32144 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, dtype)145 print ("\nnim_test_proc_name = %s, m = %d" % (nim_test_proc_name, m))146 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \147 (seeded_random_number_generator, ndim, arg.shape, arg))148 argBeforeLastM = arg.flat[:-m]149 print ("arg.flat[:-m] =\n%s" % argBeforeLastM)150 if argBeforeLastM.size > 0:151 expectedRes = argBeforeLastM.max()152 print ("expectedRes = %s" % str(expectedRes))153 else:154 expectedRes = numpy.iinfo(dtype).min155 print ("expectedRes = %s (int32.min)" % str(expectedRes))156 res = getattr(pymod_test_mod, nim_test_proc_name)(arg, m)157 print ("res = %s" % str(res))158 assert res == expectedRes159# for loop, Rand Acc Iter160@pytest.mark.parametrize("ndim", ndims_to_test)161@pytest.mark.parametrize("nim_test_proc_name", [162 "int32FindMaxForLoopRandaccIterDeref",163 "int32FindMaxForLoopRandaccIterDeref_m",164 "int32FindMaxForLoopRandaccIterDeref_i",165 "int32FindMaxForLoopRandaccIterIndex0_i",166])167def test_int32FindMaxForLoopRandaccIterDerefAlternatives(pymod_test_mod, seeded_random_number_generator,168 ndim, nim_test_proc_name):169 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, numpy.int32)170 print ("\nnim_test_proc_name = %s" % nim_test_proc_name)171 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \172 (seeded_random_number_generator, ndim, arg.shape, arg))173 expectedRes = arg.max()174 res = getattr(pymod_test_mod, nim_test_proc_name)(arg)175 print ("res = %s" % str(res))176 assert res == expectedRes177@pytest.mark.parametrize("ndim", ndims_to_test)178@pytest.mark.parametrize("nim_test_proc_name", [179 "int32FindMaxForLoopRandaccIterDeltaN",180 "int32FindMaxForLoopRandaccIterDeltaN_m",181 "int32FindMaxForLoopRandaccIterDeltaN_i",182])183@pytest.mark.parametrize("n", [1, 2, 3, 4, 5, 10, 100, 1000])184def test_int32FindMaxForLoopRandaccIterDeltaN_1(pymod_test_mod, seeded_random_number_generator,185 ndim, nim_test_proc_name, n):186 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, numpy.int32)187 print ("\nnim_test_proc_name = %s, n = %d" % (nim_test_proc_name, n))188 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \189 (seeded_random_number_generator, ndim, arg.shape, arg))190 argDeltaN = arg.flat[::n]191 print ("arg.flat[::n] =\n%s" % argDeltaN)192 expectedRes = argDeltaN.max()193 res = getattr(pymod_test_mod, nim_test_proc_name)(arg, n)194 print ("res = %s" % str(res))195 assert res == expectedRes196@pytest.mark.parametrize("ndim", ndims_to_test)197@pytest.mark.parametrize("nim_test_proc_name", [198 "int32FindMaxForLoopRandaccIterExcludeFirstM",199 "int32FindMaxForLoopRandaccIterExcludeFirstM_m",200 "int32FindMaxForLoopRandaccIterExcludeFirstM_i",201])202@pytest.mark.parametrize("m", [1, 2, 3, 4, 5, 10, 100, 1000])203def test_int32FindMaxForLoopRandaccIterExcludeFirstM_1(pymod_test_mod, seeded_random_number_generator,204 ndim, nim_test_proc_name, m):205 dtype = numpy.int32206 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, dtype)207 print ("\nnim_test_proc_name = %s, m = %d" % (nim_test_proc_name, m))208 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \209 (seeded_random_number_generator, ndim, arg.shape, arg))210 argAfterM = arg.flat[m:]211 print ("arg.flat[m:] =\n%s" % argAfterM)212 if argAfterM.size > 0:213 expectedRes = argAfterM.max()214 print ("expectedRes = %s" % str(expectedRes))215 else:216 expectedRes = numpy.iinfo(dtype).min217 print ("expectedRes = %s (int32.min)" % str(expectedRes))218 res = getattr(pymod_test_mod, nim_test_proc_name)(arg, m)219 print ("res = %s" % str(res))220 assert res == expectedRes221@pytest.mark.parametrize("ndim", ndims_to_test)222@pytest.mark.parametrize("nim_test_proc_name", [223 "int32FindMaxForLoopRandaccIterExcludeLastM_i",224])225@pytest.mark.parametrize("m", [1, 2, 3, 4, 5, 10, 100, 1000])226def test_int32FindMaxForLoopRandaccIterExcludeLastM_1(pymod_test_mod, seeded_random_number_generator,227 ndim, nim_test_proc_name, m):228 dtype = numpy.int32229 arg = array_utils.get_random_Nd_array_of_ndim_and_type(ndim, dtype)230 print ("\nnim_test_proc_name = %s, m = %d" % (nim_test_proc_name, m))231 print ("random number seed = %d\nndim = %d, shape = %s\narg =\n%s" % \232 (seeded_random_number_generator, ndim, arg.shape, arg))233 argBeforeLastM = arg.flat[:-m]234 print ("arg.flat[:-m] =\n%s" % argBeforeLastM)235 if argBeforeLastM.size > 0:236 expectedRes = argBeforeLastM.max()237 print ("expectedRes = %s" % str(expectedRes))238 else:239 expectedRes = numpy.iinfo(dtype).min...

Full Screen

Full Screen

test_conformer_separator.py

Source:test_conformer_separator.py Github

copy

Full Screen

2import torch3from torch import Tensor4from torch_complex.tensor import ComplexTensor5from espnet2.enh.separator.conformer_separator import ConformerSeparator6@pytest.mark.parametrize("input_dim", [15])7@pytest.mark.parametrize("num_spk", [1, 2])8@pytest.mark.parametrize("adim", [8])9@pytest.mark.parametrize("layers", [1, 3])10@pytest.mark.parametrize("aheads", [2])11@pytest.mark.parametrize("linear_units", [100])12@pytest.mark.parametrize("positionwise_layer_type", ["conv1d"])13@pytest.mark.parametrize("positionwise_conv_kernel_size", [3])14@pytest.mark.parametrize("normalize_before", [True])15@pytest.mark.parametrize("concat_after", [True])16@pytest.mark.parametrize("dropout_rate", [0.1])17@pytest.mark.parametrize("input_layer", ["linear", "conv2d"])18@pytest.mark.parametrize("positional_dropout_rate", [0.1])19@pytest.mark.parametrize("attention_dropout_rate", [0.1])20@pytest.mark.parametrize("nonlinear", ["relu", "sigmoid", "tanh"])21@pytest.mark.parametrize("conformer_pos_enc_layer_type", ["rel_pos"])22@pytest.mark.parametrize("conformer_self_attn_layer_type", ["rel_selfattn"])23@pytest.mark.parametrize("conformer_activation_type", ["relu", "tanh"])24@pytest.mark.parametrize("use_macaron_style_in_conformer", [True])25@pytest.mark.parametrize("use_cnn_in_conformer", [True])26@pytest.mark.parametrize("conformer_enc_kernel_size", [3, 5, 7])27@pytest.mark.parametrize("padding_idx", [-1])28def test_conformer_separator_forward_backward_complex(29 input_dim,30 num_spk,31 adim,32 aheads,33 layers,34 linear_units,35 positionwise_layer_type,36 positionwise_conv_kernel_size,37 normalize_before,38 concat_after,39 dropout_rate,40 input_layer,41 positional_dropout_rate,42 attention_dropout_rate,43 nonlinear,44 conformer_pos_enc_layer_type,45 conformer_self_attn_layer_type,46 conformer_activation_type,47 use_macaron_style_in_conformer,48 use_cnn_in_conformer,49 conformer_enc_kernel_size,50 padding_idx,51):52 model = ConformerSeparator(53 input_dim=input_dim,54 num_spk=num_spk,55 adim=adim,56 aheads=aheads,57 layers=layers,58 linear_units=linear_units,59 dropout_rate=dropout_rate,60 positional_dropout_rate=positional_dropout_rate,61 attention_dropout_rate=attention_dropout_rate,62 input_layer=input_layer,63 normalize_before=normalize_before,64 concat_after=concat_after,65 positionwise_layer_type=positionwise_layer_type,66 positionwise_conv_kernel_size=positionwise_conv_kernel_size,67 use_macaron_style_in_conformer=use_macaron_style_in_conformer,68 nonlinear=nonlinear,69 conformer_pos_enc_layer_type=conformer_pos_enc_layer_type,70 conformer_self_attn_layer_type=conformer_self_attn_layer_type,71 conformer_activation_type=conformer_activation_type,72 use_cnn_in_conformer=use_cnn_in_conformer,73 conformer_enc_kernel_size=conformer_enc_kernel_size,74 padding_idx=padding_idx,75 )76 model.train()77 real = torch.rand(2, 10, input_dim)78 imag = torch.rand(2, 10, input_dim)79 x = ComplexTensor(real, imag)80 x_lens = torch.tensor([10, 8], dtype=torch.long)81 masked, flens, others = model(x, ilens=x_lens)82 assert isinstance(masked[0], ComplexTensor)83 assert len(masked) == num_spk84 masked[0].abs().mean().backward()85@pytest.mark.parametrize("input_dim", [15])86@pytest.mark.parametrize("num_spk", [1, 2])87@pytest.mark.parametrize("adim", [8])88@pytest.mark.parametrize("layers", [1, 3])89@pytest.mark.parametrize("aheads", [2])90@pytest.mark.parametrize("linear_units", [100])91@pytest.mark.parametrize("positionwise_layer_type", ["conv1d"])92@pytest.mark.parametrize("positionwise_conv_kernel_size", [3])93@pytest.mark.parametrize("normalize_before", [True])94@pytest.mark.parametrize("concat_after", [True])95@pytest.mark.parametrize("dropout_rate", [0.1])96@pytest.mark.parametrize("input_layer", ["linear", "conv2d"])97@pytest.mark.parametrize("positional_dropout_rate", [0.1])98@pytest.mark.parametrize("attention_dropout_rate", [0.1])99@pytest.mark.parametrize("nonlinear", ["relu", "sigmoid", "tanh"])100@pytest.mark.parametrize("conformer_pos_enc_layer_type", ["rel_pos"])101@pytest.mark.parametrize("conformer_self_attn_layer_type", ["rel_selfattn"])102@pytest.mark.parametrize("conformer_activation_type", ["relu", "tanh"])103@pytest.mark.parametrize("use_macaron_style_in_conformer", [True])104@pytest.mark.parametrize("use_cnn_in_conformer", [True])105@pytest.mark.parametrize("conformer_enc_kernel_size", [3, 5, 7])106@pytest.mark.parametrize("padding_idx", [-1])107def test_conformer_separator_forward_backward_real(108 input_dim,109 num_spk,110 adim,111 aheads,112 layers,113 linear_units,114 positionwise_layer_type,115 positionwise_conv_kernel_size,116 normalize_before,117 concat_after,118 dropout_rate,119 input_layer,120 positional_dropout_rate,...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pytest-play automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful