Your IP : 216.73.216.213


Current Path : /opt/alt/python35/lib/python3.5/site-packages/google/apputils/__pycache__/
Upload File :
Current File : //opt/alt/python35/lib/python3.5/site-packages/google/apputils/__pycache__/basetest.cpython-35.pyc



B��]���@s�dZdZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZyddlZWnek
r�dZYnXddlmZddlZddlmZejZdd�Zdd	�Zejd
e�ddd
�ejdejjdd�ddd
�ejde�ddd
�dd�Ze�Gdd�dej �Z dd�Z!Gdd�de"�Z#iZ$dd�Z%dd�Z&d d!�Z'da(d"d#�Z)Gd$d%�d%e"�Z*ddd&d'�Z+ddd(d)�Z,d*d+�Z-d,d-�Z.d.d/�Z/d0d1�Z0e1e1fZ2d2d3�Z3Gd4d5�d5e4�Z5Gd6d7�d7e6�Z7d8d9�Z8d:d;�Z9d<d=�Z:d>d?�Z;d@dA�Z<dBdC�Z=ddDdEdF�Z>dGdH�Z?GdIdJ�dJej@�ZAdKdL�ZBdMdN�ZCGdOdP�dPe"�ZDdQdR�ZEdSdT�ZFdS)UzyBase functionality for google tests.

This module contains base classes and high-level functions for Google-style
tests.
z$dborowitz@google.com (Dave Borowitz)�N)�app)�	shellutilcCsDd}tjjdd�}yt|�}Wntk
r?YnX|S)Ni-ZTEST_RANDOM_SEED�)�os�environ�get�int�
ValueError)Zrandom_seed�value�r�I/opt/alt/python35/lib/python3.5/site-packages/google/apputils/basetest.py�_GetDefaultTestRandomSeed8s
r
cCs:tjjdd�}|s6tjjtj�d�}|S)zGet default test temp dir.ZTEST_TMPDIRrZgoogle_apputils_basetest)rrr�path�join�tempfile�
gettempdir)Ztmpdirrrr�_GetDefaultTestTmpdirBsrZtest_random_seedz�Random 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.Zallow_override�Ztest_srcdirZTEST_SRCDIRrz.Root of directory tree where source files live�test_tmpdirz%Directory for temporary testing filescCscdd�}tjj�}|jd�|j�r_|tjj_|j�r_tjjd�dS)z3Workaround for <http://bugs.python.org/issue20165>.cSs>t|j�t|j�ko;t|j�ko;dkSS)zpTells whether or not this result was a success.

    Any unexpected pass is to be counted as a non-success.
    r)�len�failures�errors�unexpectedSuccesses)�selfrrr�
wasSuccessfulas z@_MonkeyPatchTestResultForUnexpectedPasses.<locals>.wasSuccessful�testz^unittest.result.TestResult monkey patch to report unexpected passes as failures did not work.
N)�unittest�result�
TestResult�addUnexpectedSuccessr�sys�stderr�write)rZtest_resultrrr�)_MonkeyPatchTestResultForUnexpectedPasses\s

r#cseZdZdZdJZd�fdd�Z�fdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
ddd�Zddd�Zddd�Z
�fdd�Zd�fdd�Zdd�Zddd�Zdd d!�Zdd"d#�Zdd$d%�ZdKdd'd(d)�Zdd'd*d+�ZGd,d-�d-e�Zdd.d/�Zdd0d1�Zdd2d3�Zd4d5�Zd6d7�Zd8d9�Zdd:d;�Zd<d=�Z d>d?dd@dA�Z!ddBdC�Z"dDdE�Z#dFdG�Z$�fdHdI�Z%�S)L�TestCasezBExtension of unittest.TestCase providing more powerful assertions.�P��runTestcs#tt|�j|�i|_dS)N)�superr$�__init__�_TestCase__recorded_properties)r�
methodName)�	__class__rrr)|szTestCase.__init__csFt|�}tt|�j�}|dk	rBdj||f�}|S)aqFormat 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.
    N�
)�strr(r$�shortDescriptionr)r�desc�doc_first_line)r,rrr/�s
zTestCase.shortDescriptioncCs*|j|�s&|jd||f�dS)zrAssert that actual.startswith(expected_start) is True.

    Args:
      actual: str
      expected_start: str
    z%r does not start with %rN)�
