a
    Sici                     @   s  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
 edZe Ze ZdZG dd deZG d	d
 d
eZdd Zdd Zdd Zdd ZG dd deZdd Zdd Zdd Zdd Zdd ZG dd  d eZd!d" Z G d#d$ d$e
j!ed%Z!d&d' Z"dS )(al  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 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 :func:`parameters` (eg. testAddition0,
testAddition1, etc.) This naming scheme is subject to change; for more reliable
and stable names, especially in test logs, use :func:`named_parameters` instead.

Tests using :func:`named_parameters` are similar to :func:`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))


Cartesian product of Parameter Values as Parametrized Test Cases
================================================================

If required to test method over a cartesian product of parameters,
`parameterized.product` may be used to facilitate generation of parameters
test combinations::

    class TestModuloExample(parameterized.TestCase):
      @parameterized.product(
          num=[0, 20, 80],
          modulo=[2, 4],
          expected=[0]
      )
      def testModuloResult(self, num, modulo, expected):
        self.assertEqual(expected, num % modulo)

This results in 6 test cases being created - one for each combination of the
parameters. It is also possible to supply sequences of keyword argument dicts
as elements of the cartesian product::

    @parameterized.product(
        (dict(num=5, modulo=3, expected=2),
         dict(num=7, modulo=4, expected=3)),
        dtype=(int, float)
    )
    def testModuloResult(self, num, modulo, expected, dtype):
      self.assertEqual(expected, dtype(num) % modulo)

This results in 4 test cases being created - for each of the two sets of test
data (supplied as kwarg dicts) and for each of the two data types (supplied as
a named parameter). Multiple keyword argument dicts may be supplied if required.

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)
    )abcN)absltestz0\<([a-zA-Z0-9_\-\.]+) object at 0x[a-fA-F0-9]+\>testcase_namec                   @   s   e Zd ZdZdS )NoTestsErrorz?Raised when parameterized decorators do not generate any tests.N)__name__
__module____qualname____doc__ r
   r
   V/var/www/html/django/DPS/env/lib/python3.9/site-packages/absl/testing/parameterized.pyr      s   r   c                       s    e Zd ZdZ fddZ  ZS )DuplicateTestNameErrorzGRaised when a parameterized test has the same test name multiple times.c                    s   t t| d||| d S )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)selftest_class_nameZnew_test_nameZoriginal_test_name	__class__r
   r   r      s
    
zDuplicateTestNameError.__init__)r   r   r   r	   r   __classcell__r
   r
   r   r   r      s   r   c                 C   s   t dt| S )Nz<\1>)_ADDR_REsubreprobjr
   r
   r   _clean_repr   s    r   c                 C   s$   t | tjo"t | t o"t | t S N)
isinstancer   Iterablestrbytesr   r
   r
   r   _non_string_or_bytes_iterable   s    
r    c                 C   sJ   t | tjr$ddd |  D S t| r<dtt| S t| fS d S )Nz, c                 s   s"   | ]\}}d |t |f V  qdS )z%s=%sN)r   ).0argnamevaluer
   r
   r   	<genexpr>  s   z)_format_parameter_list.<locals>.<genexpr>)	r   r   Mappingjoinitemsr    mapr   _format_parameter_listtestcase_paramsr
   r
   r   r)      s    
r)   c                    s   t   fdd}|S )Nc                     s    | i |I d H S r   r
   )argskwargsfuncr
   r   wrapper
  s    z_async_wrapped.<locals>.wrapper)	functoolswraps)r/   r0   r
   r.   r   _async_wrapped	  s    r3   c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
_ParameterizedTestIterz9Callable and iterable class for producing new test cases.Nc                 C   s2   || _ || _|| _|du r |j}|| _tj| _dS )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.
      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_namer4   )r   test_methodr6   naming_typeoriginal_namer
   r
   r   r     s    z_ParameterizedTestIter.__init__c                 O   s   t dd S )Na  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. You may also be using another decorator before the parameterized one, in which case you should reverse the order.)RuntimeError)r   r,   r-   r
   r
   r   __call__.  s    z_ParameterizedTestIter.__call__c                    s0   j jfdd  fddjD S )Nc                    sd  t  fdd}tu rd|_d }t tjrft vrJtdt  t }dd  	 D  n<t
 rt d tstd d } d	d   ntd
j}|dr|r|ds|d7 }|t| |_nBtu rt tjrt  dt f }||_ntdf d|jt f |_jrL| jdjf 7  _tr`t|S |S )Nc                    sB   t tjr | fi S tr4 | gR  S  | S d S r   )r   r   r%   r    r   )r9   r+   r
   r   bound_param_test;  s
    zX_ParameterizedTestIter.__iter__.<locals>.make_bound_param_test.<locals>.bound_param_testTz*Dict for named tests must contain key "%s"c                 S   s   i | ]\}}|t kr||qS r
   )_NAMED_DICT_KEY)r!   kvr
   r
   r   
