
     q                        S r SSKJr  SSKJr  SSKJr  SSKJr  SSKJ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SSKJr  SSKrSS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSK J!r!  SSK J"r"  SSK J#r#  SSK$J%r%  SSK$J&r&  SSK'J(r(   SSK)r)\RV                  (       a  \,r-Sr.Sr/Sr0Sr1S\1-   S\.-  -   r2\" SS5      r3S r4S r5S r6S r7S  r8 S$S! jr9 " S" S#\5      r:g! \* a    Sr) NZf = f)%&Implementation of gsutil test command.    )absolute_import)print_function)division)unicode_literals)
namedtupleN)range)ProjectIdException)Command)ResetFailureCount)CommandException)PopulateProjectId)GetTestNames)InvokedFromParFile)unittest)NO_MAX)UTF8)
IS_WINDOWS   2   sequential_onlyz3
  gsutil test [-l] [-u] [-f] [command command...]
z
<B>SYNOPSIS</B>
a  


<B>DESCRIPTION</B>
  The gsutil test command runs the gsutil unit tests and integration tests.
  The unit tests use an in-memory mock storage service implementation, while
  the integration tests send requests to the production service using the
  `preferred API
  <https://cloud.google.com/storage/docs/request-endpoints#gsutil>`_ set in the
  boto configuration file.

  CAUTION: The ``test`` command creates test buckets and objects in your project.
  Force quitting the ``test`` command can leave behind stale buckets, objects,
  and HMAC keys in your project.

  To run both the unit tests and integration tests, run the command with no
  arguments:

    gsutil test

  To run the unit tests only (which run quickly):

    gsutil test -u

  Tests run in parallel regardless of whether the top-level -m flag is
  present. To limit the number of tests run in parallel to 10 at a time:

    gsutil test -p 10

  To force tests to run sequentially:

    gsutil test -p 1

  To have sequentially-run tests stop running immediately when an error occurs:

    gsutil test -f

  To run tests for one or more individual commands add those commands as
  arguments. For example, the following command will run the cp and mv command
  tests:

    gsutil test cp mv

  To list available tests, run the test command with the -l argument:

    gsutil test -l

  The tests are defined in the code under the gslib/tests module. Each test
  file is of the format test_[name].py where [name] is the test name you can
  pass to this command. For example, running "gsutil test ls" would run the
  tests in "gslib/tests/test_ls.py".

  You can also run an individual test class or function name by passing the
  test module followed by the class name and optionally a test name. For
  example, to run the an entire test class by name:

    gsutil test naming.GsutilNamingTests

  or an individual test function:

    gsutil test cp.TestCp.test_streaming

  You can list the available tests under a module or class by passing arguments
  with the -l option. For example, to list all available test functions in the
  cp module:

    gsutil test -l cp

  To output test coverage:

    gsutil test -c -p 500
    coverage html

  This will output an HTML report to a directory named 'htmlcov'.

  Test coverage is compatible with v4.1 of the coverage module
  (https://pypi.python.org/pypi/coverage).


<B>OPTIONS</B>
  -b          Run tests against multi-regional US buckets. By default,
              tests run against regional buckets in us-central1.

  -c          Output coverage information.

  -f          Exit on first sequential test failure.

  -l          List available tests.

  -p N        Run at most N tests in parallel. The default value is %d.

  -s          Run tests against S3 instead of GS.

  -u          Only run unit tests.
TestProcessDatazname return_code stdout stderrc                 D   ^ ^  " UU 4S jS[         R                  5      mT$ )zCreates a closure of CustomTestResult.

Args:
  total_tests: The total number of tests being run.

Returns:
  An instance of CustomTestResult.
c                   2   >^  \ rS rSrSrUU U4S jrSrU =r$ )3MakeCustomTestResultClass.<locals>.CustomTestResult   zDA subclass of unittest.TextTestResult that prints a progress report.c                   > [         TU ]  U5        U R                  (       a  SR                  UR	                  5       R                  S5      SS  5      nSU R                  T[        U R                  5      [        U R                  5      [        U R                  5      U4-  nUS S nUR                  S5      nU R                  R                  SU-  5        g g )N.z(%d/%d finished - E[%d] F[%d] s[%d] - %sI   z%s - )super	startTestdotsjoinidsplittestsRunlenerrorsfailuresskippedljuststreamwrite)selftesttest_idmessageCustomTestResult	__class__total_testss       &platform/gsutil/gslib/commands/test.pyr"   =MakeCustomTestResultClass.<locals>.CustomTestResult.startTest   s    d-d3	((4779??3/45>MM;DKK0@&DLL(97DD #2,--#'G+, 
     )__name__
__module____qualname____firstlineno____doc__r"   __static_attributes____classcell__)r4   r3   r5   s   @r6   r3   r      s    N	- 	-r8   r3   )r   TextTestResult)r5   r3   s   `@r6   MakeCustomTestResultClassrB      s"    - -00 - 
r8   c                    U /n/ nU(       a  UR                  5       nU H`  n[        U[        R                  5      (       a  UR	                  U5        M5  UR	                  UR                  5       [        S5      S 5        Mb     U(       a  M  U$ )zGTakes a list of test suites and returns a list of contained test names.gslib.tests.test_N)pop
isinstancer   	TestSuiteappendr%   r(   )
test_suitesuites
test_namessuiter0   s        r6   GetTestNamesFromSuitesrM      sv    <&*JJLE	D(,,	-	-d$'')C(;$<$=>?	  	 
r8   c                 p    [        U R                  5      R                  S5      S   S-   U R                  -   $ )z<Converts a python.unittest to its gsutil test-callable name.'   r   )strr4   r&   _testMethodName)	test_cases    r6   TestCaseToNamerT      s8    
i!!
"
(
(
.q
1C
7

#
#$ %r8   c                    SSK Jn  / n/ n/ n/ nU /n/ nU(       a  UR                  5       n[        U[        R
                  R                  5      (       a%  UR                   H  n	UR                  U	5        M     O0[        U[        R                  5      (       a  UR                  U5        U(       a  M  U H  n
[        XR                  S5      n[        USS5      (       a  UR                  [        U
5      5        MG  [        USS5      (       d  UR                  [        U
5      5        Mu  [        U
SS5      (       d  UR                  [        U
5      5        M  [        X5      (       a  UR                  [        U
5      5        M  UR                  [        U
5      5        M     [        U5      [        U5      [        U5      [        U5      4$ )a  Splits a test suite into groups with different running properties.

Args:
  test_suite: A python unittest test suite.

Returns:
  4-part tuple of lists of test names:
  (tests that must be run sequentially,
   tests that must be isolated in a separate process but can be run either
       sequentially or in parallel,
   unit tests that can be run in parallel,
   integration tests that can run in parallel)
r   )GsUtilUnitTestCaseNrequires_isolationFis_parallelizableT)"gslib.tests.testcase.unit_testcaserV   rE   rF   r   rL   rG   _testsrH   TestCasegetattrrR   rT   sorted)rI   rV   isolated_testssequential_tests parallelizable_integration_testsparallelizable_unit_testsitems_to_evaluatecases_to_evaluatesuite_or_caseitemrS   test_methods               r6   SplitParallelizableTestSuiterg      s     D.%'" !l%))+M-!9!9::&&$  & '	M8#4#4	5	5}- 	 %i)%>%>EK{0%88 N956["5t<<nY78Y 3T::nY78	I	2	2&&~i'@A&--nY.GH % !
"F>$:
*
+
1
2
4 4r8   c                 8    SnU  H  nU(       a  M  US-  nM     U$ )z*Counts number of falses in the input list.r   rP   r9   )
input_list	num_falsere   s      r6   CountFalseInListrk     s'    )d41ni  
r8   c           	      r   Un[        5       (       d  [        R                  /O/ n[        R                  R
                  (       a  S/O/ n[        R                  R                  (       a  S/O/ n	/ n
 SS[        5       -  /n
[        R                  " 5       nUn[        U5      U:  Ga  U[        U 5      :  Ga  [        R                  R                  5       nU(       a  X]S'   [        5       n[!        U["        R$                  /-   U
-   S/-   U-   U	-   S[&        -   /-   X   [        S5      S	 /-   5       Vs/ s H  n[(        R*                  " U5      PM     nn[(        R,                  " U5       H3  u  nn[(        R*                  " U5      U[(        R*                  " U5      '   M5     UR/                  [0        R2                  " U[0        R4                  [0        R4                  US
95        US-  nUR/                  S5        [        R                  " 5       U-
  S:  a:  [7        SX-
  [        U5      [        U 5      4-  5        [        R                  " 5       n[        U5      U:  a  U[        U 5      :  a  GM  U[        U 5      :X  a"  [7        S[        U5      [        U 5      4-  5        U$ ! [         a     GN1f = fs  snf )aO  Creates test processes to run tests in parallel.

Args:
  parallel_tests: List of all parallel tests.
  test_index: List index of last created test before this function call.
  process_list: List of running subprocesses. Created processes are appended
                to this list.
  process_done: List of booleans indicating process completion. One 'False'
                will be added per process created.
  max_parallel_tests: Maximum number of tests to run in parallel.
  root_coverage_file: The root .coverage filename if coverage is requested.

Returns:
  Index of last created test.
-s-bz-ozGSUtil:default_project_id=%sGSUTIL_COVERAGE_OUTPUT_FILEr0   --rD   N)stdoutstderrenvrP   Fr   z.Created %d new processes (total %d/%d created)z.Test process creation finished (%d/%d created))r   sys
executabletestsutilRUN_S3_TESTSUSE_MULTIREGIONAL_BUCKETSr   r
   timerk   r(   osenvironcopydictlistgslibGSUTIL_PATH_SEQUENTIAL_ISOLATION_FLAGsix
ensure_str	iteritemsrH   
subprocessPopenPIPEprint)parallel_tests
test_indexprocess_listprocess_donemax_parallel_testsroot_coverage_fileorig_test_indexexecutable_prefixs3_argumentmultiregional_bucketsproject_id_argprocess_create_start_timelast_log_timers   envstrpartcmdkvs                      r6   CreateTestProcessesr     s   * / /A.B.Bs~~&**11r+$)JJ$H$H4&b.	,/@/BBN #iik+-	,	'*<	<	c.)	)
**//
C+=
'(VF *.  H 	
 "" ../0 ',?(@(ABCD	*
	*
t 	*
   c"1"%.."3fS^^A # * *#	%&
 !OJyy{]"Q&=*C,=.!## % iikmA 
,	'*<	<	c.)	)@ 3~&&	;s>234 6	U 
 		s   0J# 2 J4#
J10J1c                       \ rS rSrSr\R                  " S/ \S\SSSS\	/S9
r
\R                  " S/ S	S
\0 S9rS rS r\" 5       \" 5       4S jrS rSrg)TestCommandih  r   r0   r   zbuflp:scTF)	command_name_aliasesusage_synopsismin_argsmax_argssupported_sub_argsfile_url_okprovider_url_okurls_start_argsupported_private_argscommand_helpz2Run gsutil unit/integration tests (for developers))	help_namehelp_name_aliases	help_typehelp_one_line_summary	help_textsubcommand_help_textc           
         / n/ n/ nSnSnSn	[        U5      n
[        R                  " 5       =p[        USUUUUS9n[        U5      U
:  Ga  [        [        U5      5       H  nX^   (       d  XN   R	                  5       c  M!  SX^'   XN   R                  5       u  nnXN   R                  R                  5         XN   R                  R                  5         XN   R                  S:w  a  US-  nUR                  [        X   XN   R                  UUS95        M     [        U5      U
:  a  [        UUUUUUS9n[        U5      U
:  Ga  [        R                  " 5       U-
  S:  a  [        S[        U5      X4-  5        [        U5      U	:X  a  US-  nO[        U5      n	SnUS:  a~  / n[        [        U5      5       H!  nX^   (       a  M  UR                  X   5        M#     [        R                  " 5       U-
  n[        S	R                  [        [        U5      5      US
95        [        R                  " 5       n[        R                   " S5        [        U5      U
:  a  GM  [        R                  " 5       nU(       a  U H}  nUR"                  S:w  d  M  UR                  R%                  S5      n[        SUR&                  -  5        U H/  n[        UR)                  [*        5      R-                  5       5        M1     M     UUU-
  4$ )a>  Executes the parallel/isolated portion of the test suite.

Args:
  parallel_integration_tests: List of tests to execute.
  max_parallel_tests: Maximum number of parallel tests to run at once.
  coverage_filename: If not None, filename for coverage output.

Returns:
  (int number of test failures, float elapsed time)
r   )r   TrP   )namereturn_coderq   rr   r   z%d/%d finished - %d failures   zL{sec} seconds elapsed since beginning parallel tests.
Still running: {procs})secprocs   
zResults for failed test %s:)r(   rz   r   r	   pollcommunicaterq   closerr   
returncoderH   r   r   formatrQ   intsleepr   r&   r   decoder   strip)r/   parallel_integration_testsr   coverage_filenamer   r   process_resultsnum_parallel_failuresprogress_less_logging_cyclescompleted_as_of_last_lognum_parallel_testsparallel_start_timer   r   proc_numrq   rr   still_runningelapsedprocess_run_finish_timeresult
new_stderrlines                          r6   RunParallelTestsTestCommand.RunParallelTests  s    LLO#$  78*.))+5$%?%&%1%1%78IKJ o
!3
3C-.(!\%;%@%@%B%J
!%%/;;=%%++-%%++-!,,1
1
$
!;!E(4(>(I(I#)#)+	, / 
\	/	/()C)3)5)5);<MO
 
_	 2	299;&*
,?#%7OPQ !%==(A-('*?';$+,()A- M!#l"34!++$$%?%IJ 5 iik$77G ,-3Vs7|,* .4 . ))+-

1e o
!3
3f #iik#&"}}**51*
-;
< d$++d#))+, !	 $ "$'::= =r8   c                 H   [        SXV-
  < SU< 35        [        SXQ-   [        XG-   5      U[        U5      U[        U5      4-  5        U R                  U5        [        5         U(       d  U(       a  [        S5        gU(       a  [        S5        U(       d  [        S5        gg)z6Prints test results for parallel and sequential tests.z"Parallel tests complete. Success: z Fail: zDRan %d tests in %.3fs (%d sequential in %.3fs, %d parallel in %.3fs)OKzFAILED (parallel tests)zFAILED (sequential tests)N)r   floatPrintSkippedTests)r/   num_sequential_testssequential_successsequential_skippedsequential_time_elapsedr   r   parallel_time_elapseds           r6   PrintTestResultsTestCommand.PrintTestResults  s     
57LN O	N		2	&>	?	u%<=	U#89	;	;= 	-.	G %7Dk	'()*  r8   c                    [        U5      S:  d  [        U5      S:  ah  [        U5      n[        U5      nUR                  U5      n[        S5        U H/  u  pE[        SUR	                  5       -   5        [        SU-   5        M1     gg)a  Prints all skipped tests, and the reasons they  were skipped.

Takes the union of sequentual_skipped and parallel_skipped,
and pretty-prints the resulting methods and reasons. Note that these two
arguments are lists of tuples from TestResult.skipped as described here:
https://docs.python.org/2/library/unittest.html#unittest.TestResult.skipped

Args:
    sequentual_skipped: An instance of TestResult.skipped.
    parallel_skipped: An instance of TestResult.skipped.
r   zTests skipped:z  z    Reason: N)r(   setunionr   r%   )r/   r   parallel_skippedall_skippedmethodreasons         r6   r   TestCommand.PrintSkippedTests  s     "c*:&;a&?12-.&,,-=>k'.&dVYY[ !nv%& ( '@r8   c           	         SnSn[         nSnSnU R                  (       a  U R                   H  u  pgUS:X  a  S[        R                  l        M"  US:X  a  SnM,  US:X  a  SnM6  US:X  a  SnM@  US[
        -   :X  a  SnMQ  US:X  a  [        U5      nMd  US	:X  aA  [        R                  R                  (       d  [        S
5      eS[        R                  l	        M  US:X  d  M  S[        R                  l
        M     U(       a  [        (       d  [        S5      e[        R                  R                  (       a0  U[        :  a&  U R                  R                  S[        5        [        n[        [!        5       5      nU(       aM  U R"                  (       d<  [%        S['        U5      -  5        [%        SSR)                  [        U5      5      5        gU R"                  (       aZ  / n	U R"                   HG  n
X;   d  U
R+                  S5      S   U;   a  U	R-                  SU
-  5        M6  U	R-                  U
5        MI     OU V
s/ s H  n
SU
-  PM
     n	n
[.        R0                  " 5         [.        R2                  " 5       nU	(       aA  [.        R4                  " 5       nU	 H&  n UR7                  U5      nUR9                  U5        M(     U(       aG  [M        W5      n[%        S['        U5      -  5        [%        SSR)                  [        U5      5      5        g[N        RP                  " 5       RS                  5       [N        RT                  ::  a  SnO&Sn[N        RV                  " [N        RX                  5        U(       aO  [        R                  " S/SS[Z        R\                  " 5       S-   /S 9nUR_                  5         URa                  5         SnSn[c        W5      u  nnnn[        R                  R                  (       d  / n[N        Rd                  " S!U5        [N        Rd                  " S"U5        [N        Rd                  " S#U5        [N        Rd                  " S$U5        U=(       d    ['        U5      S:*  =(       a    U(       + nS%[f        Rh                  S&'   U(       aT  URk                  5       n[m        U5      n[.        Rn                  " UUUS'9nURq                  U5      nURs                  5       nGOUS:X  a  UU-  n/ n[t        Rt                  " 5       n ['        U5      ['        U5      -   (       a  [%        S(['        U5      ['        U5      -   -  5        UU-   n!URw                  [        U! V"s/ s H  n"U"PM     sn"5      5      nURk                  5       n#[m        U#5      n[.        Rn                  " UUUS'9nURq                  U5      nURs                  5       nURx                  n$OSn#Sn[t        Rt                  " 5       U -
  n%UU-  n['        U5      n&U&(       d  O/ n$[{        UU&5      n'U&S:  aK  US:  aE  S)n(U'[         :  a  U(S*-  n([%        S+R)                  [|        R~                  " U(U&U'4-  5      5      5        O[%        S,U&-  5        U R                  UUU(       a  WR                  R                  OS5      u  nn)U R                  U#UU$U%U&UU)5        U(       aR  WR                  5         UR                  5         UR                  5         [%        S-UR                  R                  -  5        S.[f        Rh                  S&'   U(       a  U(       d  [        5         ggs  sn
f ! [:        [<        4 a|  nSU< S[?        U5      < 3n [A        U5        OL! [B         a?  n[D        RF                  " 5       n[H        RJ                  " SSU5      nUSU-  -  n SnAOSnAff = f[        U5      eSnAff = fs  sn"f )/z)Command entry point for the test command.Frn   Tz-cz-fz-lrp   z-prm   zbS3 tests require S3 credentials. Please add appropriate credentials to your .boto file and re-run.z-uzrCoverage has been requested but the coverage module was not found. You can install it with "pip install coverage".zCReducing parallel tests to %d due to S3 maximum bucket limitations.zFound %d test names: z
  r   r   zgslib.tests.test_%sz%Failed to import test code from file z#. TestLoader provided this error:

z\nz
    z

Additional traceback:

%sNrP      r   zgslib/third_party/*zgslib/tests/**)sourceomitzSequential tests to run: %szIsolated tests to run: %szParallel unit tests to run: %sz%Parallel integration tests to run: %s1GSUTIL_TEST_ANALYTICS)	verbosityresultclassfailfastzRunning %d tests sequentially.z1Running %d tests in parallel mode (%d processes).z Please be patient while your CPU is incinerated. If your machine becomes unresponsive, consider reducing the amount of parallel test processes by running 'gsutil test -p <num_processes>'.
z4Running %d tests sequentially in isolated processes.z%Coverage information was saved to: %s0)H _DEFAULT_TEST_PARALLEL_PROCESSESsub_optsrv   rw   ry   r   longHAS_S3_CREDSr   rx   RUN_INTEGRATION_TESTScoverage#_DEFAULT_S3_TEST_PARALLEL_PROCESSESloggerwarnr]   r   argsr   r(   r$   r&   rH   r   installHandler
TestLoaderrG   loadTestsFromNameaddTestsImportErrorAttributeErrorrQ   
__import__	Exception	traceback
format_excresubrM   logging	getLoggergetEffectiveLevelINFOdisableERRORtempfile
gettempdirerasestartrg   debugr{   r|   countTestCasesrB   TextTestRunnerrunwasSuccessfulrz   loadTestsFromNamesr+   mintextwrapwrapr   
data_filesfilenamer   stopcombinesaver   )*r/   r   
list_testsr   perform_coverager   oarK   commands_to_testr   loaderrL   command_namesuite_for_current_commandemsgstack_traceerrr   coverage_controllerr   r   r_   r^   parallel_unit_testsr   run_tests_sequentiallyr5   r   runnerretsequential_start_timesequential_tests_to_run	test_namer   r   r   r   num_processesr2   r   s*                                             r6   
RunCommandTestCommand.RunCommand  s   HJ9O}}--$!915%**
.$Y!
$Y($Y*4445 !/$Y#Aw
$Y((" $6 7 7 %)%**
!$Y-2%**
*-  0 <= = 	

@@
kk=? ?'J$))"S_45CVJ/01 yy))$C!3z!A

!
!"7$">
?

!
!$
'	  DNN:4/$6:N   "F  "e*,	&&,&>&>|&L
#
..2
3 +( )%0j"S_45CVJ/01,,.',,>iioogmm$
 %--gY2G2A2:2E2E2G#2M401 !! %A$G!~': ::++#% MM/1ABMM-~>MM24GHMM9,. . 3"#=>!C  2#11  +.BJJ&'((*k-k:k&&3>08:f JJuc,,.	q	  	66%'""iik 
	%8!9	9.#$s+>'??A 	B"25H"H))/FG/F)I/FGHJ$335/0DE((95@2:< jj ..0 [[ ! $		.C C !N2 9:.0BC!&81&<G'==67G
 mmG'9=&IIJL N G#$ &9=9N9N&(:  **33%):+6	 5 	24F02I02G3	5
  !!# 4 ++445 7 +.BJJ&'"7Q O ^, 	&(4c!f>#=|$ =#..0K&&+6C4<<C=
 !%
%	&~ HsN   :]"]	_	__-]98_9
_5^=8_=___r9   N)r:   r;   r<   r=   r>   r   CreateCommandSpec	_SYNOPSISr   r   command_specHelpSpec_DETAILED_HELP_TEXT	help_specr   r   r   r   r3  r?   r9   r8   r6   r   r   h  s~    . **#89, 
>#)X=t+4 25 ',cr8   r   )N);r>   
__future__r   r   r   r   collectionsr   r  r{   r   r  rt   r  r  rz   r  r   	six.movesr	   r   gslib.cloud_apir
   gslib.commandr   r   gslib.exceptionr   gslib.project_idr   gslib.testsrv   gslib.tests.utilr   r   r   gslib.utils.constantsr   r   gslib.utils.system_utilr   r   r   PY3r   r   r   r   r   r6  r9  r   rB   rM   rT   rg   rk   r   r   r9   r8   r6   <module>rG     s   - & %  ' "  	  	 
     
   . ! + , .  ) / % ( & . 77	$#$  &( #. 	^| '}^'`' D .=?6 %24j ,0K\H' Hg	  (s   C0 0C;:C;