a
    Sicv                    @   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	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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ZddlmZ ddlmZ zddlZW n ey   dZY n0 ddlmZ ddlmZ ddlm Z  dd	l!m"Z" dd
l!m#Z# z\ddl$Z$ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 W n ey   Y n$0 e$j7re$8dZ9ddl:Zej;j<Z=ej>Z>ej?Z?ej@Z@ejAZAejBZBejCZCeDeEfZFdZGdd ZHG dd dejIZJdd ZKdd ZLdd ZMdd ZNejOdeL dddZPejOdeM dddZQejRdeK d dd ejOd!d"d#dd eOd$d"d% d&d' ZSeS  eTfd(d)ZUG d*d+ d+eVZWG d,d- d-eVZXG d.d/ d/eVZYG d0d1 d1ejZZZd2d3 Z[d4d5 Z\d6d7 Z]d8d9 Z^d:d; Z_d<d= Z`d>d? Zaddd@dAZbdBdC ZcdDdE ZddFdG ZedHdI ZfdJdK ZgdLdM ZhdNdO ZidPdQ ZjG dRdS dSejkZkdTdU ZldVdW ZmdXdY ZndedZd[Zod\d] Zpd^d_ Zqd`da Zrdbdc ZsdS )fzBase functionality for Abseil Python tests.

This module contains base classes and high-level functions for Abseil-style
tests.
    )abcN)mock)parse)app)flags)logging)_pretty_print_reporter)xml_reporter)AnyAnyStrBinaryIOCallableContextManagerIOIteratorListMappingMutableMappingMutableSequenceOptionalSequenceTextTextIOTupleTypeUnion_TTc                 C   s   ~| rt jS dd S dS )aP  Expects the test to fail if the run condition is True.

  Example usage::

      @expectedFailureIf(sys.version.major == 2, "Not yet working in py2")
      def test_foo(self):
        ...

  Args:
    condition: bool, whether to expect failure or not.
    reason: Text, the reason to expect failure.
  Returns:
    Decorator function
  c                 S   s   | S N fr   r   Q/var/www/html/django/DPS/env/lib/python3.9/site-packages/absl/testing/absltest.py<lambda>z       z#expectedFailureIf.<locals>.<lambda>N)unittestexpectedFailure)	conditionreasonr   r   r!   expectedFailureIfg   s    r(   c                   @   s   e Zd ZdZdZdZdS )TempFileCleanupalwayssuccessneverN)__name__
__module____qualname__ALWAYSSUCCESSOFFr   r   r   r!   r)   }   s   r)   c                  C   s6   d} t jdd}zt|} W n ty0   Y n0 | S )Ni-  ZTEST_RANDOM_SEED )osenvirongetint
ValueError)random_seedvaluer   r   r!   _get_default_test_random_seed   s    r;   c                   C   s   t jddS )z Returns default test source dir.TEST_SRCDIRr3   r4   r5   r6   r   r   r   r!   get_default_test_srcdir   s    r>   c                  C   s(   t jdd} | s$t jt d} | S )zReturns default test temp dir.TEST_TMPDIRr3   Zabsl_testing)r4   r5   r6   pathjointempfile
gettempdir)tmpdirr   r   r!   get_default_test_tmpdir   s    rE   c                  C   s   t d jrt j} ndtjv r(tjd } nd} | s4dS | dkrLt ddS | dkrXdS zt| }|dkrp|W S W n t	y   Y n0 t	d	
| d
S )a  Returns default seed to use for randomizing test order.

  This function first checks the --test_randomize_ordering_seed flag, and then
  the TEST_RANDOMIZE_ORDERING_SEED environment variable. If the first value
  we find is:
    * (not set): disable test randomization
    * 0: disable test randomization
    * 'random': choose a random seed in [1, 4294967295] for test order
      randomization
    * positive integer: use this seed for test order randomization

  (The values used are patterned after
  https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED).

  In principle, it would be simpler to return None if no override is provided;
  however, the python random module has no `get_seed()`, only `getstate()`,
  which returns far more data than we want to pass via an environment variable
  or flag.

  Returns:
    A default value for test case randomization (int). 0 means do not randomize.

  Raises:
    ValueError: Raised when the flag or env value is not one of the options
        above.
  test_randomize_ordering_seedZTEST_RANDOMIZE_ORDERING_SEEDr3   r   random   l    0z)Unknown test randomization seed value: {}N)FLAGSpresentrF   r4   r5   rG   Randomrandintr7   r8   format)Z	randomizeseedr   r   r!   $_get_default_randomize_ordering_seed   s(    


rP   Ztest_srcdirz.Root of directory tree where source files live)allow_override_cppZtest_tmpdirz%Directory for temporary testing filesZtest_random_seedzRandom seed for testing. Some test frameworks may change the default value of this flag between runs, so it is not appropriate for seeding probabilistic tests.rF   r3   a  If positive, use this as a seed to randomize the execution order for test cases. If "random", pick a random seed to use. If 0 or not set, do not randomize test case execution order. This flag also overrides the TEST_RANDOMIZE_ORDERING_SEED environment variable.xml_output_filezFile to store XML test resultsc                  C   sL   dd } t  }|t dd  | rH| t j_| rHtjd dS )z3Workaround for <http://bugs.python.org/issue20165>.c                 S   s4   t | jt | j  ko.t | j  ko.dkS   S )zTells whether or not this result was a success.

    Any unexpected pass is to be counted as a non-success.

    Args:
      self: The TestResult instance.

    Returns:
      Whether or not this result was a success.
    r   )lenfailureserrorsunexpectedSuccessesselfr   r   r!   wasSuccessful   s
    zF_monkey_patch_test_result_for_unexpected_passes.<locals>.wasSuccessfulc                   S   s   d S r   r   r   r   r   r!   r"     r#   zA_monkey_patch_test_result_for_unexpected_passes.<locals>.<lambda>z^unittest.result.TestResult monkey patch to report unexpected passes as failures did not work.
N)r$   
TestResultaddUnexpectedSuccessFunctionTestCaserY   sysstderrwrite)rY   test_resultr   r   r!   /_monkey_patch_test_result_for_unexpected_passes   s    ra   c                 C   s   || |ddS )zOpens a file.

  Like open(), but ensure that we can open real files even if tests stub out
  open().

  Args:
    filepath: A filepath.
    mode: A mode.
    _open_func: A built-in open() function.

  Returns:
    The opened file object.
  utf-8)encodingr   )filepathmodeZ
_open_funcr   r   r!   _open  s    rf   c                   @   s@   e Zd ZdZdd Zedd Zdd ZdddZdddZ	dS )_TempDira  Represents a temporary directory for tests.

  Creation of this class is internal. Using its public methods is OK.

  This class implements the `os.PathLike` interface (specifically,
  `os.PathLike[str]`). This means, in Python 3, it can be directly passed
  to e.g. `os.path.join()`.
  c                 C   s
   || _ dS )z2Module-private: do not instantiate outside module.N_pathrX   r@   r   r   r!   __init__7  s    z_TempDir.__init__c                 C   s   | j S )zReturns the path, as a string, for the directory.

    TIP: Instead of e.g. `os.path.join(temp_dir.full_path)`, you can simply
    do `os.path.join(temp_dir)` because `__fspath__()` is implemented.
    rh   rW   r   r   r!   	full_path<  s    z_TempDir.full_pathc                 C   s   | j S zSee os.PathLike.rl   rW   r   r   r!   
__fspath__F  s    z_TempDir.__fspath__Nwutf8strictc                 C   s   t | j|||||\}}|S )a  Create a file in the directory.

    NOTE: If the file already exists, it will be made writable and overwritten.

    Args:
      file_path: Optional file path for the temp file. If not given, a unique
        file name will be generated and used. Slashes are allowed in the name;
        any missing intermediate directories will be created. NOTE: This path
        is the path that will be cleaned up, including any directories in the
        path, e.g., 'foo/bar/baz.txt' will `rm -r foo`
      content: Optional string or bytes to initially write to the file. If not
        specified, then an empty file is created.
      mode: Mode string to use when writing content. Only used if `content` is
        non-empty.
      encoding: Encoding to use when writing string content. Only used if
        `content` is text.
      errors: How to handle text to bytes encoding errors. Only used if
        `content` is text.

    Returns:
      A _TempFile representing the created file.
    )	_TempFile_createri   )rX   	file_pathcontentre   rc   rU   tf_r   r   r!   create_fileK  s    z_TempDir.create_filec                 C   s:   |rt j| j|}ntj| jd}t j|dd t|S )zCreate a directory in the directory.

    Args:
      dir_path: Optional path to the directory to create. If not given,
        a unique name will be generated and used.

    Returns:
      A _TempDir representing the created directory.
    dirTexist_ok)r4   r@   rA   ri   rB   mkdtempmakedirsrg   )rX   Zdir_pathr@   r   r   r!   mkdirh  s
    z_TempDir.mkdir)NNrp   rq   rr   )N)
r-   r.   r/   __doc__rk   propertyrl   ro   ry   r   r   r   r   r!   rg   -  s   	
	  
