
                            S r SrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKr\	R                  S:  a  SSKrOSSKrSSKJr  SSKrSSKJr  \R(                  rS rS r\R.                  " S	\" 5       S
SS9  \R0                  " S\R2                  R5                  SS5      SSS9  \R0                  " S\" 5       SSS9   " S S\5      r " S S\R:                  5      rS r " S S\5      r 0 r!S r"S r#S5S jr$S5S jr%S r&S r'S  r(S! r) " S" S#\*5      r+ " S$ S%\,5      r-S& r.S' r/S( r0S) r1S* r2S6S+ jr3S, r4 " S- S.\Rj                  5      r6S/ r7S0 r8 " S1 S2\5      r9S3 r:S4 r;g)7zyBase 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)	shellutilc                      Sn [         R                  R                  SS5      n [        U5      n U $ ! [         a     U $ f = f)Ni-  TEST_RANDOM_SEED )osenvirongetint
ValueError)random_seedvalues     3platform/bq/third_party/google/apputils/basetest.py_GetDefaultTestRandomSeedr   5   sL    +
**..+R
0%	e*K 
 
 			s   1 
??c                      [         R                  R                  SS5      n U (       d3  [         R                  R	                  [
        R                  " 5       S5      n U $ )NTEST_TMPDIRr	   google_apputils_basetest)r
   r   r   pathjointempfile
gettempdir)tmpdirs    r   _GetDefaultTestTmpdirr   ?   s<    ::>>-,&	WW\\(--/1KLF	-    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.   )allow_overridetest_srcdirTEST_SRCDIRr	   z.Root of directory tree where source files livetest_tmpdirz%Directory for temporary testing filesc                      ^  \ rS rSrSr\R                  rU 4S jr\	S 5       r
\	S 5       r\	S 5       r\	S 5       r\	S 5       rS	rU =r$ )
BeforeAfterTestCaseMetaU   a  Adds setUpTestCase() and tearDownTestCase() methods.

These may be needed for setup and teardown of shared fixtures usually because
such fixtures are expensive to setup and teardown (eg Perforce clients).  When
using such fixtures, care should be taken to keep each test as independent as
possible (eg via the use of sandboxes).

Example:

  class MyTestCase(basetest.TestCase):

    __metaclass__ = basetest.BeforeAfterTestCaseMeta

    @classmethod
    def setUpTestCase(cls):
      cls._resource = foo.ReallyExpensiveResource()

    @classmethod
    def tearDownTestCase(cls):
      cls._resource.Destroy()

    def testSomething(self):
      self._resource.Something()
      ...
c                 *  > [         [        U ]  XU5        [        U R                  R                  U 5      5      nS U l        [        R                  X5        [        R                  U 5        [        R                  X5        [        R                  5         g N)superr$   __init__set_test_loadergetTestCaseNames&_BeforeAfterTestCaseMeta__tests_to_runSetSetUpAttrSetTearDownAttrSetTestMethodAttrsSetBeforeAfterTestCaseAttr)clsnamebasesdict
test_names	__class__s        r   r)    BeforeAfterTestCaseMeta.__init__s   st    	
!30dC: S%%66s;<J C ((9++C0..s?668r   c                     [        X5      nUR                  Ul        UR                  Ul        UR                  Ul        [	        XU5        g)z@Like setattr, but also preserves name, doc, and module metadata.N)getattr__name____doc__
__module__setattr)r2   method_namereplacementoriginals       r   	SetMethod!BeforeAfterTestCaseMeta.SetMethod   sB     s(H#,,K"**K%00KCk*r   c                 \   ^^ U R                   mUU4S jn[        R                  U SU5        g)z3Wraps setUp() with per-class setUp() functionality.c                    > U R                   nUR                  c   [        T5      Ul        U R                  5         T" U 5        g)z7Function that will encapsulate and replace cls.setUp().N)r7   r-   r*   setUpTestCase)selfleaf	cls_setUpr6   s     r   setUp3BeforeAfterTestCaseMeta.SetSetUpAttr.<locals>.setUp   s;     ^^d. 
			$!*oor   rJ   N)rJ   r$   rB   )r2   r6   rJ   rI   s    ` @r   r.   $BeforeAfterTestCaseMeta.SetSetUpAttr   s(     		I
"J %%c7E:r   c                 \   ^ ^ T R                   mU U4S jn[        R                  T SU5        g)z9Wraps tearDown() with per-class tearDown() functionality.c                    > T" U 5        U R                   nUR                  b1  UR                  (       d  UT:X  a  SUl        U R                  5         gggg)z:Function that will encapsulate and replace cls.tearDown().N)r7   r-   tearDownTestCase)rG   rH   r2   cls_tearDowns     r   tearDown9BeforeAfterTestCaseMeta.SetTearDownAttr.<locals>.tearDown   sU    4^^d 


)%%ck"  & *r   rQ   N)rQ   r$   rB   )r2   rQ   rP   s   ` @r   r/   'BeforeAfterTestCaseMeta.SetTearDownAttr   s'     <<L  %%c:x@r   c                 d    U H*  n[        X5      nX24S jn[        R                  XU5        M,     g)zBMakes each test method first remove itself from the remaining set.c                 `    U R                   nUR                  R                  U5        U" U 5      $ r'   )r7   r-   discard)rG   cls_test	test_namerH   s       r   test8BeforeAfterTestCaseMeta.SetTestMethodAttrs.<locals>.test  s)    ~~##I.~r   N)r:   r$   rB   )r2   r6   rX   rW   rY   s        r   r0   *BeforeAfterTestCaseMeta.SetTestMethodAttrs   s4    $  	(h ' 
 ''=  r   c                  4    S [         l        S [         l        g )Nc                     g r'    rG   s    r   <lambda>DBeforeAfterTestCaseMeta.SetBeforeAfterTestCaseAttr.<locals>.<lambda>  s    $r   c                     g r'   r^   r_   s    r   r`   ra     s    Tr   )TestCaserF   rO   r^   r   r   r1   2BeforeAfterTestCaseMeta.SetBeforeAfterTestCaseAttr  s    
 /H 1Hr   r^   )r;   r=   __qualname____firstlineno__r<   unittestdefaultTestLoaderr+   r)   staticmethodrB   r.   r/   r0   r1   __static_attributes____classcell__r7   s   @r   r$   r$   U   s    4 ++,+9\ + + 2; 2;h A A0 > >@ 2 2r   r$   c                      ^  \ rS rSrSrSrSU 4S jjrU 4S jrSS jrSS jr	SS	 jr
SS
 jrSS jrSS jrS/SS4S jrSS jrS rS rS rS rS rS rS rU 4S jrSrU =r$ )rc   i"  zBExtension of unittest.TestCase providing more powerful assertions.i@  c                 :   > [         [        U ]  U5        0 U l        g r'   )r(   rc   r)   _TestCase__recorded_properties)rG   
methodNamer7   s     r   r)   TestCase.__init__'  s    	(D":.!#Dr   c                 l   > [        U 5      n[        [        U ]  5       nUb  SR	                  X45      nU$ )aU  Format 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.

)strr(   rc   shortDescriptionr   )rG   descdoc_first_liner7   s      r   ru   TestCase.shortDescription+  s;     t9D 8T;=N!YY-.dKr   Nc           	          [        U5      n [        U5      nUW::  d   SXE4-  5       eU(       d&  U(       a  U R                  S[        U5      U4-  5         U R                  XSU U5        g! [        [        4 a    U/nSn Nxf = f! [        [        4 a%    U R                  SU< S[	        U5      < 35         Nf = f! [         a&    U R                  U=(       d    SU< SU< S	35         gf = f)
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.
r   zFor whole: len(z+) is not supported, it appears to be type: z4Prefix length (%d) is longer than whole length (%d).z-Prefix length is 0 but whole length is %d: %sNzprefix: z not found at start of whole: .)len	TypeErrorNotImplementedErrorfailtypeassertSequenceEqualAssertionError)rG   prefixwholemsg
prefix_len	whole_lens         r   assertSequenceStartsWith!TestCase.assertSequenceStartsWithC  s   v;j
-e*i
 " !>		 !" )
ii?UU#$ %!
v[j'93?' *+ xfj *+ -
iitE{, --  !
ii      !!s4   A. B	 C .BB	2B>=B>-C10C1c                     [        U5      [        U5      -
  nU(       d  gSU< SU< SU< 3nU(       a	  USU-  -  nOUnU R                  U5        g)zBChecks whether actual iterable is a superset of expected iterable.NzMissing elements z
Expected: 	
Actual: z: %s)r*   r~   )rG   expected_subset
actual_setr   missingmissing_msgs         r   assertContainsSubsetTestCase.assertContainsSubsetk  sR    /"S_4G  	*.K
	Vk!!ccIIcNr   c                     [        U Vs/ s H  oDS4PM     sn5      n[        U Vs/ s H  oDS4PM     sn5      nU Vs/ s H  oDU;  d  M
  UPM     nnU Vs/ s H  oDU;  d  M
  UPM     nnUR                  5         UR                  5         / n	U(       a  U	R                  SU-  5        U(       a  U	R                  SU-  5        U	(       a*  U R                  U=(       d    SR                  U	5      5        ggs  snf s  snf s  snf s  snf ! [         aF    [        U5      n[        U5      nUR                  5         UR                  5         [	        XV5      u  px Nf = f)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.
NzExpected, but missing:
  %r
zUnexpected, but present:
  %r
r	   )r5   sortr|   list_SortedListDifferenceappendr~   r   )
rG   expected_seq
actual_seqr   elementexpectedactualr   
unexpectederrorss
             r   assertSameElementsTestCase.assertSameElementsy  s.   *DlCl7lCDhJ?Jt_J?@f(0JW64IgJ+1M6H5LG6jMllnoo Fmm4w>?mm6CD
ii&rwwv' ' D?JM  D l#hJfmmokkm1(CgzDsP   	D C8D C=D  	DDD 	D&D,"D 8D AEEc                    [        U[        R                  5      (       d   SU< 35       e[        U[        R                  5      (       d   SU< 35       eX:X  a  gU(       a  U R                  U5      eS/n[        R
                  " UR                  S5      UR                  S5      5       H=  nUR                  U5        UR                  S5      (       a  M,  UR                  S5        M?     U R                  SR                  U5      5      e)z-Assert that two multi-line strings are equal.z First argument is not a string: z!Second argument is not a string: Nrs   Tr	   )

isinstancetypesStringTypesfailureExceptiondifflibndiff
splitlinesr   endswithr   )rG   firstsecondr   failure_messagelines         r   assertMultiLineEqualTestCase.assertMultiLineEqual  s    eU..// 90579/fe//00 ;179;0 
!!#&&fOe..t4f6G6G6MNT"]]4  t$ O 

 8
99r   c                 x    Uc  SU< SU< SU< S3nU R                  X!:*  U5        U R                  X1:  U5        g)z8Asserts that value is between minv and maxv (inclusive).N"z" unexpectedly not between "z" and ")assert_)rG   r   minvmaxvr   s        r   assertBetweenTestCase.assertBetween  s3    
{=BD$OcLL$LL$r   c                 D   [        U[        5      (       a  U R                  S5        U(       d  U R                  S5        SSR                  U5      -  n[        R
                  " XA[        R                  5      (       d$  U R                  U=(       d    SU< SU< S35        gg)	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.
    z6regexes is a string; it needs to be a list of strings.zNo regexes specified.z(?:%s)z)|(?:zString "z)" does not contain any of these regexes: rz   N)r   
basestringr~   r   research	MULTILINE)rG   
actual_strregexesmessageregexs        r   assertRegexMatchTestCase.assertRegexMatch  s    @ ':&&
iiHI
ii'(w||G,,E99U55
ii D D.8'C E 6r   r	   Tc                    [        XU5      u  pV[        U5      nU R                  US:H  S[        U5      < SU< S[        U5      < 35        U R	                  UUS[        U5      < SU< S[        U5      < SU< 3S9  g)a8  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 strings.
  env: Dictionary of environment variable settings.
  close_fds: Whether or not to close all open fd's in the child after
    forking.
r   Running command
 failed with error code  and message
 which matches no regex in r   NGetCommandStderrGetCommandStringr   _QuoteLongStringr   rG   commandr   env	close_fdsret_codeerrcommand_strings           r   assertCommandSucceedsTestCase.assertCommandSucceeds  s     'wY?OX%g.NLLA ^,S!	#$ 	
 !0 %	  
r   c                     [        XU5      u  pV[        U5      nU R                  US:g  S[        U5      -  5        U R	                  UUS[        U5      < SU< S[        U5      < SU< 3S9  g)	aC  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.
r   z:The following command succeeded while expected to fail:
%sr   r   r   r   r   Nr   r   s           r   assertCommandFailsTestCase.assertCommandFails  sw     'wY?OX%g.NLLAE(	)* 	
 !0 %	  
r   c                      U" U0 UD6  U R                  UR                  S-   5        g! U a)  nU R                  U" U5      U< SU< 35         SnAgSnAff = f)al  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.
 not raisedz does not match predicate N)r~   r;   r   )rG   expected_exception	predicatecallable_objargskwargsr   s          r   assertRaisesWithPredicateMatch'TestCase.assertRaisesWithPredicateMatch+  sc    =D#F#
 ii"++m;<	  H
ll9S>7:IFH HHs   ) AAAc                      U" U0 UD6  U R                  UR                  S-   5        g! U a1  n[        U5      nU R                  X':H  SU< SU< 35         SnAgSnAff = f)a  Asserts that the message in a raised exception equals the given string.

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

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.
  args: Extra args.
  kwargs: Extra kwargs.
r   z,Exception message does not match.
Expected: r   N)r~   r;   rt   r   )rG   r   expected_exception_messager   r   r   r   actual_exception_messages           r   assertRaisesWithLiteralMatch%TestCase.assertRaisesWithLiteralMatch@  sn    "
=D#F# ii"++m;<  >!$S
ll-I $>#;=> >>s   ) A 'AA c                 4    U R                   " UUU/UQ70 UD6  g)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.
  args: Extra args.
  kwargs: Extra keyword args.
N)assertRaisesRegexp)rG   r   expected_regexpr   r   r   s         r   assertRaisesWithRegexpMatch$TestCase.assertRaisesWithRegexpMatch]  s/    " 	 
	
 r   c           
      "   [        U[        5      (       d  U/nSnSnU Hm  nUR                  [        U5      U5      nUS:X  a!  US:X  a  U R	                  SU< SU< S35        O$US:X  a  U R	                  SU< SU< SU< S35        UnUnMo     g)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'.
r   NzDid not find 'z' in ''z	' after ')r   r   findrt   r~   )rG   stringstargetcurrent_indexlast_stringstringindexs          r   assertContainsInOrderTestCase.assertContainsInOrderu  s     gt$$	gMKkk#f+}5e	"!+		6# 	$B;		;0 	1km r   c                 D  ^  U 4S jnU 4S jn[         R                  " U6  H;  n[        U5      n[        USS 5       H  u  pVXES-   S  H  nU" Xg5        M     M     M=     U H;  nU H  n	U" X5        M     [         R                  " X5       H  u  pU" X5        M     M=     g)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.
  ['foo'],  # As do strings.
  [A(1, 'a')],
  [A(2, 'b')],  # 2 is after 1.
  [A(2, 'c'), A(2, 'd')],  # The second argument is irrelevant.
  [A(3, 'z')])

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].
c                   > TR                  X:H  U < SU< 35        TR                  X:g  U < SU< 35        TR                  X5        TR                  X:  U< SU < 35        TR                  X5        TR                  X:*  U< SU < 35        TR	                  X5        TR                  X:  U < SU< 35        TR                  X5        TR                  X:  U < SU< 35        g)z$Ensures small is ordered before big. unexpectedly equals  unexpectedly less than z$ unexpectedly less than or equal to  unexpectedly greater than z' unexpectedly greater than or equal to N)assertFalse
assertTrue
assertLessassertLessEqualassertGreaterassertGreaterEqual)smallbigrG   s     r   
CheckOrder1TestCase.assertTotallyOrdered.<locals>.CheckOrder  s    
u|6;SAC
ooel5:C@B
ooe!
s{9<eDF
5&
s|u&' $
u{<A3GI
c)
u|&'r   c           
      :  > TR                  X5        TR                  X:g  U < SU< 35        TR                  [        U 5      [        U5      S[        U 5      U [        U5      U4-  5        TR                  X:  U < SU< 35        TR                  X:  U< SU < 35        TR                  X5        TR                  X5        TR                  X:  U < SU< 35        TR                  X:  U< SU < 35        TR	                  X5        TR	                  X5        g)zEnsures that a and b are equal.r   z5hash %d of %r unexpectedly not equal to hash %d of %rr   r   N)assertEqualr   hashr   r   )abrG   s     r   
CheckEqual1TestCase.assertTotallyOrdered.<locals>.CheckEqual  s    
q
qvaCD
tAwQNq'1d1gq123 qu1EF
qu1EF
1 
1 
qu1aHI
qu1aHI
a#
a#r   Nr   r   )	itertoolsproductr   	enumerate)rG   groupsr  r	  elementsr   r   r  groupr  r  s   `          r   assertTotallyOrderedTestCase.assertTotallyOrdered  s    N'*$$ %%v.hh#HSbM2,%AIJ'C
U
  ( 3 / !1 ##E1$!1 2 r   c                     U R                   $ )z1Return any properties that the user has recorded.ro   r_   s    r   getRecordedPropertiesTestCase.getRecordedProperties  s    %%%r   c                      X R                   U'   g)zRecord 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
Nr  )rG   property_nameproperty_values      r   recordPropertyTestCase.recordProperty  s     1?}-r   c                    >  [         [        U ]  X5      $ ! [         a#    [	        U SS5      n[         [        U ]  U5         Of = f[         [        U ]  X5      $ )N_testMethodNamer   )r(   rc   _getAssertEqualityFuncAttributeErrorr:   r)   )rG   r   r   test_methodr7   s       r   r  TestCase._getAssertEqualityFunc  s]    	28T9%HH 2 D"3\BkHd$[12 47FFs    *AA)__recorded_properties)runTestr'   NT)r;   r=   re   rf   r<   maxDiffr)   ru   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  rj   rk   rl   s   @r   rc   rc   "  s    J'$0&!P*(\:&%)EV 574T&* D:=*=:04Yv&?G Gr   rc   c                    S=p#/ n/ n  X   nX   nXg:  a.  UR                  U5        US-  nX   U:X  a  US-  nX   U:X  a  M  OlXg:  a.  UR                  U5        US-  nX   U:X  a  US-  nX   U:X  a  M  O9US-  n X   U:X  a  US-  nX   U:X  a  M  US-  nX   U:X  a  US-  nX   U:X  a  M  M  ! US-  nX   U:X  a  US-  nX   U:X  a  M  f f = f! [         a+    UR                  XS 5        UR                  XS 5         XE4$ f = f)a6  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 actualy got.
Returns:
  (missing, unexpected)
  missing: items in expected that are not in actual.
  unexpected: items in actual that are not in expected.
r   r   N)r   
IndexErrorextend)r   r   ijr   r   er  s           r   r   r   
  sa     )!'*
+a
)a	
q	QkQ
q&! kQ5!	Qi1n
q&! i1n 	
Q	q FA q  q&!	QFA 	Q+ 	( q&!	QFA 	Q nnXb\"r
#			s;   8C 0C 8C >B3 C 3CCC 0D
	D
c                   6    \ rS rSrSrS rS rS rS rS r	Sr
g	)
CapturedStreamiK  z'A temporarily redirected output stream.c                    Xl         UR                  5       U l        X l        [        R
                  " U R                  5      U l        [        R                  " U R                  [        R                  [        R                  -  [        R                  -  S5      nU R                   R                  5         [        R                  " X0R                  5        [        R                  " U5        g )N  )_streamfileno_fd	_filenamer
   dup_uncaptured_fdopenO_CREATO_TRUNCO_WRONLYflushdup2close)rG   streamfilenamecap_fds       r   r)   CapturedStream.__init__N  s    L}}DHN &&*D WWT^^ZZ"**,r{{:F
 	LLGGFHHHHVr   c                 n   U R                   (       d   e[        R                  " U R                  [        R                  [        R
                  -  [        R                  -  S5      nU R                  R                  5         [        R                  " XR                  5        [        R                  " U5        g)z>Resume capturing output to a file (after calling StopCapture).r/  N)r5  r
   r6  r3  r7  O_APPENDr9  r0  r:  r;  r2  r<  )rG   r?  s     r   RestartCaptureCapturedStream.RestartCapture`  ss      WWT^^ZZ"++-;F
 	LLGGFHHHHVr   c                     U R                   R                  5         [        R                  " U R                  U R
                  5        g)zRemove output redirection.N)r0  r:  r
   r;  r5  r2  r_   s    r   StopCaptureCapturedStream.StopCaptureo  s*    LLGGD*r   c                     U R                   $ r'   )r3  r_   s    r   r>  CapturedStream.filenamet  s    >>r   c                 h    U R                  5         [        R                  " U R                  5        U ?g r'   )rF  r
   r<  r5  r_   s    r   __del__CapturedStream.__del__w  s&    HHT  !r   )r2  r3  r0  r5  N)r;   r=   re   rf   r<   r)   rC  rF  r>  rK  rj   r^   r   r   r-  r-  K  s    /$+
r   r-  c                 `    [         R                  U 5      (       a   e[        X5      [         U '   g)zRedirect an output stream to a file.

Args:
  stream: Should be sys.stdout or sys.stderr.
  filename: File where output should be stored.
N)_captured_streamshas_keyr-  )r=  r>  s     r   _CaptureTestOutputrP    s+     &&v...	.,V>Fr   c                    [         R                  U 5      (       d   e[         U    n[         R                  5        H  nUR                  5         M      [	        UR                  5       U5        [         U 	 [         R                  5        H  nUR                  5         M     g! [         U 	 [         R                  5        H  nUR                  5         M     f = f)zCompare 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)rN  rO  
itervaluesrF  _Diffr>  rC  )r=  golden_filenamecap
cap_streams       r   _DiffTestOutputrW    s     
	"	"6	*	**	*&!#%002j 3"	#,,./* 	&!'224
! 5 	&!'224
! 5s   B 4Cc                     U (       d.  [         R                  R                  [        R                  S5      n [        [        R                  U 5        g )Nzcaptured.out)r
   r   r   FLAGSr"   rP  sysstdoutoutfiles    r   CaptureTestStdoutr^    -    	ggll5,,n=GSZZ)r   c                     U (       d.  [         R                  R                  [        R                  S5      n [        [        R                  U 5        g )Nzcaptured.err)r
   r   r   rY  r"   rP  rZ  stderrr\  s    r   CaptureTestStderrrb    r_  r   c                 8    [        [        R                  U 5        g r'   )rW  rZ  r[  goldens    r   DiffTestStdoutrf        #**f%r   c                 8    [        [        R                  U 5        g r'   )rW  rZ  ra  rd  s    r   DiffTestStderrri    rg  r   c                      [         (       a5  [         R                  5       u  pUR                  5         A[         (       a  M4  g g r'   )rN  popitemrF  )_rV  s     r   StopCapturingrm    s/    %--/MA 	r   c                     [         R                  " U[         R                  [         R                  -  [         R                  -  S5      n[         R
                  " X 5        [         R                  " U5        g)z$Write data into file named filename.r/  N)r
   r6  r7  r8  r9  writer<  )datar>  fds      r   _WriteTestDatarr    sA    	wwxbjj02;;>F"((2((2,r   c                       \ rS rSrSrg)OutputDifferedErrori  r^   Nr;   r=   re   rf   rj   r^   r   r   rt  rt        r   rt  c                       \ rS rSrSrg)DiffFailureErrori  r^   Nru  r^   r   r   rx  rx    rv  r   rx  c                    S[         R                  " U 5      < S[         R                  " U5      < 3n[         R                  " U5      u  p4[        R                  " U5      (       a.  [        R
                  " U5      S:X  a  [        SU< SU< S35      e[        R                  " U5      (       a  [        R
                  " U5      S:w  a  [        SU< SU< S35      eg	)
z+Run standard unix 'diff' against two files.z${TEST_DIFF:-diff}  r   z	
Running rs   z'
Test output differed from golden file
r   z.
Failure diffing test output with golden file
N)commandsmkarggetstatusoutputr
   	WIFEXITEDWEXITSTATUSrt  rx  )lhsrhscmdstatusoutputs        r   rS  rS    s     '/nnS&98>>#;NO#--c26\\&bnnV49
696C D D<<2>>&#9Q#>
36@ A A $?r   c                     [         R                  R                  [        R                  S5      n[        X5        [        X!5        g)zDiff data agains a golden file.zprovided.datNr
   r   r   rY  r"   rr  rS  )rp  re  	data_files      r   DiffTestStringFiler    s,    ggll5,,n=)!	r   c                     [         R                  R                  [        R                  S5      n[        X5        [         R                  R                  [        R                  S5      n[        X5        [        X#5        g)zDiff two strings.zprovided_1.datzprovided_2.datNr  )data1data2
data1_file
data2_files       r   DiffTestStringsr    sP    ww||E--/?@*#ww||E--/?@*#
r   c                     [        X5        g r'   )rS  )testgenre  s     r   DiffTestFilesr    s
    r   c                 p    [        U [        R                  5      (       a  U $ [        R                  " U 5      $ )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.
)r   r   r   r   ShellEscapeList)r   s    r   r   r     s-     **++N$$W--r   c           	         Uc  0 n[         R                  R                  S5      (       a,  UR                  S5      (       d  [         R                  S   US'   [        U [        R
                  5      n[        R                  " U UUU[        R                  [        R                  S9nUR                  5       S   nUR                  5       nXe4$ )aM  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).
PYTHON_RUNFILES)r   r   shellra  r[  r   )r
   r   r   r   r   r   
subprocessPopenSTDOUTPIPEcommunicatewait)r   r   r   	use_shellprocessr  exit_statuss          r   r   r     s     	[# ZZ^^%&&sww7H/I/IZZ(9:C%"3"34)
__'  #&+
	r   c                     SU -   S-   S-   $ )zQuotes a potentially multi-line string to make the start and end obvious.

Args:
  s: A string.

Returns:
  The quoted string.
z8<-----------
rs   z----------->8
r^   )ss    r   r   r     s$     

 r   c                   "    \ rS rSrSrSS jrSrg)TestProgramManualRuni,  z,A TestProgram which runs the tests manually.c                 R    U(       a   [         R                  R                  U 5        gg)zRun the tests.N)rg   TestProgramrunTests)rG   do_runs     r   r  TestProgramManualRun.runTests/  s    ##D) r   r^   N)F)r;   r=   re   rf   r<   r  rj   r^   r   r   r  r  ,  s
    4*r   r  c                  $    [        [        X5        g)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)r   r   s     r   mainr  5  s     Hd#r   c                      [         R                  " 5       R                  n [        R                  nU (       a?  U R
                  UL a  U R                  R                  S;   a  gU R                  n U (       a  M?  g)z8Returns True iff app.main or app.really_start is active.)runreally_startTF)rZ  	_getframef_backr   __dict__	f_globalsf_codeco_name)fapp_dicts     r   _IsInAppMainr  D  sU    	mmo!\\(	{{h188#3#37N#N	A 	
 
r   c                   $    \ rS rSrSrS rS rSrg)	SavedFlagiO  z3Helper class for saving and restoring a flag value.c                 T    Xl         UR                  U l        UR                  U l        g r'   )flagr   present)rG   r  s     r   r)   SavedFlag.__init__R  s    IDJ<<DLr   c                 p    U R                   U R                  l         U R                  U R                  l        g r'   )r   r  r  r_   s    r   RestoreFlagSavedFlag.RestoreFlagW  s!    jjDIIODIIr   )r  r  r   N)r;   r=   re   rf   r<   r)   r  rj   r^   r   r   r  r  O  s    ; 
%r   r  c                   ^ ^^ [        5       (       a  [        S [        R                  5       R	                  5        5       5      nSU;   a  S[        l        US	 [        [        R                  5      nUR	                  5        H  nUR                  5         M     T " UTT5        gS[        ;   a  [        R                  SS5        UU U4S jn[        R                  " US9  g)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__.
c              3   P   #    U  H  nUR                   [        U5      4v   M     g 7fr'   )r3   r  ).0r  s     r   	<genexpr>_RunInApp.<locals>.<genexpr>  s$      ? =1 	!- =s   $&alsologtostderrTc                    > T" U TT5        g r'   r^   )argvr   functionr   s    r   Main_RunInApp.<locals>.Main  s    tT6"r   )r  N)r  r5   rY  FlagDictrR  r  rZ  r  r  
SetDefaultr   r  )r  r   r   saved_flagsr  
saved_flagr  s   ```    r   r  r  \  s    P ^^  ? % 0 ; ; =? ?K6 K'"e
'
( ?D!,,.
 / T4  E!($/# $r   c                    UR                  S5      n[        R                  R                  [        R
                  5      (       d$  [        R                  " [        R
                  5        [        R                  S   n[        US5      (       a*  [        UR                  5      (       a  UR                  5         UR                  SU 5         Sn[        U0 UD6nU(       a  X6l        O#[        R                   " UR"                  S9Ul        UR                  R%                  UR&                  5      n[        US5      (       a*  [        UR(                  5      (       a  UR)                  5         [        R*                  " UR-                  5       (       + 5        g! [        US5      (       a,  [        UR(                  5      (       a  UR)                  5         f f f = f)ar  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__rJ   r  N)	verbosityrQ   )r   r
   r   isdirrY  r"   makedirsrZ  moduleshasattrcallablerJ   
setdefaultr  r  rg   TextTestRunnerr  r  rY   rQ   exitwasSuccessful)r  r   r   test_runnermain_modresulttest_programs          r   r  r    sY     

<(+ 
u((	)	)KK!!" [[$(XwHX^^$<$<NN
 	FD!F'88L + ( 7 7 **!,l$$(():):;F x$$(2C2C)D)D((v##%%& x$$(2C2C)D)D *E$s   	A#F ?Gr'   r$  )<r<   
__author__r{  r   getpassr  r
   r   r  rZ  r   r   version_info	unittest2rg   google.apputilsr   gflagsflagsr   rY  r   r   DEFINE_integerDEFINE_stringr   r   r   r$   rc   r   objectr-  rN  rP  rW  r^  rb  rf  ri  rm  rr  r   rt  	Exceptionrx  rS  r  r  r  r   r   r   r  r  r  r  r  r  r  r^   r   r   <module>r     s    4
     	 	  
   f   %
   ')B)DN %&	'
   MJJNN="5D#$&   M#8#:;#$&
J2d J2ZbGx   bGP.B/V /d  ?"0**&&. y A .>*8// *$
% 
%_ D.'r   