zmc
2023-08-08 e792e9a60d958b93aef96050644f369feb25d61b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
U
£ý°dô=ã@sdZdZddlZddlZddlZddlZddlZzddlmZ    Wne
k
r\ddl Z    YnXe  d¡Z e ¡jZeƒZeƒZdd„Zdd„Zd    d
„Zd d „ZGd d„deƒZdd„Zdd„Zdd„Zdd„Zdd„ZGdd„deƒZdd„Z Gdd„dej!edZ!d d!„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.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 individual 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 (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 named_parameters 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.TestCase):
    @parameterized.named_parameters(
       ('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
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, 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.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 argument does not need to
be wrapped into a tuple:
 
  class NegativeNumberExample(parameterized.TestCase):
    @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]+\>cCst dt|ƒ¡S)Nz<\1>)ÚADDR_REÚsubÚrepr©Úobj©rú^d:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\google/protobuf/internal/_parameterized.pyÚ
_CleanRepr§sr    cCsd|j|jfS)Nz%s.%s)Ú
__module__Ú__name__)ÚclsrrrÚ    _StrClass­sr cCst|tjƒot|tƒ S©N)Ú
isinstanceÚcollections_abcÚIterableÚstrrrrrÚ_NonStringIterable±s 
ÿrcCsJt|tjƒr$d dd„| ¡Dƒ¡St|ƒr<d tt|ƒ¡St|fƒSdS)Nz, css"|]\}}d|t|ƒfVqdS)z%s=%sN)r    )Ú.0ÚargnameÚvaluerrrÚ    <genexpr>¸sÿz'_FormatParameterList.<locals>.<genexpr>)    rrÚ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.TestCase. 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¦t ˆ¡‡‡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
ˆ|ˆƒdSr)rrrr©r#)r$rrrÚBoundParamTestàs
 zS_ParameterizedTestIter.__iter__.<locals>.MakeBoundParamTest.<locals>.BoundParamTestTréz(%s)z%s is not a valid naming type.z%s(%s)z
%s) Ú    functoolsÚwrapsÚ
_FIRST_ARGÚ__x_use_name__r rÚ_ARGUMENT_REPRrÚ__x_extra_id__r'Ú__doc__)rr,)r%r$rrÚMakeBoundParamTestßs$ÿ
ÿz;_ParameterizedTestIter.__iter__.<locals>.MakeBoundParamTestc3s|]}ˆ|ƒVqdSrr)rÚc)r5rrrþsz2_ParameterizedTestIter.__iter__.<locals>.<genexpr>)r r"r!r+r)r5r%r$rÚ__iter__Ûsz_ParameterizedTestIter.__iter__N)r r
Ú __qualname__r4r&r*r7rrrrrÀsrcCst|ƒdkot|dtƒ S)z<True iff testcases contains only a single non-tuple element.r-r)ÚlenrÚtuple©r!rrrÚ_IsSingletonListsr<c    Csœt|ddƒrtd|fƒ‚i|_}|j ¡ ¡D]d\}}| tjj    ¡r2t
|t j ƒr2t ||ƒi}t|||t|||ƒƒ| ¡D]\}}t|||ƒq€q2dS)NÚ
_id_suffixzECannot add parameters to %s, which already has parameterized methods.)ÚgetattrÚAssertionErrorr=Ú__dict__ÚcopyrÚ
startswithÚunittestÚ
TestLoaderÚtestMethodPrefixrÚtypesÚ FunctionTypeÚdelattrÚ _UpdateClassDictForParamTestCaserÚsetattr)Z class_objectr!r%Ú    id_suffixÚnamerÚmethodsÚmethrrrÚ _ModifyClasss(ÿÿ
 
ÿ
 
þrOcs6‡‡fdd„}tˆƒr2tˆdƒs*tdƒ‚ˆd‰|S)zÃImplementation of the parameterization decorators.
 
  Args:
    naming_type: The naming type.
    testcases: Testcase parameters.
 
  Returns:
    A function for modifying the decorated object.
  cs>t|tƒr.t|tˆtjƒs"tˆƒnˆˆƒ|St|ˆˆƒSdSr)rÚtyperOrÚSequenceÚlistrr©r%r!rrÚ_Apply#s
üz#_ParameterDecorator.<locals>._Applyrz7Single parameter argument must be a non-string iterable)r<rr?)r%r!rTrrSrÚ_ParameterDecorators
 ÿrUcGs
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.
  )rUr2r;rrrÚ
parameters6s rVcGs
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.
  )rUr0r;rrrÚnamed_parametersEsrWc@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<}| ¡ ¡D]>\}}| tjj¡rt|ƒrt|ƒ}| |¡t    ||||ƒqt
  ||||¡S)Nr=) rArrBrCrDrErÚiterÚpoprIrPÚ__new__)ZmcsÚ
class_nameÚbasesÚdctrKrLrÚiteratorrrrr[cs ÿ
zTestGeneratorMetaclass.__new__N)r r
r8r4r[rrrrrXVs rXcCs|t|ƒD]n\}}t|ƒs&td|fƒ‚t|ddƒr:|j}nd|t|f}||ks^td|fƒ‚|||<t|ddƒ||<qdS)    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 %rr1Fz%s%s%dz/Name of parameterized test case "%s" not uniquer3ÚN)Ú    enumerateÚcallabler?r>r Ú
_SEPARATOR)r^rKrLr_ÚidxÚfuncÚnew_namerrrrIos     ÿ 
ÿrIc@s(eZdZdZdd„Zdd„Zdd„ZdS)    ÚTestCasez9Base class for test cases using the parameters decorator.cCs|j t¡dS)Nr)Ú_testMethodNameÚsplitrcr+rrrÚ _OriginalNameˆszTestCase._OriginalNamecCsd| ¡t|jƒfS)Nz%s (%s))rjr Ú    __class__r+rrrÚ__str__‹szTestCase.__str__cCs$dt|jƒ| ¡|j |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%sr`)r rkrjr=Úgetrhr+rrrÚidŽs    
þz TestCase.idN)r r
r8r4rjrlrnrrrrrg…srg)Ú    metaclasscCs"td|jtfiƒ}|d|tfiƒS)a!Returns 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:
 
    import google3
    import mox
 
    from google3.testing.pybase import parameterized
 
    class ExampleTest(parameterized.CoopTestCase(mox.MoxTestBase)):
      ...
 
  Args:
    other_base_class: (class) A test case base class.
 
  Returns:
    A new class object.
  Z CoopMetaclassÚ CoopTestCase)rPÚ __metaclass__rXrg)Zother_base_classrorrrrpœsÿýþrp)#r4Ú
__author__r.ÚrerFrCÚuuidÚcollections.abcÚabcrÚ ImportErrorÚ collectionsÚcompilerÚuuid1ÚhexrcÚobjectr0r2r    r rrrr<rOrUrVrWrPrXrIrgrprrrrÚ<module>!s8q
 
 
A