rg   c                   @   s   e Zd ZdZdd Zedd Zedd Zdd	 Z	d ddZ
dd Zd!ddZd"ddZd#ddZd$ddZejd%eeeee dddZdS )&rs   a  Represents a tempfile for tests.

  Creation of this class is internal. Using its public methods is OK.

  This class implements the `os.PathLike` interface (specifically,
  `os.PathLike[str]`). This means, in Python 3, it can be directly passed
  to e.g. `os.path.join()`.
  c                 C   s
   || _ dS )zPrivate: use _create instead.Nrh   rj   r   r   r!   rk     s    z_TempFile.__init__c                 C   s   |rtt j|t|}t j||}t jt j|dd t j|rt |t jst 	|}	t 
||	jt	jB  n0t j|dd tjt|d\}
}t |
 |}| |}|rt|tr|j||||d q||| n
|d ||fS )z+Module-private: create a tempfile instance.Tr|   rz   re   rc   rU   r#   )r4   r@   rA   _get_first_partr   dirnameexistsaccessW_OKstatchmodst_modeS_IWUSRrB   mkstempstrclose
isinstance
write_textwrite_bytes)cls	base_pathru   rv   re   rc   rU   cleanup_pathr@   	stat_infofdrw   r   r   r!   rt     s$    



z_TempFile._createc                 C   s   | j S )zReturns the path, as a string, for the file.

    TIP: Instead of e.g. `os.path.join(temp_file.full_path)`, you can simply
    do `os.path.join(temp_file)` because `__fspath__()` is implemented.
    rh   rW   r   r   r!   rl     s    z_TempFile.full_pathc                 C   s   | j S rm   rn   rW   r   r   r!   ro     s    z_TempFile.__fspath__rq   rr   c                 C   s:   | j ||d}| W  d   S 1 s,0    Y  dS )z(Return the contents of the file as text.rc   rU   N)	open_textread)rX   rc   rU   fpr   r   r!   	read_text  s    z_TempFile.read_textc                 C   s4   |   }| W  d   S 1 s&0    Y  dS )z(Return the content of the file as bytes.N)
open_bytesr   )rX   r   r   r   r!   
read_bytes  s    
z_TempFile.read_bytesrp   c                 C   s>   | j |||d}|| W d   n1 s00    Y  dS )a  Write text to the file.

    Args:
      text: Text to write. In Python 2, it can be bytes, which will be
        decoded using the `encoding` arg (this is as an aid for code that
        is 2 and 3 compatible).
      mode: The mode to open the file for writing.
      encoding: The encoding to use when writing the text to the file.
      errors: The error handling strategy to use when converting text to bytes.
    r   N)r   r_   )rX   textre   rc   rU   r   r   r   r!   r     s    z_TempFile.write_textwbc                 C   s8   |  |}|| W d   n1 s*0    Y  dS )zWrite bytes to the file.

    Args:
      data: bytes to write.
      mode: Mode to open the file for writing. The "b" flag is implicit if
        not already present. It must not have the "t" flag.
    N)r   r_   )rX   datare   r   r   r   r!   r     s    	z_TempFile.write_bytesrtc                 C   s8   d|v rt d|d|vr&|d7 }| |||}|S )a  Return a context manager for opening the file in text mode.

    Args:
      mode: The mode to open the file in. The "t" flag is implicit if not
        already present. It must not have the "b" flag.
      encoding: The encoding to use when opening the file.
      errors: How to handle decoding errors.

    Returns:
      Context manager that yields an open file.

    Raises:
      ValueError: if invalid inputs are provided.
    bzFInvalid mode {!r}: "b" flag not allowed when opening file in text modetr8   rN   rf   )rX   re   rc   rU   cmr   r   r!   r     s    z_TempFile.open_textrbc                 C   s:   d|v rt d|d|vr&|d7 }| j|ddd}|S )aL  Return a context manager for opening the file in binary mode.

    Args:
      mode: The mode to open the file in. The "b" mode is implicit if not
        already present. It must not have the "t" flag.

    Returns:
      Context manager that yields an open file.

    Raises:
      ValueError: if invalid inputs are provided.
    r   zHInvalid mode {!r}: "t" flag not allowed when opening file in binary moder   Nr   r   )rX   re   r   r   r   r!   r     s    z_TempFile.open_bytes)re   rc   rU   returnc                 c   s>   t j| j|||d}|V  W d    n1 s00    Y  d S )Nr   )ioopenrl   )rX   re   rc   rU   r   r   r   r!   rf     s
    
z_TempFile._openN)rq   rr   )rp   rq   rr   )r   )r   rq   rr   )r   )rq   rr   )r-   r.   r/   r   rk   classmethodrt   r   rl   ro   r   r   r   r   r   r   
contextlibcontextmanagerr   r   r
   rf   r   r   r   r!   rs   ~  s&   	
 
	




 rs   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )_methodao  A decorator that supports both instance and classmethod invocations.

  Using similar semantics to the @property builtin, this decorator can augment
  an instance method to support conditional logic when invoked on a class
  object. This breaks support for invoking an instance method via the class
  (e.g. Cls.method(self, ...)) but is still situationally useful.
  c                 C   s   || _ d | _d S r   )_finstancemethod_fclassmethod)rX   Zfinstancemethodr   r   r!   rk   (  s    z_method.__init__c                 C   s   t || _| S r   )r   r   )rX   Zfclassmethodr   r   r!   r   -  s    
z_method.classmethodc                 C   s,   t | jdr| jjS t | jdr(| jjS dS )Nr   r3   )getattrr   r   r   rW   r   r   r!   r   2  s
    z_method.__doc__c                 C   s    |d u r| j n| j}|||S r   )r   r   __get__)rX   objtype_funcr   r   r!   r   :  s    z_method.__get__N)r-   r.   r/   r   rk   r   r   r   r   r   r!   r     s
   r   c                       s  e Zd ZdZejZdZdZdZ	dZ
 fddZ fddZe fd	d
ZdmddZdnddZedd Zejdd Zedd Zdd Zdd Zdd Zedef eedddd Zeed!d"d#Z fd$d%Zdod&d'Zdpd(d)Zdqd*d+Z drd,d-Z!dsd.d/Z"dtd0d1Z#dud2d3Z$dvd4d5Z%dwd6d7Z&dxd8d9Z'dyd:d;Z(dz fd<d=	Z)d{d>d?Z*d|d@dAZ+d}dBdCZ,d~dDdEZ-ddGdHZ.ddIdJZ/G dKdL dLe0Z1e2j3e1dMdNdOZ4e2j3edef ddPdQdOZ4ddRdOZ4e2j3e1dMdSdTZ5e2j3edef ddPdUdTZ5ddVdTZ5ddWdXZ6ddYdZZ7dd[d\Z8d]d^ Z9dd_d`Z:ddadbZ;ddedfZ<ddgdhZ= fdidjZ>d fdkdl	Z?  Z@S )TestCasez4Extension of unittest.TestCase providing more power.i@  TNc                    s&   t t| j|i | t| d| _d S )N_outcome)superr   rk   r   r   )rX   argskwargs	__class__r   r!   rk   T  s    zTestCase.__init__c                    s4   t t|   ttdr0t | _| | jj d S )N	ExitStack)	r   r   setUphasattrr   r   _exit_stack
addCleanupr   rW   r   r   r!   r   Y  s    

