3 SÉLjK<ã @sdZdZddlZddlZddlZddlZy ddlZWnek rPddlZYnXddl Z ddl Z ej dƒZ e j ƒjZeƒZeƒZdd„Zdd„Zd d „Zd d „ZGd d„deƒZdd„Zdd„Zdd„Zdd„Zdd„ZGdd„deƒZdd„ZGdd„dej ƒZ!dd „Z"dS)!a(Adds 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.ParameterizedTestCase): @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.ParameterizedTestCase): @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 (which is modified internally) and the arguments for the specific invocation, which are part of the string returned by the shortDescription() method on test cases. The id method of the test, used internally by the unittest framework, is also modified to show the arguments. 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>'. For even more descriptive names, especially in test logs, you can use the NamedParameters decorator. In this case, only tuples are supported, and the first parameters has to be a string (or an object that returns an apt name when converted via str()): class NamedExample(parameterized.ParameterizedTestCase): @parameterized.NamedParameters( ('Normal', 'aa', 'aaa', True), ('EmptyPrefix', '', 'abc', True), ('BothEmpty', '', '', True)) def testStartsWith(self, prefix, string, result): self.assertEqual(result, strings.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 ParameterizedTestCase 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.ParameterizedTestCase): def testAdd(self, arg1, arg2, result): self.assertEqual(arg1 + arg2, result) def testSubtract(self, arg2, 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.ParameterizedTestCase): @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 argument does not need to be wrapped into a tuple: class NegativeNumberExample(parameterized.ParameterizedTestCase): @parameterized.Parameters( -1, -3, -4, -5 ) def testIsNegative(self, arg): self.assertTrue(IsNegative(arg)) z!tmarek@google.com (Torsten Marek)éNz0\<([a-zA-Z0-9_\-\.]+) object at 0x[a-fA-F0-9]+\>cCstjdt|ƒƒS)Nz<\1>)ÚADDR_REÚsubÚrepr)Úobj©rú$/usr/lib/python3.6/_parameterized.pyÚ _CleanRepr¥srcCsd|j|jfS)Nz%s.%s)Ú __module__Ú__name__)ÚclsrrrÚ _StrClass«sr cCst|tjƒot|tjƒ S)N)Ú isinstanceÚ collectionsÚIterableÚsixZ string_types)rrrrÚ_NonStringIterable¯s rcCsJt|tjƒr$djdd„|jƒDƒƒSt|ƒr¶sz'_FormatParameterList..) r rÚMappingÚjoinÚitemsrÚmaprÚ_FormatParameterList)Útestcase_paramsrrrr´s   rc@s(eZdZdZdd„Zdd„Zdd„ZdS) Ú_ParameterizedTestIterz9Callable and iterable class for producing new test cases.cCs||_||_||_dS)a\Returns 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. N)Ú _test_methodÚ testcasesÚ _naming_type)ÚselfÚ test_methodrÚ naming_typerrrÚ__init__Ász_ParameterizedTestIter.__init__cOs tdƒ‚dS)Nz¹You appear to be running a parameterized test case without having inherited from parameterized.ParameterizedTestCase. This is bad because none of your test cases are actually being run.)Ú RuntimeError)rÚargsÚkwargsrrrÚ__call__Ósz_ParameterizedTestIter.__call__cs.|j‰|j‰‡‡fdd„‰‡fdd„|jDƒS)Ncs¦tjˆƒ‡‡fdd„ƒ}ˆtkrJd|_|jtˆdƒ7_ˆdd…‰n(ˆtkrddtˆƒf|_nt dˆfƒ‚d|jtˆƒf|_ ˆj r¢|j d ˆj f7_ |S) Ncs@tˆtjƒrˆ|fˆŽn"tˆƒr2ˆ|fˆžŽn ˆ|ˆƒdS)N)r rrr)r)r rrrÚBoundParamTestÞs  zS_ParameterizedTestIter.__iter__..MakeBoundParamTest..BoundParamTestTréz(%s)z%s is not a valid naming type.z%s(%s)z %s) Ú functoolsÚwrapsÚ _FIRST_ARGÚ__x_use_name__r ÚstrÚ_ARGUMENT_REPRrÚ__x_extra_id__r#Ú__doc__)rr')r!r )rrÚMakeBoundParamTestÝs z;_ParameterizedTestIter.__iter__..MakeBoundParamTestc3s|]}ˆ|ƒVqdS)Nr)rÚc)r1rrrüsz2_ParameterizedTestIter.__iter__..)rrr)rr)r1r!r rÚ__iter__Ùsz_ParameterizedTestIter.__iter__N)r r Ú __qualname__r0r"r&r3rrrrr¾srcCst|ƒdkot|dtƒ S)zt|tƒr.t|tˆtjƒs"tˆƒnˆˆƒ|St|ˆˆƒSdS)N)r ÚtyperJrÚSequenceÚlistr)r)r!rrrÚ_Apply!s z#_ParameterDecorator.._Applyrz7Single parameter argument must be a non-string iterable)r7rr:)r!rrNr)r!rrÚ_ParameterDecorators  rOcGs tt|ƒS)aiA 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). Returns: A test generator to be handled by TestGeneratorMetaclass. )rOr.)rrrrÚ Parameters4s rPcGs tt|ƒS)aŸA decorator for creating parameterized tests. See the module docstring for a usage example. The first element of each parameter tuple should be a string and 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. Returns: A test generator to be handled by TestGeneratorMetaclass. )rOr+)rrrrÚNamedParametersCsrQc@seZdZdZdd„ZdS)ÚTestGeneratorMetaclassaìMetaclass for test cases with test generators. A test generator is an iterable in a testcase that produces callables. These callables must be single-argument methods. These methods are injected into the class namespace and the original iterable is removed. If the name of the iterable conforms to the test pattern, the injected methods will be picked up as tests by the unittest framework. In general, it is supposed to be used in conjunction with the Parameters decorator. cCshi|d<}xJ|jƒD]>\}}|jtjjƒrt|ƒrt|ƒ}|j|ƒt||||ƒqWt j ||||ƒS)Nr8) rr=r>r?r@rÚiterÚpoprDrKÚ__new__)ZmcsÚ class_nameÚbasesÚdctrFrGrÚiteratorrrrrUas  zTestGeneratorMetaclass.__new__N)r r r4r0rUrrrrrRTs rRcCs€xzt|ƒD]n\}}t|ƒs(td|fƒ‚t|ddƒr<|j}nd|t|f}||ks`td|fƒ‚|||<t|ddƒ||<q WdS) aAdds individual test cases to a dictionary. Args: dct: The target dictionary. id_suffix: The dictionary for mapping names to test IDs. name: The original name of the test case. iterator: The iterator generating the individual test cases. z,Test generators must yield callables, got %rr,Fz%s%s%dz/Name of parameterized test case "%s" not uniquer/ÚN)Ú enumerateÚcallabler:r9r Ú _SEPARATOR)rXrFrGrYÚidxÚfuncÚnew_namerrrrDms      rDc@s,eZdZdZeZdd„Zdd„Zdd„ZdS) ÚParameterizedTestCasez9Base class for test cases using the Parameters decorator.cCs|jjtƒdS)Nr)Ú_testMethodNameÚsplitr])rrrrÚ _OriginalName‡sz#ParameterizedTestCase._OriginalNamecCsd|jƒt|jƒfS)Nz%s (%s))rdr Ú __class__)rrrrÚ__str__ŠszParameterizedTestCase.__str__cCs$dt|jƒ|jƒ|jj|jdƒfS)z½Returns 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%s.%s%srZ)r rerdr8Úgetrb)rrrrÚid�s zParameterizedTestCase.idN) r r r4r0rRÚ __metaclass__rdrfrhrrrrraƒs racCs"td|jtfiƒ}|d|tfiƒS)a;Returns a new base class with a cooperative metaclass base. This enables the ParameterizedTestCase 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: import google3 import mox from google3.testing.pybase import parameterized class ExampleTest(parameterized.CoopParameterizedTestCase(mox.MoxTestBase)): ... Args: other_base_class: (class) A test case base class. Returns: A new class object. Z CoopMetaclassÚCoopParameterizedTestCase)rKrirRra)Zother_base_classÚ metaclassrrrrj›s rj)#r0Ú __author__rr)ÚrerAZ unittest2r>Ú ImportErrorZuuidrÚcompilerZuuid1Úhexr]Úobjectr+r.rr rrrr7rJrOrPrQrKrRrDZTestCaserarjrrrrÚ�s:    A