startswith�fail)r�actualZexpected_startrrr�assertStartsWith�szTestCase.assertStartsWithcCs*|j|�r&|jd||f�dS)zwAssert that actual.startswith(unexpected_start) is False.

    Args:
      actual: str
      unexpected_start: str
    z%r does start with %rN)r2r3)rr4Zunexpected_startrrr�assertNotStartsWith�szTestCase.assertNotStartsWithcCs*|j|�s&|jd||f�dS)zlAssert that actual.endswith(expected_end) is True.

    Args:
      actual: str
      expected_end: str
    z%r does not end with %rN)�endswithr3)rr4Zexpected_endrrr�assertEndsWith�szTestCase.assertEndsWithcCs*|j|�r&|jd||f�dS)zqAssert that actual.endswith(unexpected_end) is False.

    Args:
      actual: str
      unexpected_end: str
    z%r does end with %rN)r7r3)rr4Zunexpected_endrrr�assertNotEndsWith�szTestCase.assertNotEndsWithNcCs%yt|�}Wn'ttfk
r9|g}d}YnXyt|�}Wn5ttfk
r�|jd|t|�f�YnX||ks�td||f��|r�|r�|jdt|�|f�y!|j||d|�|�Wn/tk
r |j|pd||f�YnXdS)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 append on failure.
    rz>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.)r�	TypeError�NotImplementedErrorr3�type�AssertionError�assertSequenceEqual)r�prefixZwhole�msg�
prefix_lenZ	whole_lenrrr�assertSequenceStartsWith�s*		
	!
z!TestCase.assertSequenceStartsWithcCsat|�t|�}|s dSd|||f}|rJ|d|7}n|}|j|�dS)zBChecks whether actual iterable is a superset of expected iterable.Nz+Missing elements %s
Expected: %s
Actual: %sz: %s)�setr3)rZexpected_subsetZ
actual_setr@�missingZmissing_msgrrr�assertContainsSubset�szTestCase.assertContainsSubsetcCsat|�t|�@}|s dSd|||f}|rJ|d|7}n|}|j|�dS)zBChecks whether actual iterable and expected iterable are disjoint.Nz*Common elements %s
Expected: %s
Actual: %sz: %s)rCr3)r�expected_seq�
actual_seqr@�commonZ
common_msgrrr�assertNoCommonElements�szTestCase.assertNoCommonElementscs�tjjdkr;tt|�j|_|j||�dStt|�j}y|dgg�Wnb|jk
r�}z?dt|�kr�|j	|_n	||_|j||�WYdd}~XnXds�t
�dS)alAn unordered sequence specific comparison.

    It asserts that actual_seq and expected_seq have the same element counts.
    Equivalent to::

        self.assertEqual(Counter(iter(actual_seq)),
                         Counter(iter(expected_seq)))

    Asserts that each element has the same count in both sequences.
    Example:
        - [0, 1, 1] and [1, 0, 1] compare equal.
        - [0, 0, 1] and [0, 1] compare unequal.

    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�zFirst has 0, Second has 1:  23z0Impossible: TestCase assertItemsEqual is broken.)r �version_info�majorr(r$�assertCountEqual�assertItemsEqual�failureExceptionr.�_FixedAssertItemsEqualr=)r�args�kwargsZsuper_assert_items_equalZerror_to_introspect)r,rrrOs	#zTestCase.assertItemsEqualcs#tt|�j||d|�dS)z;A version of assertItemsEqual that works around issue14832.r@N)r(r$rO)rrFrGr@)r,rrrQ3szTestCase._FixedAssertItemsEqualcOs|j||�dS)a�An unordered sequence specific comparison.

    Equivalent to assertItemsEqual(). This method is a compatibility layer
    for Python 3k, since 2to3 does not convert assertItemsEqual() calls into
    assertCountEqual() calls.

    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)rO)rrRrSrrrrN7szTestCase.assertCountEqualcsat|t�st|t�r5|jd||f�y|tdd�|D���tdd�|D����fdd��D�}�fdd��D�}|j�|j�WnStk
rt|��t|���j��j�t���\}}YnXg}|r$|jd|�|r;|jd|�|r]|j|pYd	j	|��d
S)a.Assert that two sequences have the same elements (in any order).

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

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

    If possible, you should use assertItemsEqual 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.
    zqPassing a string to assertSameElements is usually a bug. Did you mean to use assertEqual?
Expected: %s
Actual: %scSsg|]}|df�qS)Nr)�.0�elementrrr�
<listcomp>es	z/TestCase.assertSameElements.<locals>.<listcomp>cSsg|]}|df�qS)Nr)rTrUrrrrVfs	cs"g|]}|�kr|�qSrr)rTrU)r4rrrVgs	cs"g|]}|�kr|�qSrr)rTrU)�expectedrrrVhs	zExpected, but missing:
  %r
zUnexpected, but present:
  %r
rN)
�
isinstancer.r3�dict�sortr:�list�_SortedListDifference�appendr)rrFrGr@rD�
unexpectedrr)r4rWr�assertSameElementsGs0	