zTestCase.setUpc                    s>   t t|   ttdr:t| dr:t | _| | jj d S )Nr   addClassCleanup)	r   r   
setUpClassr   r   r   _cls_exit_stackr   r   r   r   r   r!   r   `  s    
zTestCase.setUpClassc                 C   sv   |   }|r.tj||}tj|t|}ntj|dd tj|d}|}t| tj|dd | 	|| t
|S )a  Create a temporary directory specific to the test.

    NOTE: The directory and its contents will be recursively cleared before
    creation. This ensures that there is no pre-existing state.

    This creates a named directory on disk that is isolated to this test, and
    will be properly cleaned up by the test. This avoids several pitfalls of
    creating temporary directories for test purposes, as well as makes it easier
    to setup directories and verify their contents. For example::

        def test_foo(self):
          out_dir = self.create_tempdir()
          out_log = out_dir.create_file('output.log')
          expected_outputs = [
              os.path.join(out_dir, 'data-0.txt'),
              os.path.join(out_dir, 'data-1.txt'),
          ]
          code_under_test(out_dir)
          self.assertTrue(os.path.exists(expected_paths[0]))
          self.assertTrue(os.path.exists(expected_paths[1]))
          self.assertEqual('foo', out_log.read_text())

    See also: :meth:`create_tempdir` for creating temporary files.

    Args:
      name: Optional name of the directory. If not given, a unique
        name will be generated and used.
      cleanup: Optional cleanup policy on when/if to remove the directory (and
        all its contents) at the end of the test. If None, then uses
        :attr:`tempfile_cleanup`.

    Returns:
      A _TempDir representing the created directory; see _TempDir class docs
      for usage.
    Tr|   rz   )_get_tempdir_path_testr4   r@   rA   r   r   rB   r~   _rmtree_ignore_errors_maybe_add_temp_path_cleanuprg   )rX   namecleanup	test_pathr@   r   r   r   r!   create_tempdiri  s    %zTestCase.create_tempdirrp   rq   rr   c           
      C   s2   |   }tj||||||d\}}	| |	| |S )a  Create a temporary file specific to the test.

    This creates a named file on disk that is isolated to this test, and will
    be properly cleaned up by the test. This avoids several pitfalls of
    creating temporary files for test purposes, as well as makes it easier
    to setup files, their data, read them back, and inspect them when
    a test fails. For example::

        def test_foo(self):
          output = self.create_tempfile()
          code_under_test(output)
          self.assertGreater(os.path.getsize(output), 0)
          self.assertEqual('foo', output.read_text())

    NOTE: This will zero-out the file. This ensures there is no pre-existing
    state.
    NOTE: If the file already exists, it will be made writable and overwritten.

    See also: :meth:`create_tempdir` for creating temporary directories, and
    ``_TempDir.create_file`` for creating files within a temporary directory.

    Args:
      file_path: Optional file path for the temp file. If not given, a unique
        file name will be generated and used. Slashes are allowed in the name;
        any missing intermediate directories will be created. NOTE: This path is
        the path that will be cleaned up, including any directories in the path,
        e.g., ``'foo/bar/baz.txt'`` will ``rm -r foo``.
      content: Optional string or
        bytes to initially write to the file. If not
        specified, then an empty file is created.
      mode: Mode string to use when writing content. Only used if `content` is
        non-empty.
      encoding: Encoding to use when writing string content. Only used if
        `content` is text.
      errors: How to handle text to bytes encoding errors. Only used if
        `content` is text.
      cleanup: Optional cleanup policy on when/if to remove the directory (and
        all its contents) at the end of the test. If None, then uses
        :attr:`tempfile_cleanup`.

    Returns:
      A _TempFile representing the created file; see _TempFile class docs for
      usage.
    )rv   re   rc   rU   )r   rs   rt   r   )
rX   ru   rv   re   rc   rU   r   r   rw   r   r   r   r!   create_tempfile  s    0

zTestCase.create_tempfilec                 C   s   | j std| j |S )a  Returns the CM's value after registering it with the exit stack.

    Entering a context pushes it onto a stack of contexts. When `enter_context`
    is called on the test instance (e.g. `self.enter_context`), the context is
    exited after the test case's tearDown call. When called on the test class
    (e.g. `TestCase.enter_context`), the context is exited after the test
    class's tearDownClass call.

    Contexts are exited in the reverse order of entering. They will always
    be exited, regardless of test failure/success.

    This is useful to eliminate per-test boilerplate when context managers
    are used. For example, instead of decorating every test with `@mock.patch`,
    simply do `self.foo = self.enter_context(mock.patch(...))' in `setUp()`.

    NOTE: The context managers will always be exited without any error
    information. This is an unfortunate implementation detail due to some
    internals of how unittest runs tests.

    Args:
      manager: The context manager to enter.
    zgself._exit_stack is not set: enter_context is Py3-only; also make sure that AbslTest.setUp() is called.)r   AssertionErrorenter_context)rX   managerr   r   r!   r     s
    zTestCase.enter_contextc                 C   s   | j std| j |S )Nz|cls._cls_exit_stack is not set: cls.enter_context requires Python 3.8+; also make sure that AbslTest.setUpClass() is called.)r   r   r   )r   r   r   r   r!   r     s
    c                 C   s   t jtj| jddS )N	__main__.r3   )r4   r@   rA   r?   r:   r/   replacer   r   r   r!   _get_tempdir_path_cls  s    
zTestCase._get_tempdir_path_clsc                 C   s   t j|  | jS r   )r4   r@   rA   r   _testMethodNamerW   r   r   r!   r     s    zTestCase._get_tempdir_path_testc                 C   s   |d ur|S | j S r   )tempfile_cleanup)rX   overrider   r   r!   _get_tempfile_cleanup	  s    zTestCase._get_tempfile_cleanupc                 C   sZ   |  |}|tjkrd S |tjkr0| t| n&|tjkrH| t| ntd	|d S )NzUnexpected cleanup value: {})
r   r)   r2   r0   r   r   r1    _internal_add_cleanup_on_successr   rN   )rX   r@   r   r   r   r!   r     s    



z%TestCase._maybe_add_temp_path_cleanup.)functionr   r   r   c                    sV   j }t|jjt|jj t|jj  fdd}j|g|R i | dS )z7Adds `function` as cleanup when the test case succeeds.c                     s     sd S  | i | d S r   )3_internal_ran_and_passed_when_called_during_cleanupr   r   r   previous_failure_countrX   r   r!   _call_cleaner_on_success(  s
    zKTestCase._internal_add_cleanup_on_success.<locals>._call_cleaner_on_successN)r   rS   resultrT   rU   rV   r   )rX   r   r   r   outcomer   r   r   r!   r     s    


z)TestCase._internal_add_cleanup_on_success)r   r   c                 C   sf   | j }tjdd dkrDt|jjt|jj t|jj }||kS |  }| 	||j |
 S dS )zEReturns whether test is passed. Expected to be called during cleanup.N   )      )r   r]   version_inforS   r   rT   rU   rV   defaultTestResult_feedErrorsToResultrY   )rX   r   r   Zcurrent_failure_countr   r   r   r!   r   /  s    


z<TestCase._internal_ran_and_passed_when_called_during_cleanupc                    sJ   |   }|dr"|tdd }tt|  }|durFd||f}|S )ar  Formats both the test method name and the first line of its docstring.

    If no docstring is given, only returns the method name.

    This method overrides unittest.TestCase.shortDescription(), which
    only returns the first line of the docstring, obscuring the name
    of the test upon failure.

    Returns:
      desc: A short description of a test method.
    r   N
)id
startswithrS   r   r   shortDescriptionrA   )rX   descdoc_first_liner   r   r!   r   C  s    
zTestCase.shortDescriptionc                 C   s"   | |s| d||f | dS )zAsserts that actual.startswith(expected_start) is True.

    Args:
      actual: str
      expected_start: str
      msg: Optional message to report on failure.
    z%r does not start with %rNr   fail)rX   actualexpected_startmsgr   r   r!   assertStartsWithb  s    
zTestCase.assertStartsWithc                 C   s"   | |r| d||f | dS )zAsserts that actual.startswith(unexpected_start) is False.

    Args:
      actual: str
      unexpected_start: str
      msg: Optional message to report on failure.
    z%r does start with %rNr   )rX   r   Zunexpected_startr   r   r   r!   assertNotStartsWithm  s    
zTestCase.assertNotStartsWithc                 C   s"   | |s| d||f | dS )zAsserts that actual.endswith(expected_end) is True.

    Args:
      actual: str
      expected_end: str
      msg: Optional message to report on failure.
    z%r does not end with %rNendswithr   )rX   r   Zexpected_endr   r   r   r!   assertEndsWithx  s    
zTestCase.assertEndsWithc                 C   s"   | |r| d||f | dS )zAsserts that actual.endswith(unexpected_end) is False.

    Args:
      actual: str
      unexpected_end: str
      msg: Optional message to report on failure.
    z%r does end with %rNr   )rX   r   Zunexpected_endr   r   r   r!   assertNotEndsWith  s    
zTestCase.assertNotEndsWithc              	   C   s   zt |}W n  ttfy,   |g}d}Y n0 zt |}W n. ttfyh   | d|t|f | Y n0 ||ksJ | |d||f |s|r| dt ||f | z| ||d| | W n& ty   | d||f | Y n0 dS )a  An equality assertion for the beginning of ordered sequences.

    If prefix is an empty sequence, it will raise an error unless whole is also
    an empty sequence.

    If prefix is not a sequence, it will raise an error if the first element of
    whole does not match.

    Args:
      prefix: A sequence expected at the beginning of the whole parameter.
      whole: The sequence in which to look for prefix.
      msg: Optional message to report on failure.
    rH   z>For whole: len(%s) is not supported, it appears to be type: %sz4Prefix length (%d) is longer than whole length (%d).z-Prefix length is 0 but whole length is %d: %sNz+prefix: %s not found at start of whole: %s.)rS   	TypeErrorNotImplementedErrorr   type_formatMessageassertSequenceEqualr   )rX   prefixZwholer   
prefix_lenZ	whole_lenr   r   r!   assertSequenceStartsWith  sB    



z!TestCase.assertSequenceStartsWithc                 C   sH   t |tjs$| dt|j| t|rD| d|t|| dS )zAsserts that an object has zero length.

    Args:
      container: Anything that implements the collections.abc.Sized interface.
      msg: Optional message to report on failure.
    "Expected a Sized object, got: {!r}z{!r} has length of {}.Nr   r   Sizedr   rN   r   r-   rS   rX   	containerr   r   r   r!   assertEmpty  s    zTestCase.assertEmptyc                 C   sB   t |tjs$| dt|j| t|s>| d|| dS )zAsserts that an object has non-zero length.

    Args:
      container: Anything that implements the collections.abc.Sized interface.
      msg: Optional message to report on failure.
    r   z{!r} has length of 0.Nr  r  r   r   r!   assertNotEmpty  s    zTestCase.assertNotEmptyc                 C   sZ   t |tjs$| dt|j| t||krVtj	
