
     q                        d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlmZ ddlZdd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ddl m"Z" ddl m#Z# ddl$m%Z% ddl$m&Z& ddl'm(Z( 	 ddl)Z)ejV                  re,Z-dZ.dZ/dZ0dZ1de1z   de.z  z   Z2 edd      Z3d Z4d Z5d Z6d Z7d  Z8	 d$d!Z9 G d" d#e      Z:y# e*$ r dZ)Y Sw xY w)%&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                 B      G  fddt         j                        S )zCreates a closure of CustomTestResult.

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

  Returns:
    An instance of CustomTestResult.
  c                   (     e Zd ZdZ fdZ xZS )3MakeCustomTestResultClass.<locals>.CustomTestResultzDA subclass of unittest.TextTestResult that prints a progress report.c                    t         |   |       | j                  rdj                  |j	                         j                  d      dd        }d| j                  t        | j                        t        | j                        t        | j                        |fz  }|d d }|j                  d      }| j                  j                  d|z         y y )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!   z=MakeCustomTestResultClass.<locals>.CustomTestResult.startTest   s    d-d3	((4779??3/45>MM;DKK0@&DLL(97DD #2,--#'G+, 
    )__name__
__module____qualname____doc__r!   __classcell__)r3   r2   r4   s   @r5   r2   r      s    N	- 	-r6   r2   )r   TextTestResult)r4   r2   s   `@r5   MakeCustomTestResultClassr=      s    -00 - 
r6   c                     | g}g }|rq|j                         }|D ]Y  }t        |t        j                        r|j	                  |       /|j	                  |j                         t        d      d        [ |rq|S )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suiter/   s        r5   GetTestNamesFromSuitesrH      sq    <&*JJLE	D(,,	-d$'')C(;$<$=>?	  	 
r6   c                 p    t        | j                        j                  d      d   dz   | j                  z   S )z<Converts a python.unittest to its gsutil test-callable name.'   r   )strr3   r%   _testMethodName)	test_cases    r5   TestCaseToNamerO      s8    
i!!
"
(
(
.q
1C
7

#
#$ %r6   c                 8   ddl m} g }g }g }g }| g}g }|r|j                         }t        |t        j
                  j                        r#|j                  D ]  }	|j                  |	        n+t        |t        j                        r|j                  |       |r|D ]  }
t        |
|
j                  d      }t        |dd      r|j                  t        |
             Bt        |dd      s|j                  t        |
             jt        |
dd      s|j                  t        |
             t        |
|      r|j                  t        |
             |j                  t        |
              t        |      t        |      t        |      t        |      fS )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_testcaserQ   r@   rA   r   rG   rB   _testsrC   TestCasegetattrrM   rO   sorted)rD   rQ   isolated_testssequential_tests parallelizable_integration_testsparallelizable_unit_testsitems_to_evaluatecases_to_evaluatesuite_or_caseitemrN   test_methods               r5   SplitParallelizableTestSuiterb      st     D.%'" !l%))+M-!9!9:&&$  & '	M8#4#4	5}- 	 %i)Y%>%>EK{0%8 N956["5t<nY78Y 3T:nY78	I1	2&&~i'@A&--nY.GH % !
"F>$:
*
+
1
2
4 4r6   c                 (    d}| D ]
  }|r|dz  } |S )z*Counts number of falses in the input list.r   rK    )
input_list	num_falser`   s      r5   CountFalseInListrg     s%    )d1ni  
r6   c                 ,   |}t               st        j                  gng }t        j                  j
                  rdgng }t        j                  j                  rdgng }	g }
	 ddt               z  g}
t        j                         }|}t        |      |k  r|t        |       k  rt        j                  j                         }|r||d<   t               }t!        |t"        j$                  gz   |
z   dgz   |z   |	z   dt&        z   gz   | |   t        d      d	 gz         D cg c]  }t)        j*                  |       }}t)        j,                  |      D ]0  \  }}t)        j*                  |      |t)        j*                  |      <   2 |j/                  t1        j2                  |t0        j4                  t0        j4                  |
             |dz  }|j/                  d       t        j                         |z
  dkD  r:t7        d||z
  t        |      t        |       fz         t        j                         }t        |      |k  r|t        |       k  r|t        |       k(  r"t7        dt        |      t        |       fz         |S # t        $ r Y w xY wc c}w )ag  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_FILEr/   --r?   N)stdoutstderrenvrK   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
   timerg   r'   osenvironcopydictlistgslibGSUTIL_PATH_SEQUENTIAL_ISOLATION_FLAGsix
ensure_str	iteritemsrC   
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_timero   envstrpartcmdkvs                      r5   CreateTestProcessesr     s   * / /A.Bs~~&**11r+$)JJ$H$H4&b.	,/@/BBN #iik+-	,	'*<	<	c.)	)
**//
C+=c
'(VF *.  H 	
 "" ../0 J',?(@(ABCD	*
	*