zTestCase.assertSameElementscCs�t|t�s"td|f��t|t�sDtd|f��||krTdS|ri|dg}n	dg}xUtj|jd�|jd��D]/}|j|�|jd�s�|jd�q�W|jdj	|���dS)z-Assert that two multi-line strings are equal.z"First argument is not a string: %rz#Second argument is not a string: %rNz:
r-Tr)
rXr.r=�difflib�ndiff�
splitlinesr]r7rPr)r�first�secondr@�failure_message�linerrr�assertMultiLineEqual}s	+
zTestCase.assertMultiLineEqualcCsO|dkrd|||f}|j||k|�|j||k|�dS)z8Asserts that value is between minv and maxv (inclusive).Nz+"%r" unexpectedly not between "%r" and "%r")�
assertTrue)rr
ZminvZmaxvr@rrr�
assertBetween�szTestCase.assertBetweencCsrt|t�r|jd�|s/|jd�t|d�}x7|dd�D]%}t|�|k	rP|jd�qPW|tkr�t|t�r�dd�|D�}t}n4|tkr�t|t�r�d	d�|D�}t}|tkrd
dj|�}n3|tkr,dd
j|�d}n
|jd�tj||tj�sn|j|pjd||f�dS)a�Asserts that at least one regex in regexes matches str.

    If possible you should use assertRegexpMatches, which is a simpler
    version of this method. assertRegexpMatches 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 '(.|
)'.

    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.
    z5regexes is a string; use assertRegexpMatches instead.zNo regexes specified.rrNz'regexes list must all be the same type.cSsg|]}|jd��qS)zutf-8)�decode)rT�regexrrrrV�s	z-TestCase.assertRegexMatch.<locals>.<listcomp>cSsg|]}|jd��qS)zutf-8)�encode)rTrkrrrrV�s	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.)	rXr.r3r<�bytesr�re�search�	MULTILINE)rZ
actual_str�regexes�messageZ
regex_typerkrrr�assertRegexMatch�s,"

	
zTestCase.assertRegexMatch�Tc	Cs�t|||�\}}t|dt�r>dd�|D�}t|�}|j|ddt|�|t|�f�|j||ddt|�|t|�|f�dS)alAsserts 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.
      close_fds: Whether or not to close all open fd's in the child after
        forking.
    rcSsg|]}|jd��qS)zutf-8)rl)rTrkrrrrV�s	z2TestCase.assertCommandSucceeds.<locals>.<listcomp>z;Running command
%s failed with error code %s and message
%srszXRunning command
%s failed with error code %s and message
%s which matches no regex in %sN)�GetCommandStderrrXr.�GetCommandString�assertEqual�_QuoteLongStringrt)r�commandrr�env�	close_fds�ret_code�err�command_stringrrr�assertCommandSucceeds�s$			zTestCase.assertCommandSucceedsc	Cs�t|||�\}}t|dt�r>dd�|D�}t|�}|j|ddt|��|j||ddt|�|t|�|f�dS)a_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.
      close_fds: Whether or not to close all open fd's in the child after
        forking.
    rcSsg|]}|jd��qS)zutf-8)rl)rTrkrrrrVs	z/TestCase.assertCommandFails.<locals>.<listcomp>z:The following command succeeded while expected to fail:
%srszXRunning command
%s failed with error code %s and message
%s which matches no regex in %sN)rvrXr.rw�assertNotEqualryrt)rrzrrr{r|r}r~rrrr�assertCommandFails�s 
		zTestCase.assertCommandFailsc@s4eZdZdd�Zdd�Zdd�ZdS)zTestCase._AssertRaisesContextcCs||_||_||_dS)N)�expected_exception�	test_case�	test_func)rr�r�r�rrrr) s		z&TestCase._AssertRaisesContext.__init__cCs|S)Nr)rrrr�	__enter__%sz'TestCase._AssertRaisesContext.__enter__cCsM|dkr&|jj|jjd�t||j�s<dS|j|�dS)Nz not raisedFT)r�r3r��__name__�
issubclassr�)r�exc_type�	exc_value�tbrrr�__exit__(s
z&TestCase._AssertRaisesContext.__exit__N)r��
__module__�__qualname__r)r�r�rrrr�_AssertRaisesContextsr�c
sY��fdd�}�j|�|�}|dkr:|S|�|||�WdQRXdS)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 macthing exception.
    cs$�j�|�d|�f�dS)Nz%r does not match predicate %r)rh)r~)�	predicaterrr�CheckDsz6TestCase.assertRaisesWithPredicateMatch.<locals>.CheckN)r�)rr�r��callable_objrRrSr��contextr)r�rr�assertRaisesWithPredicateMatch0sz'TestCase.assertRaisesWithPredicateMatchc