|}| d|t||| dS )zAsserts that an object has the expected length.

    Args:
      container: Anything that implements the collections.abc.Sized interface.
      expected_len: The expected length of the container.
      msg: Optional message to report on failure.
    r   z!{} has length of {}, expected {}.N)r   r   r  r   rN   r   r-   rS   r$   util	safe_repr)rX   r  expected_lenr   Zcontainer_reprr   r   r!   	assertLen  s    
zTestCase.assertLenc                 C   s   t |t |kr,| dt |t || g }tt||D ]^\}\}}	z| j||	|||d W q> | jy }
 z|d||
 W Y d}
~
q>d}
~
0 0 q>|rt |dkr|dd dg }| |d	|}| | dS )ak  An approximate equality assertion for ordered sequences.

    Fail if the two sequences are unequal as determined by their value
    differences rounded to the given number of decimal places (default 7) and
    comparing to zero, or by comparing that the difference between each value
    in the two sequences is more than the given delta.

    Note that decimal places (from zero) are usually not the same as significant
    digits (measured from the most significant digit).

    If the two sequences compare equal then they will automatically compare
    almost equal.

    Args:
      expected_seq: A sequence containing elements we are expecting.
      actual_seq: The sequence that we are testing.
      places: The number of decimal places to compare.
      msg: The message to be printed if the test fails.
      delta: The OK difference between compared values.
    z Sequence size mismatch: {} vs {})placesr   deltazAt index {}: {}N   ...r   )
rS   r   rN   	enumeratezipassertAlmostEqualfailureExceptionappendr   rA   )rX   expected_seq
actual_seqr  r   r  Zerr_listidxZexp_elemZact_elemerrr   r   r!   assertSequenceAlmostEqual  s&    
*z"TestCase.assertSequenceAlmostEqualc                 C   s2   t |t | }|sdS | d|||f | dS )zBChecks whether actual iterable is a superset of expected iterable.Nz+Missing elements %s
Expected: %s
Actual: %ssetr   )rX   Zexpected_subsetZ
actual_setr   missingr   r   r!   assertContainsSubset  s    zTestCase.assertContainsSubsetc                 C   s2   t |t |@ }|sdS | d|||f | dS )zBChecks whether actual iterable and expected iterable are disjoint.Nz*Common elements %s
Expected: %s
Actual: %sr  )rX   r  r  r   commonr   r   r!   assertNoCommonElements  s    zTestCase.assertNoCommonElementsc                    s   t  ||| dS )a  Deprecated, please use assertCountEqual instead.

    This is equivalent to assertCountEqual.

    Args:
      expected_seq: A sequence containing elements we are expecting.
      actual_seq: The sequence that we are testing.
      msg: The message to be printed if the test fails.
    N)r   assertCountEqual)rX   r  r  r   r   r   r!   assertItemsEqual'  s    
zTestCase.assertItemsEqualc                    s  t |tst |tr&| d||f  z\tdd |D tdd |D   fddD }fdd D }|  |  W n@ ty   t|t|      t \}}Y n0 g }|r||df |r|	d|  |r|	d	|  |s
|r| d

| dS )a1  Asserts that two sequences have the same elements (in any order).

    This method, unlike assertCountEqual, doesn't care about any
    duplicates in the expected and actual sequences::

        # Doesn't raise an AssertionError
        assertSameElements([1, 1, 1, 0, 0, 0], [0, 1])

    If possible, you should use assertCountEqual instead of
    assertSameElements.

    Args:
      expected_seq: A sequence containing elements we are expecting.
      actual_seq: The sequence that we are testing.
      msg: The message to be printed if the test fails.
    zuPassing string/bytes to assertSameElements is usually a bug. Did you mean to use assertEqual?
Expected: %s
Actual: %sc                 S   s   g | ]}|d fqS r   r   .0elementr   r   r!   
<listcomp>Q  r#   z/TestCase.assertSameElements.<locals>.<listcomp>c                 S   s   g | ]}|d fqS r   r   r!  r   r   r!   r$  R  r#   c                    s   g | ]}| vr|qS r   r   r!  )r   r   r!   r$  S  r#   c                    s   g | ]}| vr|qS r   r   r!  )expectedr   r!   r$  T  r#   :
zExpected, but missing:
  %r
zUnexpected, but present:
  %r
r3   N)r   _TEXT_OR_BINARY_TYPESr   dictsortr   list_sorted_list_differenceextendr  rA   )rX   r  r  r   r  
unexpectedrU   r   )r   r%  r!   assertSameElements3  s8    
zTestCase.assertSameElementsc           	      K   s  t |tsJ d|f t |ts0J d|f |dd}|rRtdt|||kr^dS |rn|d g}ndg}|r|t|7 }t|	d	|	d	D ]"}|
| |ds|
d q|rt||krt|| }|d| }|
d
| | d|dS )z.Asserts that two multi-line strings are equal.z"First argument is not a string: %rz#Second argument is not a string: %r
line_limitr   zUnexpected keyword args {}Nr&  r   Tz3(... and {} more delta lines omitted for brevity.)
r3   )r   r   popr   rN   tuplerS   difflibndiff
splitlinesr  r   r  rA   )	rX   firstsecondr   r   r/  failure_messagelineZ	n_omittedr   r   r!   assertMultiLineEqualk  sB    

zTestCase.assertMultiLineEqualc                 C   s:   |  |d|||f }| ||k| | ||k| dS )z8Asserts that value is between minv and maxv (inclusive).z+"%r" unexpectedly not between "%r" and "%r"N)r   
assertTrue)rX   r:   ZminvZmaxvr   r   r   r!   assertBetween  s    zTestCase.assertBetweenc                 C   s  t |tr| d| |s&| d| t|d }|dd D ]}t||ur>| d| q>|tu rt |trdd |D }t}n$|tu rt |trd	d |D }t}|tu rd
d| }n(|tu rdd| d }n| d| t||tj	s| d||f | dS )a  Asserts that at least one regex in regexes matches str.

    If possible you should use `assertRegex`, which is a simpler
    version of this method. `assertRegex` takes a single regular
    expression (a string or re compiled object) instead of a list.

    Notes:

    1. This function uses substring matching, i.e. the matching
       succeeds if *any* substring of the error message matches *any*
       regex in the list.  This is more convenient for the user than
       full-string matching.

    2. If regexes is the empty list, the matching will always fail.

    3. Use regexes=[''] for a regex that will always pass.

    4. '.' matches any single character *except* the newline.  To
       match any character, use '(.|\n)'.

    5. '^' matches the beginning of each line, not just the beginning
       of the string.  Similarly, '$' matches the end of each line.

    6. An exception will be thrown if regexes contains an invalid
       regex.

    Args:
      actual_str:  The string we try to match with the items in regexes.
      regexes:  The regular expressions we want to match against str.
          See "Notes" above for detailed notes on how this is interpreted.
      message:  The message to be printed if the test fails.
    z4regexes is string or bytes; use assertRegex instead.zNo regexes specified.r   rH   Nz'regexes list must all be the same type.c                 S   s   g | ]}| d qS rb   )decoder"  regexr   r   r!   r$    r#   z-TestCase.assertRegexMatch.<locals>.<listcomp>c                 S   s   g | ]}| d qS r<  encoder>  r   r   r!   r$    r#   z(?:%s)z)|(?:s   (?:s   )|(?:   )z8Only know how to deal with unicode str or bytes regexes.z/"%s" does not contain any of these regexes: %s.)
r   r'  r   r   bytesr   rA   research	MULTILINE)rX   Z
actual_strregexesmessageZ
regex_typer?  r   r   r!   assertRegexMatch  s:    !
zTestCase.assertRegexMatchr#   c           	      C   s   t |||\}}t|d tr,dd |D }t|}| |d| |dt||t|f  | j||| |dt||t||f d dS )an  Asserts that a shell command succeeds (i.e. exits with code 0).

    Args:
      command: List or string representing the command to run.
      regexes: List of regular expression byte strings that match success.
      env: Dictionary of environment variable settings. If None, no environment
          variables will be set for the child process. This is to make tests
          more hermetic. NOTE: this behavior is different than the standard
          subprocess module.
      close_fds: Whether or not to close all open fd's in the child after
          forking.
      msg: Optional message to report on failure.
    r   c                 S   s   g | ]}| d qS r<  r@  r>  r   r   r!   r$    r#   z2TestCase.assertCommandSucceeds.<locals>.<listcomp>z;Running command
