B s `YZ @sXdZddlmZddlmZddlmZddlZddlZddlZddlZddl m Z ddl m Z ddl Z yddl mZWneefk rdZYnXed ZeZeZd ZGd d d eZGd ddeZddZddZddZGdddeZddZddZddZ ddZ!Gdd d e"Z#d!d"Z$e %e#Gd#d$d$e j&Z&d%d&Z'dS)'aAdds support for parameterized tests to Python's unittest TestCase class. A parameterized test is a method in a test case that is invoked with different argument tuples. A simple example: class AdditionExample(parameterized.TestCase): @parameterized.parameters( (1, 2, 3), (4, 5, 9), (1, 1, 3)) def testAddition(self, op1, op2, result): self.assertEqual(result, op1 + op2) Each invocation is a separate test case and properly isolated just like a normal test method, with its own setUp/tearDown cycle. In the example above, there are three separate testcases, one of which will fail due to an assertion error (1 + 1 != 3). Parameters for invididual test cases can be tuples (with positional parameters) or dictionaries (with named parameters): class AdditionExample(parameterized.TestCase): @parameterized.parameters( {'op1': 1, 'op2': 2, 'result': 3}, {'op1': 4, 'op2': 5, 'result': 9}, ) def testAddition(self, op1, op2, result): self.assertEqual(result, op1 + op2) If a parameterized test fails, the error message will show the original test name and the parameters for that test. The id method of the test, used internally by the unittest framework, is also modified to show the arguments (but note that the name reported by `id()` doesn't match the actual test name, see below). To make sure that test names stay the same across several invocations, object representations like >>> class Foo(object): ... pass >>> repr(Foo()) '<__main__.Foo object at 0x23d8610>' are turned into '<__main__.Foo>'. When selecting a subset of test cases to run on the command-line, the test cases contain an index suffix for each argument in the order they were passed to `parameters()` (eg. testAddition0, testAddition1, etc.) This naming scheme is subject to change; for more reliable and stable names, especially in test logs, use `named_parameters()` instead. Tests using `named_parameters()` are similar to `parameters()`, except only tuples or dicts of args are supported. For tuples, the first parameter arg has to be a string (or an object that returns an apt name when converted via str()). For dicts, a value for the key 'testcase_name' must be present and must be a string (or an object that returns an apt name when converted via str()): class NamedExample(parameterized.TestCase): @parameterized.named_parameters( ('Normal', 'aa', 'aaa', True), ('EmptyPrefix', '', 'abc', True), ('BothEmpty', '', '', True)) def testStartsWith(self, prefix, string, result): self.assertEqual(result, string.startswith(prefix)) class NamedExample(parameterized.TestCase): @parameterized.named_parameters( {'testcase_name': 'Normal', 'result': True, 'string': 'aaa', 'prefix': 'aa'}, {'testcase_name': 'EmptyPrefix', 'result': True, 'string': 'abc', 'prefix': ''}, {'testcase_name': 'BothEmpty', 'result': True, 'string': '', 'prefix': ''}) def testStartsWith(self, prefix, string, result): self.assertEqual(result, string.startswith(prefix)) Named tests also have the benefit that they can be run individually from the command line: $ testmodule.py NamedExample.testStartsWithNormal . -------------------------------------------------------------------- Ran 1 test in 0.000s OK Parameterized Classes ===================== If invocation arguments are shared across test methods in a single TestCase class, instead of decorating all test methods individually, the class itself can be decorated: @parameterized.parameters( (1, 2, 3), (4, 5, 9)) class ArithmeticTest(parameterized.TestCase): def testAdd(self, arg1, arg2, result): self.assertEqual(arg1 + arg2, result) def testSubtract(self, arg1, arg2, result): self.assertEqual(result - arg1, arg2) Inputs from Iterables ===================== If parameters should be shared across several test cases, or are dynamically created from other sources, a single non-tuple iterable can be passed into the decorator. This iterable will be used to obtain the test cases: class AdditionExample(parameterized.TestCase): @parameterized.parameters( c.op1, c.op2, c.result for c in testcases ) def testAddition(self, op1, op2, result): self.assertEqual(result, op1 + op2) Single-Argument Test Methods ============================ If a test method takes only one argument, the single arguments must not be wrapped into a tuple: class NegativeNumberExample(parameterized.TestCase): @parameterized.parameters( -1, -3, -4, -5 ) def testIsNegative(self, arg): self.assertTrue(IsNegative(arg)) List/tuple as a Single Argument =============================== If a test method takes a single argument of a list/tuple, it must be wrapped inside a tuple: class ZeroSumExample(parameterized.TestCase): @parameterized.parameters( ([-1, 0, 1], ), ([-2, 0, 2], ), ) def testSumIsZero(self, arg): self.assertEqual(0, sum(arg)) Async Support =============================== If a test needs to call async functions, it can inherit from both parameterized.TestCase and another TestCase that supports async calls, such as [asynctest](https://github.com/Martiusweb/asynctest): import asynctest class AsyncExample(parameterized.TestCase, asynctest.TestCase): @parameterized.parameters( ('a', 1), ('b', 2), ) async def testSomeAsyncFunction(self, arg, expected): actual = await someAsyncFunction(arg) self.assertEqual(actual, expected) )absolute_import)division)print_functionN)abc)absltest)_parameterized_asyncz0\<([a-zA-Z0-9_\-\.]+) object at 0x[a-fA-F0-9]+\> testcase_namec@seZdZdZdS) NoTestsErrorz?Raised when parameterized decorators do not generate any tests.N)__name__ __module__ __qualname____doc__rr>/tmp/pip-unpacked-wheel-00lyeop_/absl/testing/parameterized.pyr sr cs eZdZdZfddZZS)DuplicateTestNameErrorzGRaised when a parameterized test has the same test name multiple times.cstt|d|||dS)NzDuplicate parameterized test name in {}: generated test name {!r} (generated from {!r}) already exists. Consider using named_parameters() to give your tests unique names and/or renaming the conflicting test method.)superr__init__format)selftest_class_nameZ new_test_nameZoriginal_test_name) __class__rrrs zDuplicateTestNameError.__init__)r r r r r __classcell__rr)rrrsrcCstdt|S)Nz<\1>)_ADDR_REsubrepr)objrrr _clean_reprsrcCs(t|tjo&t|tj o&t|tj S)N) isinstancerIterablesix text_type binary_type)rrrr_non_string_or_bytes_iterables r"cCsLt|tjr&dddt|DSt|r>dtt|St |fSdS)Nz, css"|]\}}d|t|fVqdS)z%s=%sN)r).0argnamevaluerrr sz)_format_parameter_list..) rrMappingjoinr iteritemsr"mapr_format_parameter_list)testcase_paramsrrrr+s   r+c@s*eZdZdZd ddZddZddZdS) _ParameterizedTestIterz9Callable and iterable class for producing new test cases.NcCs2||_||_||_|dkr |j}||_tj|_dS)aReturns concrete test functions for a test and a list of parameters. The naming_type is used to determine the name of the concrete functions as reported by the unittest framework. If naming_type is _FIRST_ARG, the testcases must be tuples, and the first element must have a string representation that is a valid Python identifier. Args: test_method: The decorated test method. testcases: (list of tuple/dict) A list of parameter tuples/dicts for individual test invocations. naming_type: The test naming type, either _NAMED or _ARGUMENT_REPR. original_name: The original test method name. When decorated on a test method, None is passed to __init__ and test_method.__name__ is used. Note test_method.__name__ might be different than the original defined test method because of the use of other decorators. A more accurate value is set by TestGeneratorMetaclass.__new__ later. N) _test_method testcases _naming_typer _original_namer-)r test_methodr/ naming_type original_namerrrrsz_ParameterizedTestIter.__init__cOs tddS)NaYou appear to be running a parameterized test case without having inherited from parameterized.TestCase. This is bad because none of your test cases are actually being run. You may also be using another decorator before the parameterized one, in which case you should reverse the order.) RuntimeError)rargskwargsrrr__call__ sz_ParameterizedTestIter.__call__cs0jjfddfddjDS)Ncsptfdd}tkrd|_d}ttjrhtkrJtdtt}ddt Dn>t rtdt j stdd}d dntd j }|d r|r|d s|d 7}|t||_nBtkrttjrtd tf}||_ntdfd|jtf|_jrP|jdjf7_trltrlt|S|S)Ncs<ttjr|fStr.|fS|SdS)N)rrr'r")r)r2r,rrbound_param_tests   zX_ParameterizedTestIter.__iter__..make_bound_param_test..bound_param_testTz*Dict for named tests must contain key "%s"cSsi|]\}}|tkr||qSr)_NAMED_DICT_KEY)r#kvrrr ,szR_ParameterizedTestIter.__iter__..make_bound_param_test..rzWThe first element of named test parameters is the test name suffix and must be a stringz9Named tests must be passed a dict or non-string iterable.Ztest__z(%s)z%s is not a valid naming type.z%s(%s)z %s) functoolswraps_NAMED__x_use_name__rrr'r:r5rr)r" string_typesr1 startswithstrr _ARGUMENT_REPRtypes GeneratorTypetupler+__x_params_repr__r riscoroutinefunctionZ async_wrapped)r,r9rZtest_method_name params_repr)r3rr2)r,rmake_bound_param_testsL         z>_ParameterizedTestIter.__iter__..make_bound_param_testc3s|]}|VqdS)Nr)r#c)rNrrr&Ysz2_ParameterizedTestIter.__iter__..)r.r0r/)rr)rNr3rr2r__iter__sCz_ParameterizedTestIter.__iter__)N)r r r r rr8rPrrrrr-s r-c Cst|ddrtd|fi|_}xt|jD]p\}}|tj j r6t |t j r6t||i}t|j|||t||||x"t|D]\}}t|||qWq6WdS)N_test_params_reprsz{Cannot add parameters to %s. Either it already has parameterized methods, or its super class is also a parameterized class.)getattrAssertionErrorrQrr)__dict__copyrEunittest TestLoadertestMethodPrefixrrH FunctionTypedelattr&_update_class_dict_for_param_test_caser r-setattr) Z class_objectr/r3test_params_reprsnamermethods meth_namemethrrr _modify_class\s     rbcsxfdd}tdkrTtdtsTtdtjsTtdsLtddttjshtstt d|S)aImplementation of the parameterization decorators. Args: naming_type: The naming type. testcases: Testcase parameters. Raises: NoTestsError: Raised when the decorator generates no tests. Returns: A function for modifying the decorated object. cs*t|trt||St|SdS)N)rtyperbr-)r)r3r/rr_apply}s  z$_parameter_decorator.._applyr>rzCSingle parameter argument must be a non-string non-Mapping iterablezparameterized test decorators did not generate any tests. Make sure you specify non-empty parameters, and do not reuse generators more than once.) lenrrJrr'r"rSSequencelistr )r3r/rdr)r3r/r_parameter_decoratorps   rhcGs tt|S)aA decorator for creating parameterized tests. See the module docstring for a usage example. Args: *testcases: Parameters for the decorated method, either a single iterable, or a list of tuples/dicts/objects (for tests with only one argument). Raises: NoTestsError: Raised when the decorator generates no tests. Returns: A test generator to be handled by TestGeneratorMetaclass. )rhrG)r/rrr parameterssricGs tt|S)aA decorator for creating parameterized tests. See the module docstring for a usage example. For every parameter tuple passed, the first element of the tuple should be a string and will be appended to the name of the test method. Each parameter dict passed must have a value for the key "testcase_name", the string representation of that value will be appended to the name of the test method. Args: *testcases: Parameters for the decorated method, either a single iterable, or a list of tuples or dicts. Raises: NoTestsError: Raised when the decorator generates no tests. Returns: A test generator to be handled by TestGeneratorMetaclass. )rhrB)r/rrrnamed_parameterssrjc@seZdZdZddZdS)TestGeneratorMetaclasszAMetaclass for adding tests generated by parameterized decorators.c Cs|di}xbt|D]P\}}|tjjrt|rt |t rJ||_ t |}| |t|||||qWxH|D]@}t|dd} | rvt|trvx | D]\} } || | qWqvWt||||S)NrQ) setdefaultrr)rUrErVrWrXr"rr-r1iterpopr[rR issubclassTestCaseitemsrc__new__) Zmcs class_namebasesdctr]r^riteratorbaseZbase_test_params_reprsr2Ztest_method_idrrrrrs      zTestGeneratorMetaclass.__new__N)r r r r rrrrrrrksrkc Csxt|D]\}}t|s(td|ft|ddsPt|ddsPtd||t|ddrh|j}|}n|}d||f}||krt||||||<t|dd||<q WdS) aAdds individual test cases to a dictionary. Args: test_class_name: The name of the class tests are added to. dct: The target dictionary. test_params_reprs: The dictionary for mapping names to test IDs. name: The original name of the test case. iterator: The iterator generating the individual test cases. Raises: DuplicateTestNameError: Raised when a test name occurs multiple times. RuntimeError: If non-parameterized functions are generated. z,Test generators must yield callables, got %rrCNrKz{}.{} generated a test function without using the parameterized decorators. Only tests generated using the decorators are supported.Fz%s%d) enumeratecallablerSrRr5rr r) rrur]r^rvidxfuncr4new_namerrrr[s"        r[cs0eZdZdZddZddZfddZZS)rpz9Base class for test cases using the parameters decorator.cCs|j|jdS)Nrx)rQget_testMethodName)rrrr_get_params_repr!szTestCase._get_params_reprcCs.|}|rd|}d|j|tj|jS)N z {}{} ({}))rrrrVutilZstrclassr)rrMrrr__str__$s zTestCase.__str__cs.tt|}|}|r&d||S|SdS)zReturns the descriptive ID of the test. This is used internally by the unittesting framework to get a name for the test to be used in reports. Returns: The test id. z{} {}N)rrpidrr)rrwrM)rrrr,s  z TestCase.id)r r r r rrrrrr)rrrpsrpcCs"td|jtfi}|d|tfiS)aReturns a new base class with a cooperative metaclass base. This enables the TestCase to be used in combination with other base classes that have custom metaclasses, such as mox.MoxTestBase. Only works with metaclasses that do not override type.__new__. Example: from absl.testing import parameterized class ExampleTest(parameterized.CoopTestCase(OtherTestCase)): ... Args: other_base_class: (class) A test case base class. Returns: A new class object. Z CoopMetaclass CoopTestCase)rc __metaclass__rkrp)Zother_base_class metaclassrrrrBs r)(r __future__rrrr@rerHrVZabsl._collections_abcrZ absl.testingrrr ImportError SyntaxErrorcompilerobjectrBrGr: Exceptionr rrr"r+r-rbrhrirjrcrkr[ add_metaclassrprrrrrsB         p)3' %