sY��fdd�}�j|�|�}|dkr:|S|�|||�WdQRXdS)a#Asserts that the message in a raised exception equals the given string.

    Unlike assertRaisesRegexp, 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 macthing exception.
    cs0t|�}�j�|kd�|f�dS)Nz9Exception message does not match.
Expected: %r
Actual: %r)r.rh)r~Zactual_exception_message)�expected_exception_messagerrrr�js
z4TestCase.assertRaisesWithLiteralMatch.<locals>.CheckN)r�)rr�r�r�rRrSr�r�r)r�rr�assertRaisesWithLiteralMatchNsz%TestCase.assertRaisesWithLiteralMatchcOs|j|||||�S)a�Asserts that the message in a raised exception matches the given regexp.

    This is just a wrapper around assertRaisesRegexp. Please use
    assertRaisesRegexp instead of assertRaisesWithRegexpMatch.

    Args:
      expected_exception: Exception class expected to be raised.
      expected_regexp: Regexp (re pattern object or string) expected to be
        found in error message.
      callable_obj: Function to be called, or None to return a context.
      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 macthing exception.
    )�assertRaisesRegex)rr�Zexpected_regexpr�rRrSrrr�assertRaisesWithRegexpMatchxsz$TestCase.assertRaisesWithRegexpMatchcCs�t|t�s|g}d}d}x�|D]�}|jt|�|�}|dkr{|dkr{|jd||f�n&|dkr�|jd|||f�|}|}q+WdS)a@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'.
    rNrzDid not find '%s' in '%s'z$Did not find '%s' after '%s' in '%s'���r�)rXr[�findr.r3)r�strings�targetZ
current_indexZlast_string�string�indexrrr�assertContainsInOrder�s
	
		zTestCase.assertContainsInOrdercCs�d}tt|��}t|�}x:|D]2}||krD|}Px||j�kr\qGWq+W|dk	r�|jd|||f�dS)a�Assert that "container" contains "subsequence" as a subsequence.

    Asserts that big_list contains all the elements of small_list, 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.
    Nz:%s not a subsequence of %s. First non-matching element: %s)r[�reversed�popr3)r�	containerZsubsequenceZfirst_nonmatchingZreversed_container�errr�assertContainsSubsequence�s
	z"TestCase.assertContainsSubsequencecs�fdd�}�fdd�}xvtj|�D]e}t|�}xPt|dd��D]8\}}x)||dd�D]}|||�q~Wq]Wq4Wx\|D]T}x|D]}	||	|	�q�Wx-tj||�D]\}	}
||	|
�q�Wq�WdS)a�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 = xio
        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].
    cs�j||kd||f��j||kd||f��j||��j||kd||f��j||��j||kd||f��j||��j||kd||f��j||��j||kd||f�dS)z$Ensures small is ordered before big.z%r unexpectedly equals %rz%r unexpectedly less than %rz(%r unexpectedly less than or equal to %rz%r unexpectedly greater than %rz+%r unexpectedly greater than or equal to %rN)�assertFalserh�
assertLess�assertLessEqual�
assertGreater�assertGreaterEqual)�small�big)rrr�
CheckOrder�s$z1TestCase.assertTotallyOrdered.<locals>.CheckOrdercs/�j||��j||kd||f��jt|�t|�dt|�|t|�|f��j||kd||f��j||kd||f��j||��j||��j||kd||f��j||kd||f��j||��j||�dS)zEnsures that a and b are equal.z%r unexpectedly equals %rz5hash %d of %r unexpectedly not equal to hash %d of %rz%r unexpectedly less than %rz%r unexpectedly greater than %rN)rxr��hashr�r�)�a�b)rrr�
CheckEquals      z1TestCase.assertTotallyOrdered.<locals>.CheckEqualNrr�)�	itertools�productr[�	enumerate)r�groupsr�r��elementsr�r�r��groupr�r�r)rr�assertTotallyOrdered�s)#