%s failed with error code %s and message
%sXRunning command
%s failed with error code %s and message
%s which matches no regex in %srH  N)get_command_stderrr   r   get_command_stringassertEqualr   _quote_long_stringrI  	rX   commandrG  env	close_fdsr   Zret_coder  command_stringr   r   r!   assertCommandSucceeds  s:    	zTestCase.assertCommandSucceedsc           	      C   s   t |||\}}t|d tr,dd |D }t|}| |d| |dt|  | j||| |dt||t||f d dS )aa  Asserts a shell command fails and the error matches a regex in a list.

    Args:
      command: List or string representing the command to run.
      regexes: the list of regular expression strings.
      env: Dictionary of environment variable settings. If None, no environment
          variables will be set for the child process. This is to make tests
          more hermetic. NOTE: this behavior is different than the standard
          subprocess module.
      close_fds: Whether or not to close all open fd's in the child after
          forking.
      msg: Optional message to report on failure.
    r   c                 S   s   g | ]}| d qS r<  r@  r>  r   r   r!   r$    r#   z/TestCase.assertCommandFails.<locals>.<listcomp>z:The following command succeeded while expected to fail:
%srK  rL  N)rM  r   r   rN  assertNotEqualr   rP  rI  rQ  r   r   r!   assertCommandFails  s0    zTestCase.assertCommandFailsc                   @   s&   e Zd ZdddZdd Zdd ZdS )	zTestCase._AssertRaisesContextNc                 C   s   || _ || _|| _|| _d S r   )expected_exception	test_case	test_funcr   )rX   rY  rZ  r[  r   r   r   r!   rk   +  s    z&TestCase._AssertRaisesContext.__init__c                 C   s   | S r   r   rW   r   r   r!   	__enter__1  s    z'TestCase._AssertRaisesContext.__enter__c                 C   sN   |d u r | j | jjd | j t|| js0dS | | |rJ|d | _dS )Nz not raisedFT)	rZ  r   rY  r-   r   
issubclassr[  with_traceback	exception)rX   exc_type	exc_valuetbr   r   r!   __exit__4  s    
z&TestCase._AssertRaisesContext.__exit__)N)r-   r.   r/   rk   r\  rc  r   r   r   r!   _AssertRaisesContext)  s   
rd  )r   c                 C   s   |  d d d S r   rd  )rX   rY  	predicater   r   r!   assertRaisesWithPredicateMatch?  s    z'TestCase.assertRaisesWithPredicateMatch)callable_objr   c                 O   s   |  d d d S r   re  )rX   rY  rf  rh  r   r   r   r   r!   rg  F  s    c                    s^    fdd} ||}|du r(|S | ||i | W d   n1 sP0    Y  dS )a?  Asserts that exception is thrown and predicate(exception) is true.

    Args:
      expected_exception: Exception class expected to be raised.
      predicate: Function of one argument that inspects the passed-in exception
          and returns True (success) or False (please fail the test).
      callable_obj: Function to be called.
      *args: Extra args.
      **kwargs: Extra keyword args.

    Returns:
      A context manager if callable_obj is None. Otherwise, None.

    Raises:
      self.failureException if callable_obj does not raise a matching exception.
    c                    s     | d|  f  d S )Nz%r does not match predicate %r)r:  )r  rf  rX   r   r!   Check`  s    

z6TestCase.assertRaisesWithPredicateMatch.<locals>.CheckNre  )rX   rY  rf  rh  r   r   rj  contextr   ri  r!   rg  N  s    c                 C   s   |  d d d S r   re  )rX   rY  expected_exception_messager   r   r!   assertRaisesWithLiteralMatchj  s    z%TestCase.assertRaisesWithLiteralMatchc                 O   s   |  d d d S r   re  )rX   rY  rl  rh  r   r   r   r   r!   rm  r  s    c                    s^    fdd} ||}|du r(|S | ||i | W d   n1 sP0    Y  dS )a)  Asserts that the message in a raised exception equals the given string.

    Unlike assertRaisesRegex, this method takes a literal string, not
    a regular expression.

    with self.assertRaisesWithLiteralMatch(ExType, 'message'):
      DoSomething()

    Args:
      expected_exception: Exception class expected to be raised.
      expected_exception_message: String message expected in the raised
          exception.  For a raise exception e, expected_exception_message must
          equal str(e).
      callable_obj: Function to be called, or None to return a context.
      *args: Extra args.
      **kwargs: Extra kwargs.

    Returns:
      A context manager if callable_obj is None. Otherwise, None.

    Raises:
      self.failureException if callable_obj does not raise a matching exception.
    c                    s$   t | } |kd |f  d S )Nz9Exception message does not match.
Expected: %r
Actual: %r)r   r:  )r  Zactual_exception_messagerl  rX   r   r!   rj    s    
z4TestCase.assertRaisesWithLiteralMatch.<locals>.CheckNre  )rX   rY  rl  rh  r   r   rj  rk  r   rn  r!   rm  z  s    c                 C   s   t |tttu rtntfr |f}d}d}|D ]`}|t||}|dkrf|dkrf| d||f | n|dkr| d|||f | |}|}q,dS )at  Asserts that the strings provided are found in the target in order.

    This may be useful for checking HTML output.

    Args:
      strings: A list of strings, such as [ 'fox', 'dog' ]
      target: A target string in which to look for the strings, such as
          'The quick brown fox jumped over the lazy dog'.
      msg: Optional message to report on failure.
    r   NzDid not find '%s' in '%s'z$Did not find '%s' after '%s' in '%s')r   rC  r   unicodefindr   )rX   stringstargetr   current_indexZlast_stringstringindexr   r   r!   assertContainsInOrder  s(    zTestCase.assertContainsInOrderc                 C   sb   d}t t|}t |}|D ]"}||vr0|} q@|| krq0q|dur^| d|||f | dS )a  Asserts that "container" contains "subsequence" as a subsequence.

    Asserts that "container" contains all the elements of "subsequence", in
    order, but possibly with other elements interspersed. For example, [1, 2, 3]
    is a subsequence of [0, 0, 1, 2, 0, 3, 0] but not of [0, 0, 1, 3, 0, 2, 0].

    Args:
      container: the list we're testing for subsequence inclusion.
      subsequence: the list we hope will be a subsequence of container.
      msg: Optional message to report on failure.
    Nz:%s not a subsequence of %s. First non-matching element: %s)r*  reversedr0  r   )rX   r  subsequencer   Zfirst_nonmatchingZreversed_containerer   r   r!   assertContainsSubsequence  s    z"TestCase.assertContainsSubsequencec                 C   s   t |}t |}d}tdt| t| D ]L}|t|kr@ qzd}|t|k rn|| |||  krn|d7 }qDt||}q,|t|k r| d|||d| f | dS )a  Asserts that "container" contains "subsequence" as an exact subsequence.

    Asserts that "container" contains all the elements of "subsequence", in
    order, and without other elements interspersed. For example, [1, 2, 3] is an
    exact subsequence of [0, 0, 1, 2, 3, 0] but not of [0, 0, 1, 2, 0, 3, 0].

    Args:
      container: the list we're testing for subsequence inclusion.
      subsequence: the list we hope will be an exact subsequence of container.
      msg: Optional message to report on failure.
    r   rH   z>%s not an exact subsequence of %s. Longest matching prefix: %sN)r*  rangerS   maxr   )rX   r  ry  r   Zlongest_matchstartrv  r   r   r!   assertContainsExactSubsequence  s$    
z'TestCase.assertContainsExactSubsequencec                    s    fdd} fdd}| d tj| D ]F}t|}t|dd D ](\}}||d d D ]}||| qdqLq0|D ]8}	|	D ]}
||
|
 qt|	|	D ]\}
}||
| qq|dS )	aS  Asserts that total ordering has been implemented correctly.

    For example, say you have a class A that compares only on its attribute x.
    Comparators other than ``__lt__`` are omitted for brevity::

        class A(object):
          def __init__(self, x, y):
            self.x = x
            self.y = y

          def __hash__(self):
            return hash(self.x)

          def __lt__(self, other):
            try:
              return self.x < other.x
            except AttributeError:
              return NotImplemented

    assertTotallyOrdered will check that instances can be ordered correctly.
    For example::

        self.assertTotallyOrdered(
            [None],  # None should come before everything else.
            [1],  # Integers sort earlier.
            [A(1, 'a')],
            [A(2, 'b')],  # 2 is after 1.
            [A(3, 'c'), A(3, 'd')],  # The second argument is irrelevant.
            [A(4, 'z')],
            ['foo'])  # Strings sort last.

    Args:
      *groups: A list of groups of elements.  Each group of elements is a list
        of objects that are equal.  The elements in each group must be less
        than the elements in the group after it.  For example, these groups are
        totally ordered: ``[None]``, ``[1]``, ``[2, 2]``, ``[3]``.
      **kwargs: optional msg keyword argument can be passed.
    c              	      s    | |k d| |f  | |k d| |f  | |   || k  d|| f  | |   || kd|| f   ||    | |k d| |f  ||   | |k d| |f  dS )z$Ensures small is ordered before big.z%r unexpectedly equals %r%r unexpectedly less than %rz(%r unexpectedly less than or equal to %r%r unexpectedly greater than %rz+%r unexpectedly greater than or equal to %rN)assertFalser   r:  