<dictcomp>P  s   zR_ParameterizedTestIter.__iter__.<locals>.make_bound_param_test.<locals>.<dictcomp>r   zWThe first element of named test parameters is the test name suffix and must be a string   z9Named tests must be passed a dict or non-string iterable.test__z(%s)z%s is not a valid naming type.z%s(%s)z
%s)r1   r2   _NAMED__x_use_name__r   r   r%   r@   r<   r'   r    r   r8   
startswithr   _ARGUMENT_REPRtypesGeneratorTypetupler)   __x_params_repr__r	   inspectiscoroutinefunctionr3   )r+   r?   r   test_method_nameparams_repr)r:   r   r9   r*   r   make_bound_param_test:  s\    


z>_ParameterizedTestIter.__iter__.<locals>.make_bound_param_testc                 3   s   | ]} |V  qd S r   r
   )r!   c)rS   r
   r   r$   }      z2_ParameterizedTestIter.__iter__.<locals>.<genexpr>)r5   r7   r6   r>   r
   )rS   r:   r   r9   r   __iter__6  s    Cz_ParameterizedTestIter.__iter__)N)r   r   r   r	   r   r=   rV   r
   r
   r
   r   r4     s   
r4   c           	      C   s   t | dd rJ d| f i  | _}| j  D ]j\}}|tjjr2t	|t
jr2t| | i }t| j|||t|||| | D ]\}}t| || qq2d S )N_test_params_reprsz{Cannot add parameters to %s. Either it already has parameterized methods, or its super class is also a parameterized class.)getattrrW   __dict__copyr'   rI   unittest
TestLoadertestMethodPrefixr   rK   FunctionTypedelattr&_update_class_dict_for_param_test_caser   r4   setattr)	Zclass_objectr6   r:   test_params_reprsnamer   methods	meth_namemethr
   r
   r   _modify_class  s&    



rg   c                    sx    fdd}t dkrTtd tsTtd tjsTtd sLJ dd ttjshtsttd|S )a  Implementation 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.
  c                    s*   t | trt|   | S t|  S d S r   )r   typerg   r4   r   r:   r6   r
   r   _apply  s    
z$_parameter_decorator.<locals>._applyrD   r   zCSingle 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.)	lenr   rM   r   r%   r    Sequencelistr   )r:   r6   rj   r
   ri   r   _parameter_decorator  s"    rn   c                  G   s
   t t| S )a  A 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.
  )rn   rJ   r6   r
   r
   r   
parameters  s    rp   c                  G   s
   t t| S )a  A 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.
  )rn   rG   ro   r
   r
   r   named_parameters  s    rq   c                     s2  |  D ]*\}}t|ttfsJ d|t|qt }| D ]}t|ttfrbtdd |D spJ d||r>t|d  t fdd|D sJ d| |@ rJ dt |@ | O }q>|t|@ rJ d	t|t|@ d