zTestCase.assertTotallyOrderedcs"|j|td�|j|td�dd�}||krBdS|t|j���}|t|j���}g}g}g}	tjj��fdd�}
d|
|�|
|�|r�d	|nd
fg}x`|D]X\}}
||kr	|j||
f�q�|
||kr�|	j||
||f�q�Wx3|D]+\}}||kr>|j||f�q>W|r�|jdd
j�fdd
�|D���|	r�|jdd
j�fdd
�|	D���|r|jdd
j�fdd
�|D���|j	dj|���dS)aRaises 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 dictionarycSs+yt|�SWntk
r&|SYnXdS)N)�sortedr:)Z
list_of_itemsrrr�Sorted2s
z(TestCase.assertDictEqual.<locals>.SortedNcsCt�fdd�|j�D��}ddjdd�|D��S)zDeterministic repr for dict.c3s-|]#\}}�|��|�fVqdS)Nr)rT�k�v)�	safe_reprrr�	<genexpr>Gsz9TestCase.assertDictEqual.<locals>.Repr.<locals>.<genexpr>z{%s}z, css|]}d|VqdS)z%s: %sNr)rT�pairrrrr�Is)r��itemsr)Zdikt�entries)r�rr�ReprCsz&TestCase.assertDictEqual.<locals>.Reprz
%s != %s%sz (%s)rz#Unexpected, but present entries:
%sc3s1|]'\}}d�|��|�fVqdS)z%s: %s
Nr)rTr�r�)r�rrr�\sz+TestCase.assertDictEqual.<locals>.<genexpr>zrepr() of differing entries:
%sc3s=|]3\}}}d�|��|��|�fVqdS)z
%s: %s != %s
Nr)rTr��a_value�b_value)r�rrr�aszMissing entries:
%sc3s1|]'\}}d�|��|�fVqdS)z%s: %s
Nr)rTr�r�)r�rrr�hsr-)
�assertIsInstancerYr[r�r�utilr�r]rrP)rr�r�r@r�Za_itemsZb_itemsr^rDZ	differentr�rsZa_keyr�Zb_keyr�r)r�r�assertDictEqual$sF2			zTestCase.assertDictEqualcCs�tjj|�}tjj|�}|j|j|j�|j|j|j�|j|j|j�|j|j|j�|jt|j	j
d��t|j	j
d���|jtjj|j
dd�tjj|j
dd��dS)z?Asserts that urls are equal, ignoring ordering of query params.�;�keep_blank_valuesTN)�urllib�parse�urlparserx�scheme�netlocr�fragmentr��params�splitr��parse_qs�query)rr�r�Zparsed_aZparsed_brrr�assertUrlEquallszTestCase.assertUrlEqualr�r�c	Cs�g}t|||||�|jd}t|�|krV|d|d�dg}|r�dj|�}|r|d|7}|j|�dS)aAsserts 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.

    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.
    r%rrz...z; z: N)�_WalkStructureForProblems�maxDiffrrr3)	rr�r��aname�bnamer@ZproblemsZmax_problems_to_showrerrr�assertSameStructurezs
zTestCase.assertSameStructurec%Cs�ytj|�}Wn;tk
rP}ztd||f��WYdd}~XnXytj|�}Wn;tk
r�}ztd||f��WYdd}~XnX|j||ddddd|�dS)	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 contining JSON to decode and compare to second.
      second: A string contining 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: %sr�rcr�rdr@)�json�loadsr	r�)rrcrdr@Zfirst_structuredr�Zsecond_structuredrrr�assertJsonEqual�s##zTestCase.assertJsonEqualcCs|jS)z1Return any properties that the user has recorded.)r*)rrrr�getRecordedProperties�szTestCase.getRecordedPropertiescCs||j|<dS)z�Record an arbitrary property for later use.

    Args:
      property_name: str, name of property to record; must be a valid XML
        attribute name
      property_value: value of property; must be valid XML attribute value
    N)r*)rZ
property_nameZproperty_valuerrr�recordProperty�szTestCase.recordPropertycssytt|�j||�SWn:tk
rYt|dd�}tt|�j|�YnXtt|�j||�S)N�_testMethodNamerh)r(r$�_getAssertEqualityFunc�AttributeError�getattrr))rrcrdZtest_method)r,rrr��s
zTestCase._getAssertEqualityFunci@)ru)&r�r�r��__doc__r�r)r/r5r6r8r9rBrErIrOrQrNr_rgrirtr�r��objectr�r�r�r�r�r�r�r�r�r�r�r�r�r�rr)r,rr$wsF



(+6>&")]H#
r$cCsod}}g}g}xLy||}||}||krw|j|�|d7}x�|||krs|d7}qVWn�||kr�|j|�|d7}x|||kr�|d7}q�Wn^|d7}z%x|||kr�|d7}q�WWd|d7}x|||kr|d7}q�WXWqtk
r`|j||d��|j||d��PYqXqW||fS)aNFinds 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 actualy got.
  Returns:
    (missing, unexpected)
    missing: items in expected that are not in actual.
    unexpected: items in actual that are not in expected.
  rrN)r]�
IndexError�extend)rWr4�i�jrDr^r�r�rrrr\�s:










r\c@sReZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�CapturedStreamz'A temporarily redirected output stream.cCs�||_|j�|_||_tj|j�|_tj|jtjtj	Btj
Bd�}|jj�tj||j�tj
|�dS)Ni�)�_stream�fileno�_fd�	_filenamer�dup�_uncaptured_fd�open�O_CREAT�O_TRUNC�O_WRONLY�flush�dup2�close)r�stream�filename�cap_fdrrrr)s			
zCapturedStream.__init__cCsi|jst�tj|jtjtjBtjBd�}|jj	�tj
||j�tj|�dS)z>Resume capturing output to a file (after calling StopCapture).i�N)
r�r=rr�r�r��O_APPENDr�r�r�r�r�r�)rr�rrr�RestartCapture-s	
zCapturedStream.RestartCapturecCs'|jj�tj|j|j�dS)zRemove output redirection.N)r�r�rr�r�r�)rrrr�StopCapture<s
zCapturedStream.StopCapturecCs|jS)N)r�)rrrrr�AszCapturedStream.filenamecCs$|j�tj|j�|`dS)N)r�rr�r�)rrrr�__del__Ds
zCapturedStream.__del__N)	r�r�r�r�r)r�r�r�r�rrrrr�sr�cCs)|tkst�t||�t|<dS)z�Redirect an output stream to a file.

  Args:
    stream: Should be sys.stdout or sys.stderr.
    filename: File where output should be stored.
  N)�_captured_streamsr=r�)r�r�rrr�_CaptureTestOutputMsr�cCs7|tkst�xtj�D]}|j�qWdS)zdStops capturing the given output stream.

  Args:
    stream: Should be sys.stdout or sys.stderr.
  N)r�r=�valuesr�)r��
cap_streamrrr�_StopCapturingStreamXsrcCs[t|�t|}zt|j�|�Wdt|=xtj�D]}|j�qBWXdS)z�Compare ouput of redirected stream to contents of golden file.

  Args:
    stream: Should be sys.stdout or sys.stderr.
    golden_filename: Absolute path to golden file.
  N)rr��_Diffr�r�r�)r�Zgolden_filenameZcaprrrr�_DiffTestOutputcs

rcCs*t|kr&|atjjd|�dS)Nz,
NOTE: Some tests capturing output into: %s
)�_notified_test_output_pathr r!r")�outdirrrr�_MaybeNotifyAboutTestOutput|src@s4eZdZdd�Zdd�Zdd�ZdS)�_DiffingTestOutputContextcCs
||_dS)N)�_diff_fn)rZdiff_fnrrrr)�sz"_DiffingTestOutputContext.__init__cCs|S)Nr)rrrrr��sz#_DiffingTestOutputContext.__enter__cCs|j�dS)NT)r)rr�r�r�rrrr��s
z"_DiffingTestOutputContext.__exit__N)r�r�r�r)r�r�rrrrr�srcs||s*tjjtjd�}tj}ntjj|�}t|�ttj	|��dk	rxt
�fdd��SdS)aLCapture the stdout stream to a file.

  If expected_output_filepath, then this function returns a context manager
  that stops capturing and performs a diff when the context is exited.

    with basetest.CaptureTestStdout(expected_output_filepath=some_filepath):
      sys.stdout.print(....)

  Otherwise, StopCapturing() must be called to stop capturing stdout, and then
  DiffTestStdout() must be called to do the comparison.

  Args:
    outfile: The path to the local filesystem file to which to capture output;
        if omitted, a standard filepath in --test_tmpdir will be used.
    expected_output_filepath: The path to the local filesystem file containing
        the expected output to be diffed against when the context is exited.
  Returns:
    A context manager if expected_output_filepath is specified, otherwise
        None.
  zcaptured.outNcs
t��S)N)�DiffTestStdoutr)�expected_output_filepathrr�<lambda>�sz#CaptureTestStdout.<locals>.<lambda>)rrr�FLAGSr�dirnamerr�r �stdoutr)�outfiler
rr)r
r�CaptureTestStdout�s
rcs||s*tjjtjd�}tj}ntjj|�}t|�ttj	|��dk	rxt
�fdd��SdS)aMCapture the stderr stream to a file.

  If expected_output_filepath, then this function returns a context manager
  that stops capturing and performs a diff when the context is exited.

    with basetest.CaptureTestStderr(expected_output_filepath=some_filepath):
      sys.stderr.print(....)

  Otherwise, StopCapturing() must be called to stop capturing stderr, and then
  DiffTestStderr() must be called to do the comparison.

  Args:
    outfile: The path to the local filesystem file to which to capture output;
        if omitted, a standard filepath in --test_tmpdir will be used.
    expected_output_filepath: The path to the local filesystem file containing
        the expected output, to be diffed against when the context is exited.
  Returns:
    A context manager if expected_output_filepath is specified, otherwise
        None.
  zcaptured.errNcs
t��S)N)�DiffTestStderrr)r
rrr�sz#CaptureTestStderr.<locals>.<lambda>)rrrrrr
rr�r r!r)rr
rr)r
r�CaptureTestStderr�s
rcCsttj|�dS)N)rr r)�goldenrrrr	�sr	cCsttj|�dS)N)rr r!)rrrrr�srcCs0x)tr+tj�\}}|j�~qWdS)zAStop capturing redirected output.  Debugging sucks if you forget!N)r��popitemr�)�_rrrr�
StopCapturing�s	
rcCsktj|tjtjBtjBd�}t|ttf�sJ|jd�}tj	||�tj
|�dS)z$Write data into file named filename.i�zutf-8N)rr�r�r�r�rXrn�	bytearrayrlr"r�)�datar��fdrrr�_WriteTestData�s
&rcCsFt|�t|�krdt|t�o3t|t�rd|jd|t|�|t|�f�dSt|tj�rxi|D]a}||kr�t||||d||fd||f|�q}|jd|||f�q}Wx]|D],}||kr�|jd|||f�q�Wn&t|tj�rt|t�rt	t
|�t
|��}xFt|�D]8}t||||d||fd||f|�qfWx7t|t
|��D] }|jd|||f�q�Wxct|t
|��D] }|jd|||f�q�Wn)||krB|jd	||||f�dS)
z4The recursive comparison behind assertSameStructure.z%s is a %r but %s is a %rNz%s[%r]z%s has [%r] but %s does notz%s lacks [%r] but %s has itz%s[%d]z%s has [%i] but %s does notz%s lacks [%i] but %s has itz%s is %r but %s is %r)r<rX�
_INT_TYPESr]�collections�Mappingr��Sequencer.�minr�range)r�r�r�r�Zproblem_listr�Zminlenr�rrrr��s6	 


!"!r�c@seZdZdS)�OutputDifferedErrorN)r�r�r�rrrrr!sr!c@seZdZdS)�DiffFailureErrorN)r�r�r�rrrrr"sr"cCs�|||g}y$tj|dddtj�dSWn�tjk
r�}z3|j}|jdkrytd||f��WYdd}~Xn1tk
r�}zt|�}WYdd}~XnXt	d||f��dS)zGCompare two files using an external program; raise if it reports error.r|Tr!rz5
Running %s
%s
Test output differed from golden file
Nz<
Running %s
%s
Failure diffing test output with golden file
)
�
subprocess�check_output�STDOUT�CalledProcessError�output�
returncoder!�EnvironmentErrorr.r")�lhs�rhs�
external_diffrz�errorZfailure_outputrrr�_DiffViaExternalPrograms	"r.cCs�tjjd�}|r(t|||�Sy�t|d��G}t|d��.}djtj|j�|j���}WdQRXWdQRX|s�dSt	d|||f��Wn>t
k
r�}ztd|||f��WYdd}~XnXdS)z>Given two pathnames, compare two files.  Raise if they differ.Z	TEST_DIFF�rrNTz>
Comparing %s and %s
Test output differed from golden file:
%szF
Comparing %s and %s
Failure diffing test output with golden file: %s
)rrrr.r�rr`�unified_diff�	readlinesr!r)r")r*r+r,Zlhs_fZrhs_f�	diff_textr-rrrr5s/rcCs6tjjtjd�}t||�t||�dS)zDiff data agains a golden file.zprovided.datN)rrrrrrr)rrZ	data_filerrr�DiffTestStringFileKs
r3cCsKdjtj|jd�|jd���}|s7dStd|��dS)zDiff two strings.rTNz
Test strings differed:
%s)rr`r0rbr!)Zdata1Zdata2r2rrr�DiffTestStringsRs
'r4cCst||�dS)N)r)Ztestgenrrrr�
DiffTestFiles[sr5cCs$t|t�r|Stj|�SdS)z�Returns 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.
  N)rXr.rZShellEscapeList)rzrrrrw_srwTcCs�|dkri}tjjd�rE|jd�rEtjd|d<t|t�}tj|d|d|d|dtjdtj�}|j	�d}|j
�}||fS)	a[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.
    close_fds: Whether or not to close all open fd's in the child after forking.

  Returns:
    Tuple of (exit status, text printed to stdout and stderr by the command).
  NZPYTHON_RUNFILESr|r{�shellr!rr)rrrrXr.r#�Popenr%�PIPE�communicate�wait)rzr{r|Z	use_shell�processr'�exit_statusrrrrvms"	rvcCsYt|ttf�rIy|jd�}Wntk
rHt|�}YnXd|ddS)z�Quotes a potentially multi-line string to make the start and end obvious.

  Args:
    s: A string.

  Returns:
    The quoted string.
  zutf-8z8<-----------
r-z----------->8
)rXrnrrj�UnicodeDecodeErrorr.)�srrrry�s	
ryc@s%eZdZdZddd�ZdS)�TestProgramManualRunz,A TestProgram which runs the tests manually.FcCs|rtjj|�dS)zRun the tests.N)r�TestProgram�runTests)rZdo_runrrrrA�szTestProgramManualRun.runTestsN)r�r�r�r�rArrrrr?�sr?cOstt||�dS)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)�	_RunInApp�RunTests)rRrSrrr�main�srDcCsWtj�j}tj}x8|rR|j|krF|jjdkrFdS|j}qWdS)z8Returns True iff app.main or app.really_start is active.�run�really_startTF)rErF)r �	_getframe�f_backr�__dict__�	f_globals�f_code�co_name)�fZapp_dictrrr�_IsInAppMain�s		!
rNc@s.eZdZdZdd�Zdd�ZdS)�	SavedFlagz3Helper class for saving and restoring a flag value.cCs%||_|j|_|j|_dS)N)�flagr
�present)rrPrrrr)�s	zSavedFlag.__init__cCs"|j|j_|j|j_dS)N)r
rPrQ)rrrr�RestoreFlag�szSavedFlag.RestoreFlagN)r�r�r�r�r)rRrrrrrO�srOcs5tr`ytj�Wn9tk
rO}ztjjd|�WYdd}~XnXtjtj�t	�r�t
dd�tj�j
�D��}d|kr�dt_|d=ttj�}x|j
�D]}|j�q�W�|���nDdtkr	tjdd����fdd�}tjd	|�dS)
a�Executes a set of Python unit tests, ensuring app.really_start.

  Most users should call basetest.main() instead of _RunInApp.

  _RunInApp 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() or app.really_start(). _RunInApp does this
  by checking whether it is called by either app.run() or
  app.really_start(), or by calling app.really_start() explicitly.

  The reason why app.really_start 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 basetest.run() is called
  from within or outside app.run().

  If _RunInApp 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 basetest.main() without passing its argv. So the
  only way _RunInApp could get to know the argv without the flags is that
  it reparses sys.argv.

  _RunInApp 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 _RunInApp()
  (e.g. in __main__.main).

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

  Args:
    function: basetest.RunTests 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__.
  z+faulthandler.enable() failed %r; ignoring.