assertLessassertLessEqualassertGreaterassertGreaterEqual)smallbigr   rX   r   r!   
CheckOrder  sF    




z1TestCase.assertTotallyOrdered.<locals>.CheckOrderc                    s4   | |  | |k d| |f  t| tjrxt|tjrx t| t| dt| | t||f  | |k  d| |f  || k  d|| f  | |  ||   | |k d| |f  || k d|| f  | |  ||   dS )zEnsures that a and b are equal.z%r unexpectedly unequals %rz5hash %d of %r unexpectedly not equal to hash %d of %rr  r  N)	rO  r  r   r   r   Hashablehashr  r  ar   r  r   r!   
CheckEqual9  sb    





z1TestCase.assertTotallyOrdered.<locals>.CheckEqualr   Nro  rH   )r6   	itertoolsproductr*  r  )rX   groupsr   r  r  elementsrv  r  r  groupr  r   r   r  r!   assertTotallyOrdered  s    (&
zTestCase.assertTotallyOrderedc                    s  |  |t| |d |  |t| |d dd }||kr@dS |t| }|t| }g }g }g }	tjj  fdd}
d|
||
||rd	| nd
f g}|D ]@\}}||vr|||f q||| kr|	|||| f q|D ]\}}||vr|||f q|r6|dd
	 fdd|D   |	r^|dd
	 fdd|	D   |r|dd
	 fdd|D   | 
d	|dS )a  Raises AssertionError if a and b are not equal dictionaries.

    Args:
      a: A dict, the expected value.
      b: A dict, the actual value.
      msg: An optional str, the associated message.

    Raises:
      AssertionError: if the dictionaries are not equal.
    z"First argument is not a dictionaryz#Second argument is not a dictionaryc                 S   s&   z
t | W S  ty    |  Y S 0 d S r   )sortedr   )Zlist_of_itemsr   r   r!   Sorted  s    
z(TestCase.assertDictEqual.<locals>.SortedNc                    s2   t  fdd|  D }dddd |D  S )zDeterministic repr for dict.c                 3   s"   | ]\}} | |fV  qd S r   r   r"  kvr  r   r!   	<genexpr>  r#   z9TestCase.assertDictEqual.<locals>.Repr.<locals>.<genexpr>z{%s}z, c                 s   s   | ]}d | V  qdS )z%s: %sNr   )r"  pairr   r   r!   r    r#   )r  itemsrA   )Zdiktentriesr  r   r!   Repr  s    z&TestCase.assertDictEqual.<locals>.Reprz
%s != %s%sz (%s)r3   z#Unexpected, but present entries:
%sc                 3   s&   | ]\}}d  | |f V  qdS z%s: %s
Nr   r  r  r   r!   r    s   z+TestCase.assertDictEqual.<locals>.<genexpr>zrepr() of differing entries:
%sc                 3   s.   | ]&\}}}d  | | |f V  qdS )z%s: %s != %s
Nr   )r"  r  a_valueb_valuer  r   r!   r    s   zMissing entries:
%sc                 3   s&   | ]\}}d  | |f V  qdS r  r   r  r  r   r!   r    r#   r   )assertIsInstancer(  r   r*  r  r$   r  r  r  rA   r  )rX   r  r   r   r  Za_itemsZb_itemsr-  r  Z	differentr  rH  Za_keyr  Zb_keyr  r   r  r!   assertDictEqualp  s\    $zTestCase.assertDictEqualc                 C   s   t |}t |}| |j|j| | |j|j| | |j|j| | |j|j| | t|j	dt|j	d| | 
t j|jddt j|jdd| dS )z?Asserts that urls are equal, ignoring ordering of query params.;T)keep_blank_valuesN)r   urlparserO  schemenetlocr@   fragmentr  paramssplitr  parse_qsquery)rX   r  r   r   Zparsed_aZparsed_br   r   r!   assertUrlEqual  s    