d |  D }t| t| }dd t	j
| D }tt|S )a  A decorator for running tests over cartesian product of parameters values.

  See the module docstring for a usage example. The test will be run for every
  possible combination of the parameters.

  Args:
    *kwargs_seqs: Each positional parameter is a sequence of keyword arg dicts;
      every test case generated will include exactly one kwargs dict from each
      positional parameter; these will then be merged to form an overall list
      of arguments for the test case.
    **testgrid: A mapping of parameter names and their possible values. Possible
      values should given as either a list or a tuple.

  Raises:
    NoTestsError: Raised when the decorator generates no tests.

  Returns:
     A test generator to be handled by TestGeneratorMetaclass.
  z5Values of {} must be given as list or tuple, found {}c                 s   s   | ]}t |tV  qd S r   )r   dictr!   r-   r
   r
   r   r$     rU   zproduct.<locals>.<genexpr>zFPositional parameters must be a sequence of keyword argdicts, found {}r   c                 3   s   | ]}t | kV  qd S r   )setrs   	arg_namesr
   r   r$   	  rU   zVKeyword argument dicts within a single parameter must all have the same keys, found {}z\Keyword argument dict sequences must all have distinct argument names, found duplicate(s) {}zArguments supplied in kwargs dicts in positional parameters must not overlap with arguments supplied as named parameters; found duplicate argument(s) {}c                 3   s(   | ] \ }t  fd d|D V  qdS )c                 3   s   | ]} |iV  qd S r   r
   )r!   rB   rA   r
   r   r$     rU   z$product.<locals>.<genexpr>.<genexpr>N)rM   )r!   vsr
   rw   r   r$     rU   c                 S   s&   g | ]}t tjd d |D qS )c                 s   s   | ]}|  V  qd S r   )r'   )r!   caser
   r
   r   r$      s   z%product.<locals>.<listcomp>.<genexpr>)rr   	itertoolschainfrom_iterable)r!   casesr
   r
   r   
<listcomp>  s   zproduct.<locals>.<listcomp>)r'   r   rm   rM   r   rh   rt   allsortedrz   productrn   rJ   )Zkwargs_seqsZtestgridrc   valuesZprior_arg_namesZ
kwargs_seqr6   r
   ru   r   r     sN    


r   c                   @   s   e Zd ZdZdd ZdS )TestGeneratorMetaclasszAMetaclass for adding tests generated by parameterized decorators.c                 C   s   | di }|  D ]P\}}|tjjrt|rt|t	rF||_
t|}|| t||||| q|D ]<}t|dd }	|	rnt|trn|	 D ]\}
}| |
| qqnt| |||S )NrW   )
setdefaultrZ   r'   rI   r[   r\   r]   r    r   r4   r8   iterpopr`   rX   
issubclassTestCaserh   __new__)cls
class_namebasesdctrb   rc   r   iteratorbaseZbase_test_params_reprsr9   Ztest_method_idr
   r
   r   r   *  s$    


zTestGeneratorMetaclass.__new__N)r   r   r   r	   r   r
   r
   r
   r   r   '  s   r   c           	      C   s   t |D ]\}}t|s&J d|f t|ddsNt|ddsNtd| |t|ddrf|j}|}n|}d||f }||v rt| |||||< t|dd||< qdS )	a  Adds 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 %rrH   NrN   z{}.{} generated a test function without using the parameterized decorators. Only tests generated using the decorators are supported.Fz%s%d )	enumeratecallablerX   r<   r   r   r   )	r   r   rb   rc   r   idxr/   r;   new_namer
   r
   r   r`   Z  s*    
r`   c                       s0   e Zd ZdZdd Zdd Z fddZ  ZS )r   z9Base class for test cases using the parameters decorator.c                 C   s   | j | jdS )Nr   )rW   get_testMethodNamer>   r
   r
   r   _get_params_repr  s    zTestCase._get_params_reprc                 C   s.   |   }|rd| }d| j|tj| jS )N z	{}{} ({}))r   r   r   r[   utilstrclassr   )r   rR   r
   r
   r   __str__  s    zTestCase.__str__c                    s.   t t|  }|  }|r&d||S |S dS )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)r   r   idr   r   )r   r   rR   r   r
   r   r     s
    	zTestCase.id)r   r   r   r	   r   r   r   r   r
   r
   r   r   r     s   r   )	metaclassc                 C   s"   t d| jtfi }|d| tfi 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::

      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)rh   __metaclass__r   r   )Zother_base_classr   r
   r
   r   r     s    r   )#r	   collectionsr   r1   rO   rz   rerK   r[   absl.testingr   compiler   objectrG   rJ   r@   	Exceptionr   r   r   r    r)   r3   r4   rg   rn   rp   rq   r   rh   r   r`   r   r   r
   r
   r
   r   <module>   s:    G

p)A3'%