Ncss$|]}|jt|�fVqdS)N)�namerO)rTrMrrrr�sz_RunInApp.<locals>.<genexpr>�alsologtostderrTcs�|���dS)Nr)�argv)rR�functionrSrr�Main7sz_RunInApp.<locals>.MainrD)�faulthandler�enable�	Exceptionr r!r"�register�signal�SIGTERMrNrYrZFlagDictr�rTrUrRZ
SetDefaultrrF)rVrRrSr�Zsaved_flagsrUZ
saved_flagrWr)rRrVrSrrB�s(('		rBcCs|jd�}tjjtj�s4tjtj�tjd}t	|d�rit
|j�ri|j�|jd|�zXd}t
||�}|r�||_ntjd|j�|_|jj|j�}Wdt	|d�r�t
|j�r�|j�Xtj|j��dS)a�Executes a set of Python unit tests within app.really_start.

  Most users should call basetest.main() instead of RunTests.

  Please note that RunTests should be called from app.really_start (which is
  called from app.run()). Calling basetest.main() would ensure that.

  Please note that RunTests 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 app.run() has called __main__.main.
    args: Positional arguments passed through to unittest.TestProgram.__init__.
    kwargs: Keyword arguments passed through to unittest.TestProgram.__init__.
  �
testRunner�__main__�setUprUN�	verbosity�tearDown)rrr�isdirrr�makedirsr �modules�hasattr�callabler`�
setdefaultr?r^r�TextTestRunnerrarErrb�exitr)rUrRrS�test_runnerZmain_modrZtest_programrrrrC=s$

	rC)Gr��
__author__rr`Zgetpassr�r�rror\r#r r�typesr�urllib.parser�rX�ImportError�google.apputilsrZgflags�flagsrrr
rZDEFINE_integerZ
DEFINE_stringrrr#r$r\r�r�r�r�rrrrrrrr	rrrrrr�r=r!rZr"r.rr3r4r5rwrvryr@r?rDrNrOrBrCrrrr�<module>s�
	
		���cA2!!	(		i