zTestCase.assertUrlEqualr  r   c                 C   sd   g }t ||||| | jdurJ| jd }t||krJ|d|d  dg }|r`| d|| dS )a  Asserts that two values contain the same structural content.

    The two arguments should be data trees consisting of trees of dicts and
    lists. They will be deeply compared by walking into the contents of dicts
    and lists; other items will be compared using the == operator.
    If the two structures differ in content, the failure message will indicate
    the location within the structures where the first difference is found.
    This may be helpful when comparing large structures.

    Mixed Sequence and Set types are supported. Mixed Mapping types are
    supported, but the order of the keys will not be considered in the
    comparison.

    Args:
      a: The first structure to compare.
      b: The second structure to compare.
      aname: Variable name to use for the first structure in assertion messages.
      bname: Variable name to use for the second structure.
      msg: Additional text to include in the failure message.
    NP   r   rH   r  z; )_walk_structure_for_problemsmaxDiffrS   r   rA   )rX   r  r   anamebnamer   problemsZmax_problems_to_showr   r   r!   assertSameStructure  s    

zTestCase.assertSameStructurec              
   C   s   zt |}W n< tyJ } z$t| |d||f W Y d}~n
d}~0 0 zt |}W n< ty } z$t| |d||f W Y d}~n
d}~0 0 | j||dd|d dS )a  Asserts that the JSON objects defined in two strings are equal.

    A summary of the differences will be included in the failure message
    using assertSameStructure.

    Args:
      first: A string containing JSON to decode and compare to second.
      second: A string containing JSON to decode and compare to first.
      msg: Additional text to include in the failure message.
    z(could not decode first JSON value %s: %sNz)could not decode second JSON value %s: %sr5  r6  )r  r  r   )jsonloadsr8   r   r  )rX   r5  r6  r   Zfirst_structuredrz  Zsecond_structuredr   r   r!   assertJsonEqual  s"    

zTestCase.assertJsonEqualc                    sV   zt t| ||W S  tyB   t| dd}t t| | Y n0 t t| ||S )Nr   r:  )r   r   _getAssertEqualityFuncAttributeErrorr   rk   )rX   r5  r6  test_methodr   r   r!   r    s    zTestCase._getAssertEqualityFuncc                    s   t t| | ||S )z=Fail immediately with the given message, optionally prefixed.)r   r   r   r   )rX   r   r   r   r   r!   r     s    zTestCase.fail)NN)NNrp   rq   rr   N)N)N)N)N)N)N)N)N)NNN)N)N)N)N)N)N)N)rJ  NTN)NTN)N)N)N)N)N)N)N)r  r   N)N)NN)Ar-   r.   r/   r   r)   r0   r   r  longMessager   r   rk   r   r   r   r   r   r   r   r   r   r   r   r   r
   r   r7   boolr   r   r   r   r   r   r   r  r  r
  r  r  r  r   r.  r9  r;  rI  rV  rX  objectrd  typingoverloadrg  rm  rw  r{  r  r  r  r  r  r  r  r   __classcell__r   r   r   r!   r   @  s   

7  
7








*


  
-
	
	
8


?  
.  
*
 
	 
(


z
M

%
r   c                 C   s4  d }}g }g }z| | }|| }||k rT| | |d7 }| | |kr|d7 }q<n||kr| | |d7 }|| |kr|d7 }qnnb|d7 }z8| | |kr|d7 }qW |d7 }|| |kr|d7 }qn |d7 }|| |kr|d7 }q0 W q ty(   || |d  |||d  Y q,Y q0 q||fS )aO  Finds elements in only one or the other of two, sorted input lists.

  Returns a two-element tuple of lists.  The first list contains those
  elements in the "expected" list but not in the "actual" list, and the
  second contains those elements in the "actual" list but not in the
  "expected" list.  Duplicate elements in either input list are ignored.

  Args:
    expected:  The list we expected.
    actual:  The list we actually got.
  Returns:
    (missing, unexpected)
    missing: items in expected that are not in actual.
    unexpected: items in actual that are not in expected.
  r   rH   N)r  
IndexErrorr,  )r%  r   ijr  r-  rz  r  r   r   r!   r+    s>    

r+  c                 C   s   t | tot |tS r   )r   r7   r  r   r   r!   _are_both_of_integer_typeQ  s    r  c                 C   s0   t | tjo.t |tjo.t | t o.t |t S r   )r   r   r   r'  r  r   r   r!   _are_both_of_sequence_typeV  s    
r  c                 C   s   t | tjot |tjS r   )r   r   Setr  r   r   r!   _are_both_of_set_type]  s    r  c                 C   s   t | tjot |tjS r   )r   r   r   r  r   r   r!   _are_both_of_mapping_typeb  s    r  c              	   C   s6  t | t |krZt| |sZt| |sZt| |sZt| |sZ|d|t | |t |f  dS t| tjr| D ] }||vrj|d|||f  qj|D ] }|| vr|d|||f  qn|t| tj	rL| D ]P}||v rt
| | || d||f d||f | q|d||| | |f  q|D ]*}|| vr|d||||| f  qnt| tjrt| tstt| t|}t|D ].}t
| | || d||f d||f | qt|t| D ] }|d	||| | |f  qt|t|D ] }|d
||||| f  qn | |kr2|d|| ||f  dS )z4The recursive comparison behind assertSameStructure.z%s is a %r but %s is a %rNz%s has %r but %s does notz%s lacks %r but %s has itz%s[%r]z0%s has [%r] with value %r but it's missing in %sz)%s lacks [%r] but %s has it with value %rz%s[%d]z)%s has [%i] with value %r but %s does notz)%s lacks [%i] but %s has it with value %rz%s is %r but %s is %r)r   r  r  r  r  r  r   r   r  r   r  r   r'  minrS   r|  )r  r   r  r  Zproblem_listr  Zminlenr  r   r   r!   r  h  sx     

 

r  c                 C   sX   t | tr| S tjdkr"d| S d}| D ]}|d|dd d 7 }q*|dd S dS )	zReturns an escaped string that can be used as a shell command.

  Args:
    command: List or string representing the command to run.
  Returns:
    A string suitable for use as a shell command.
  nt r3   'z'"'"'z' Nro  )r   r   r4   r   rA   r   )rR  rU  wordr   r   r!   rN    s    


rN  c                 C   sZ   |du ri }t jdkrd}t| t}tj| |||tjtjd}| d }|	 }||fS )af  Runs the given shell command and returns a tuple.

  Args:
    command: List or string representing the command to run.
    env: Dictionary of environment variable settings. If None, no environment
        variables will be set for the child process. This is to make tests
        more hermetic. NOTE: this behavior is different than the standard
        subprocess module.
    close_fds: Whether or not to close all open fd's in the child after forking.
        On Windows, this is ignored and close_fds is always False.

  Returns:
    Tuple of (exit status, text printed to stdout and stderr by the command).
  Nr  F)rT  rS  shellr^   stdoutr   )
r4   r   r   r   
subprocessPopenSTDOUTPIPEcommunicatewait)rR  rS  rT  Z	use_shellprocessoutputZexit_statusr   r   r!   rM    s    

rM  c                 C   sH   t | ttfr8z| d} W n ty6   t| } Y n0 d|  d d S )zQuotes a potentially multi-line string to make the start and end obvious.

  Args:
    s: A string.

  Returns:
    The quoted string.
  rb   z8<-----------
r   z----------->8
)r   rC  	bytearrayr=  UnicodeDecodeErrorr   )sr   r   r!   rP    s    
rP  c                   C   s&   t jdt jt jrt jnd d S )Nz5Running tests under Python {0[0]}.{0[1]}.{0[2]}: {1}
z	embedded.)r]   r^   r_   rN   r   
executabler   r   r   r!   print_python_version  s    
r  c                  O   s   t   tt| | dS )a  Executes a set of Python unit tests.

  Usually this function is called without arguments, so the
  unittest.TestProgram instance will get created with the default settings,
  so it will run all test methods of all TestCase classes in the ``__main__``
  module.

  Args:
    *args: Positional arguments passed through to
        ``unittest.TestProgram.__init__``.
    **kwargs: Keyword arguments passed through to
        ``unittest.TestProgram.__init__``.
  N)r  _run_in_app	run_testsr   r   r   r!   main  s    r  c                  C   s,   t  j} | r(| jtjjkr dS | j} q
dS )z#Returns True iff app.run is active.TF)r]   	_getframef_backf_coder   run__code__r   r   r   r!   _is_in_app_main  s    
r  c               
   C   s^   t rZtt ddrZzt jtjdd W n4 tyX }  ztjd|   W Y d} ~ n
d} ~ 0 0 dS )zGHave faulthandler dump stacks on SIGTERM.  Useful to diagnose timeouts.registerNT)chainz4faulthandler.register(SIGTERM) failed %r; ignoring.
)	faulthandlerr   r  signalSIGTERM	Exceptionr]   r^   r_   )rz  r   r   r!   #_register_sigterm_with_faulthandler  s    r  c              
      s   t  rt  tdd i }dd }tD ]}t| j||< q(tD ]}|t| _q@z0ttj}W tD ]}|| t| _qbtj  n$tD ]}|| t| _qtj  0 |  n(tdd  fdd}t	j
|d dS )	a  Executes a set of Python unit tests, ensuring app.run.

  This is a private function, users should call absltest.main().

  _run_in_app calculates argv to be the command-line arguments of this program
  (without the flags), sets the default of FLAGS.alsologtostderr to True,
  then it calls function(argv, args, kwargs), making sure that `function'
  will get called within app.run(). _run_in_app does this by checking whether
  it is called by app.run(), or by calling app.run() explicitly.

  The reason why app.run has to be ensured is to make sure that
  flags are parsed and stripped properly, and other initializations done by
  the app module are also carried out, no matter if absltest.run() is called
  from within or outside app.run().

  If _run_in_app is called from within app.run(), then it will reparse
  sys.argv and pass the result without command-line flags into the argv
  argument of `function'. The reason why this parsing is needed is that
  __main__.main() calls absltest.main() without passing its argv. So the
  only way _run_in_app could get to know the argv without the flags is that
  it reparses sys.argv.

  _run_in_app changes the default of FLAGS.alsologtostderr to True so that the
  test program's stderr will contain all the log messages unless otherwise
  specified on the command-line. This overrides any explicit assignment to
  FLAGS.alsologtostderr by the test program prior to the call to _run_in_app()
  (e.g. in __main__.main).

  Please note that _run_in_app (and the function it calls) is allowed to make
  changes to kwargs.

  Args:
    function: absltest.run_tests or a similar function. It will be called as
        function(argv, args, kwargs) where argv is a list containing the
        elements of sys.argv without the command-line flags.
    args: Positional arguments passed through to unittest.TestProgram.__init__.
    kwargs: Keyword arguments passed through to unittest.TestProgram.__init__.
  alsologtostderrTc                 S   s   d S r   r   )rx   r   r   r!   r"   Y  r#   z_run_in_app.<locals>.<lambda>c                    s   t   |   d S r   )r  argvr   r   r   r   r!   main_functionn  s    z"_run_in_app.<locals>.main_function)r  N)r  r  rJ   set_defaultr   r]   r  r  flushr   r  )r   r   r   Zstored_parse_methodsZ
noop_parser   r  r  r   r  r!   r  $  s*    (r  c                 C   s   | drt|dkr|d  rt| |}t|s@t|rt|}t|jdko|jd dko|j	du o|j
du o|j S dS )zBReturns True if an attribute is a method named like a test method.ZTest   rH   r   rX   NF)r   rS   isupperr   inspect
isfunctionismethodgetfullargspecr   varargsvarkw
kwonlyargs)testCaseClassr   attrr   r   r   r!   _is_suspicious_attributeu  s    "

r  c                    s(   t  trtd  fdd}|S )a  Skip tests in the decorated TestCase, but not any of its subclasses.

  This decorator indicates that this class should skip all its tests, but not
  any of its subclasses. Useful for if you want to share testMethod or setUp
  implementations between a number of concrete testcase classes.

  Example usage, showing how you can share some common test methods between
  subclasses. In this example, only ``BaseTest`` will be marked as skipped, and
  not RealTest or SecondRealTest::

      @absltest.skipThisClass("Shared functionality")
      class BaseTest(absltest.TestCase):
        def test_simple_functionality(self):
          self.assertEqual(self.system_under_test.method(), 1)

      class RealTest(BaseTest):
        def setUp(self):
          super().setUp()
          self.system_under_test = MakeSystem(argument)

        def test_specific_behavior(self):
          ...

      class SecondRealTest(BaseTest):
        def setUp(self):
          super().setUp()
          self.system_under_test = MakeSystem(other_arguments)

        def test_other_behavior(self):
          ...

  Args:
    reason: The reason we have a skip in place. For instance: 'shared test
      methods' or 'shared assertion methods'.

  Returns:
    Decorator function that will cause a class to be skipped.
  z#Got {!r}, expected reason as stringc                    sF   t tjstdjdd  t fdd}|_S )Nz+Decorating {!r}, expected TestCase subclassr   c                    sF   | u rt  r,j| g|R i |S t| j|i |S d S r   )SkipTest__func__r   r   )r   r   r   )r'   shadowed_setupclasstest_case_classr   r!   replacement_setupclass  s
    zBskipThisClass.<locals>._skip_class.<locals>.replacement_setupclass)	r]  r$   r   r   rN   __dict__r6   r   r   )r  r  r'   )r  r  r!   _skip_class  s    z"skipThisClass.<locals>._skip_class)r   r   r   rN   )r'   r
  r   r	  r!   skipThisClass  s    (
r  c                       s6   e Zd ZdZedZ fddZ fddZ  Z	S )
TestLoadera  A test loader which supports common test features.

  Supported features include:
   * Banning untested methods with test-like names: methods attached to this
     testCase with names starting with `Test` are ignored by the test runner,
     and often represent mistakenly-omitted test cases. This loader will raise
     a TypeError when attempting to load a TestCase with such methods.
   * Randomization of test case execution order (optional).
  zMethod '%s' is named like a test case but
  is not one. This is often a bug. If you want it to be a test method,
  name it with 'test' in lowercase. If not, rename the method to not begin
  with 'Test'.c                    sF   t t| j|i | t }|r6|| _t| j| _nd | _d | _d S r   )r   r  rk   rP   _randomize_ordering_seedrG   rL   _random)rX   r   kwdsrO   r   r   r!   rk     s    zTestLoader.__init__c                    sl   t |D ]}t||rttj| qtt| |}| jdurht	d| j t	d| j | j
| |S )zFValidates and returns a (possibly randomized) list of test case names.Nz$Randomizing test order with seed: %dzFTo reproduce this order, re-run with --test_randomize_ordering_seed=%d)r{   r  r   r  
_ERROR_MSGr   getTestCaseNamesr  r   infor  shuffle)rX   r   r   namesr   r   r!   r    s    

zTestLoader.getTestCaseNames)
r-   r.   r/   r   textwrapdedentr  rk   r  r  r   r   r   r!   r    s   


r  c                	   C   s|   t jdrt jd S t jdr:t jt jtjdS t jdrxt jt jd t jt j	t
jd d d S d S )NZXML_OUTPUT_FILEZRUNNING_UNDER_TEST_DAEMONztest_detail.xmlZTEST_XMLOUTPUTDIRr   z.xml)r4   r5   r6   r@   rA   r   r?   r:   splitextbasenamer]   r  r   r   r   r!   get_default_xml_output_filename  s    
 r  c                 C   sV   t jd}| du s|sdS t|}tjdd dkrFdd |D }|| dd< dS )ao  Implements the bazel test filtering protocol.

  The following environment variable is used in this method:

    TESTBRIDGE_TEST_ONLY: string, if set, is forwarded to the unittest
      framework to use as a test filter. Its value is split with shlex, then:
      1. On Python 3.6 and before, split values are passed as positional
         arguments on argv.
      2. On Python 3.7+, split values are passed to unittest's `-k` flag. Tests
         are matched by glob patterns or substring. See
         https://docs.python.org/3/library/unittest.html#cmdoption-unittest-k

  Args:
    argv: the argv to mutate in-place.
  ZTESTBRIDGE_TEST_ONLYNr   )r      c                 S   s   g | ]}d | qS )z-k=r   )r"  test_filterr   r   r!   r$  	  r#   z$_setup_filtering.<locals>.<listcomp>rH   )r4   r5   r6   shlexr  r]   r   )r  r  filtersr   r   r!   _setup_filtering	  s    
r  c                 C   s2   | du rdS t jddkr dS dg| dd< dS )a)  Implements the bazel test fail fast protocol.

  The following environment variable is used in this method:

    TESTBRIDGE_TEST_RUNNER_FAIL_FAST=<1|0>

  If set to 1, --failfast is passed to the unittest framework to return upon
  first failure.

  Args:
    argv: the argv to mutate in-place.
  NZ TESTBRIDGE_TEST_RUNNER_FAIL_FAST1z
--failfastrH   r=   r  r   r   r!   _setup_test_runner_fail_fast	  s
    r   c                    s  dt jv r|z>tt jd d}|d W d   n1 s<0    Y  W n2 tyz   tjdt jd   td Y n0 | pt }dt jvr|S t	t jd }t	t jd d	k s|krtjd
|f  td |j
tt|  fdd}||_
|S )a  Implements the bazel sharding protocol.

  The following environment variables are used in this method:

    TEST_SHARD_STATUS_FILE: string, if set, points to a file. We write a blank
      file to tell the test runner that this test implements the test sharding
      protocol.

    TEST_TOTAL_SHARDS: int, if set, sharding is requested.

    TEST_SHARD_INDEX: int, must be set if TEST_TOTAL_SHARDS is set. Specifies
      the shard index for this instance of the test process. Must satisfy:
      0 <= TEST_SHARD_INDEX < TEST_TOTAL_SHARDS.

  Args:
    custom_loader: A TestLoader to be made sharded.

  Returns:
    The test loader for shard-filtering or the standard test loader, depending
    on the sharding environment variables.
  ZTEST_SHARD_STATUS_FILErp   r3   Nz3Error opening TEST_SHARD_STATUS_FILE (%s). Exiting.rH   ZTEST_TOTAL_SHARDSZTEST_SHARD_INDEXr   z/ERROR: Bad sharding values. index=%d, total=%d
c                    sF   g  | }t |D ]}t}|kr | q fdd|D S )Nc                    s   g | ]}| v r|qS r   r   )r"  xZfiltered_namesr   r!   r$  x	  r#   zD_setup_sharding.<locals>.getShardedTestCaseNames.<locals>.<listcomp>)r  nextr  )r   Zordered_namestestcasebucketZbucket_iteratorZdelegate_get_namesshard_indexr"  r!   getShardedTestCaseNamesn	  s    z0_setup_sharding.<locals>.getShardedTestCaseNames)r4   r5   r   r_   IOErrorr]   r^   exitr  r7   r  r  cycler|  )Zcustom_loaderr    Zbase_loaderZtotal_shardsr(  r   r&  r!   _setup_sharding7	  s0    
,


r,  c                 C   sT  | d| } t|  t|  t|dd|d< tjs>t t_tj}d}|rxtj	
|}|rtj	|szt| W n2 ty } z|jtjkr W Y d}~n
d}~0 0 t|d W d   n1 s0    Y  |ddurt|d dstjd|d   ||d< |ddu r*||d< t }|d | t|d dd}t|d d	d}	|r|	r|	d
| n|ddu rtj|d< tjr|d }
t|
trt|
tjst|
tjrd|
_tj	t j!s(ztt j! W n6 ty& } z|jtjkr W Y d}~n
d}~0 0 | |d< zt"j#|i |}|j$W |rzFt|d}||%  W d   n1 s0    Y  W |&  S |&  0 S zFt|d}||%  W d   n1 s0    Y  W |&  n
|&  0 nZ|rNzFt|d}||%  W d   n1 s.0    Y  W |&  n
|&  0 0 dS )zCSame as run_tests, except it returns the result instead of exiting.r  
testLoaderNrp   
testRunnerset_default_xml_streamzkWARNING: XML_OUTPUT_FILE or --xml_output_file setting overrides testRunner=%r setting (possibly from --pdb)r  Zset_testsuites_propertyrF   T)'r0  r  r   r,  r6   rJ   rR   r  r4   r@   r   isdirr   OSErrorerrnoEEXISTrf   r   r]   r^   r_   r   StringIOr/  r   r   TextTestRunnerpdb_post_mortemr   r   r]  Zrun_for_debuggingr?   r:   r$   TestProgramr   getvaluer   )r  r   r   Zxml_test_runner_classrR   Z
xml_bufferZxml_output_dirrz  Zrandomize_ordering_seedsetterrunnerZtest_programr    r   r   r!   _run_and_get_tests_result	  s    



0 00r;  c                 C   s$   t | ||tj}t|   dS )a  Executes a set of Python unit tests.

  Most users should call absltest.main() instead of run_tests.

  Please note that run_tests should be called from app.run.
  Calling absltest.main() would ensure that.

  Please note that run_tests is allowed to make changes to kwargs.

  Args:
    argv: sys.argv with the command-line flags removed from the front, i.e. the
      argv with which :func:`app.run()<absl.app.run>` has called
      ``__main__.main``. It is passed to
      ``unittest.TestProgram.__init__(argv=)``, which does its own flag parsing.
      It is ignored if kwargs contains an argv entry.
    args: Positional arguments passed through to
      ``unittest.TestProgram.__init__``.
    kwargs: Keyword arguments passed through to
      ``unittest.TestProgram.__init__``.
  N)r;  r	   ZTextAndXMLTestRunnerr]   r*  rY   )r  r   r   r   r   r   r!   r  	  s    
r  c                 C   sB   t j| r0zt |  W q> ty,   Y q>0 ntj| dd d S )NT)ignore_errors)r4   r@   isfileunlinkr1  shutilrmtree)r@   r   r   r!   r   
  s    r   c                 C   s   |  tjd}|d S )NrH   r   )r  r4   sep)r@   partsr   r   r!   r   
  s    r   )NT)N)tr   collectionsr   r   r2  enumr2  getpassr  r   r  r  r4   rG   rD  r  r?  r  r   r  r]   rB   r  r$   r   urllibr   r  ImportErrorabslr   r   r   absl.testingr   r	   r  r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   TYPE_CHECKINGTypeVarr   Zunittest.casecase_OutcomeZ_OutcomeTypeskipskipIf
skipUnlessr  r%   rJ   r   rC  r'  
__unittestr(   Enumr)   r;   r>   rE   rP   DEFINE_stringr<   r?   DEFINE_integerra   r   rf   r  rg   rs   r   r   r+  r  r  r  r  r  rN  rM  rP  r  r  r  r  r  r  r  r  r  r  r   r,  r;  r  r   r   r   r   r   r!   <module>   s   
T

2	Q "!         h2;
"
QK*
Hh