t 	*
   c"1"%.."3fS^^A # * *#	%&
 !OJyy{]"Q&=?*C,=.!## % iikmA 
,	'*<	<	c.)	)@ 3~&&	;s>234 6	U 
 		s   !J J	JJc                       e Zd ZdZ ej
                  dg ededdddeg
      Z	 ej                  dg dd	ei 
      Zd Zd Z e        e       fdZd Zy)TestCommandr   r/   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           	         g }g }g }d}d}d}	t        |      }
t        j                         x}}t        |d||||      }t        |      |
k  rt        t        |            D ]  }||   s||   j	                         d||<   ||   j                         \  }}||   j                  j                          ||   j                  j                          ||   j                  dk7  r|dz  }|j                  t        ||   ||   j                  ||              t        |      |
k  rt        ||||||      }t        |      |
k  rt        j                         |z
  dkD  rt        dt        |      |
|fz         t        |      |	k(  r|dz  }nt        |      }	d}|dkD  rzg }t        t        |            D ]  }||   r	|j                  ||           t        j                         |z
  }t        d	j                  t        t        |            |
             t        j                         }t        j                   d       t        |      |
k  rt        j                         }|r}|D ]x  }|j"                  dk7  s|j                  j%                  d      }t        d|j&                  z         |D ].  }t        |j)                  t*              j-                                0 z |||z
  fS )aZ  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   TrK   )namereturn_coderm   rn   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'   rv   r   r	   pollcommunicaterm   closern   
returncoderC   r   r   formatrL   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_numrm   rn   still_runningelapsedprocess_run_finish_timeresult
new_stderrlines                          r5   RunParallelTestszTestCommand.RunParallelTests  s    LLO#$  78*.))+5-$%?%&%1%1%78IKJ o
!3
3C-.(!\(%;%@%@%B%J
!%X%h/;;=X%%++-X%%++-!,,1
1
$
!;H!E(4X(>(I(I#)#)+	, / 
\	/	/()C)3)5)5);<MO
 
_	 2	299;&*
,?#%79N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#))+, !	 $ "$'::= =r6   c                 "   t        d||z
  d|       t        d||z   t        ||z         |t        |      |t        |      fz         | j                  |       t                |s|rt        d       y|rt        d       |st        d       yy)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           r5   PrintTestResultszTestCommand.PrintTestResults  s     
 557LN O	N	2	2	&)>>	?	u%<=	U#89	;	;= 	-.	G %7Dk	'()*  r6   c                 
   t        |      dkD  st        |      dkD  rgt        |      }t        |      }|j                  |      }t        d       |D ]/  \  }}t        d|j	                         z          t        d|z          1 yy)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         r5   r   zTestCommand.PrintSkippedTests  s     "c*:&;a&?12-.&,,-=>k'.&&dVYY[ !nv%& ( '@r6   c           	         d}d}t         }d}d}| j                  r| j                  D ]  \  }}|dk(  rdt        j                  _        !|dk(  rd})|dk(  rd}1|dk(  rd}9|dt
        z   k(  rd}H|dk(  rt        |      }Y|d	k(  r;t        j                  j                  st        d
      dt        j                  _	        |dk(  sdt        j                  _
         |rt        st        d      t        j                  j                  r/|t        kD  r&| j                  j                  dt               t        }t        t!                     }|rH| j"                  s<t%        dt'        |      z         t%        ddj)                  t        |                   y| j"                  rTg }	| j"                  D ]B  }
|
|v s|
j+                  d      d   |v r|	j-                  d|
z         2|	j-                  |
       D n|D 
cg c]  }
d|
z  	 }	}
t/        j0                          t/        j2                         }|	r>t/        j4                         }|	D ]%  }	 |j7                  |      }|j9                  |       ' |rGtM              }t%        dt'        |      z         t%        ddj)                  t        |                   ytO        jP                         jS                         tN        jT                  k  rd}n%d}tO        jV                  tN        jX                         |rPt        j                  dgddt[        j\                         dz   g       }|j_                          |ja                          d}d}tc              \  }}}}t        j                  j                  sg }tO        jd                  d!|       tO        jd                  d"|       tO        jd                  d#|       tO        jd                  d$|       |xs t'        |      dk  xr | }d%tf        jh                  d&<   |rV|jk                         }tm        |      }t/        jn                  |||'      }|jq                  |      }|js                         }n|dk(  r||z  }g }tu        jt                         } t'        |      t'        |      z   rt%        d(t'        |      t'        |      z   z         ||z   }!|jw                  t        |!D "cg c]  }"|" c}"            }|jk                         }#tm        |#      }t/        jn                  |||'      }|jq                  |      }|js                         }|jx                  }$nd}#d}tu        jt                         | z
  }%||z  }t'        |      }&|&sng }$t{        ||&      }'|&dkD  rH|dkD  rCd)}(|'t         kD  r|(d*z  }(t%        d+j)                  t}        j~                  |(|&|'fz                     nt%        d,|&z         | j                  |||rj                  j                  nd      \  }})| j                  |#||$|%|&||)       |rRj                          |j                          |j                          t%        d-|j                  j                  z         d.tf        jh                  d&<   |r|st                yyc c}
w # t:        t<        f$ r}d|dt?        |      }	 tA        |       t        |      # tB        $ rG}tE        jF                         }tI        jJ                  dd|      }|d|z  z  }Y d}~t        |      d}~ww xY wd}~ww xY wc c}"w )/z)Command entry point for the test command.Frj   Tz-cz-fz-lrl   z-pri   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:

%sNrK      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_optsrr   rs   ru   r~   longHAS_S3_CREDSr   rt   RUN_INTEGRATION_TESTScoverage#_DEFAULT_S3_TEST_PARALLEL_PROCESSESloggerwarnrX   r   argsr   r'   r#   r%   rC   r   installHandler
TestLoaderrB   loadTestsFromNameaddTestsImportErrorAttributeErrorrL   
__import__	Exception	traceback
format_excresubrH   logging	getLoggergetEffectiveLevelINFOdisableERRORtempfile
gettempdirerasestartrb   debugrw   rx   countTestCasesr=   TextTestRunnerrunwasSuccessfulrv   loadTestsFromNamesr*   mintextwrapwrapr   
data_filesfilenamer   stopcombinesaver   )*r.   r   
list_testsr   perform_coverager   oarF   commands_to_testr   loaderrG   command_namesuite_for_current_commandemsgstack_traceerrr   coverage_controllerr   r   rZ   rY   parallel_unit_testsr   run_tests_sequentiallyr4   r   runnerretsequential_start_timesequential_tests_to_run	test_namer   r   r   r   num_processesr1   r   s*                                             r5   
RunCommandzTestCommand.RunCommand  s%   HJ9O}}--$!Q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   :Z+"Z0#	]0\??\:['\:'	\703\2#\:2\77\::\?N)r7   r8   r9   r:   r   CreateCommandSpec	_SYNOPSISr   r~   command_specHelpSpec_DETAILED_HELP_TEXT	help_specr   r   r   r   r,  rd   r6   r5   r   r   h  s    . +**#89, g
>#)X=t+4 25 ',cr6   r   )N);r:   
__future__r   r   r   r   collectionsr   r   rw   r   r   rp   r  r  rv   r   r   	six.movesr	   r|   gslib.cloud_apir
   gslib.commandr   r   gslib.exceptionr   gslib.project_idr   gslib.testsrr   gslib.tests.utilr   r   r   gslib.utils.constantsr   r   gslib.utils.system_utilr   r   r   PY3r   r   r   r   r~   r.  r1  r   r=   rH   rO   rb   rg   r   r   rd   r6   r5   <module>r?     s   - & %  ' "  	  	 
     
   . ! + , .  ) / % ( & . 77	$#$  &( #. 	^| '}^'`' D .=?6 %24j ,0K\H' Hg	  (s   C* *C43C4