
    D                        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ZddlZddlZddl	Z	ddl
Z
ddlZddlmZ ddlmZ 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#c m$Z$ ddl"m%Z% ddl"m&Z& ddl'm(Z( ddl)m*Z* d Z+ G d de,      Z- e%j\                  e$j^                  d       G d de!j`                               Z1y)z*Contains gsutil base unit test case class.    )absolute_import)print_function)division)unicode_literalsN)get_utf8able_str)
project_id)wildcard_iterator)BotoTranslation)CloudApiDelegator)CommandRunner)ApiMapConstants)ApiSelector)DiscardMessagesQueue)
GcsJsonApi)MockLoggingHandler)base)unittest)WorkingDirectory)UTF8)print_to_fdc                     t         j                  s| j                          y	 | j                          y# t        $ r Y yw xY w)zCSuppress IOError when closing sys.stdout or sys.stderr in tearDown.N)sixPY2closeIOError)fds    5platform/gsutil/gslib/tests/testcase/unit_testcase.py_AttemptToCloseSysFdr   1   s7    
 
HHJ
	HHJ	 		s   4 	A A c                        e Zd ZdZed        Zy) GsutilApiUnitTestClassMapFactoryzClass map factory for use in unit tests.

  BotoTranslation is used for all cases so that GSMockBucketStorageUri can
  be used to communicate with the mock XML service.
  c                     t         j                  t        t         j                  t        i}t         j                  t        i}||d}|S )z*Returns a class map for use in unit tests.gss3)r   XMLr
   JSON)clsgs_class_maps3_class_map	class_maps       r   GetClassMapz,GsutilApiUnitTestClassMapFactory.GetClassMapG   sC     	 	L  OO_5L#<8I    N)__name__
__module____qualname____doc__classmethodr+    r,   r   r    r    @   s      r,   r    zNot running integration tests.c                        e Zd ZdZed        Z fdZ fdZ	 	 	 	 	 	 	 ddZedd       Z	edd       Z
edd       Z	 	 	 	 dd	Zdd
Z xZS )GsUtilUnitTestCasez!Base class for gsutil unit tests.c                    t         j                  j                          t        j                  | _        t        | _        t        j                         | _
        t        | j
                  | j                        | _        dt        _        y )N)bucket_storage_uri_classgsutil_api_class_map_factoryzmock-project-id-for-unit-tests)r   GsUtilTestCase
setUpClassutilGSMockBucketStorageUrimock_bucket_storage_urir    !mock_gsutil_api_class_map_factorylogging	getLoggerloggerr   command_runnerr   UNIT_TEST_PROJECT_ID)r'   s    r   r9   zGsUtilUnitTestCase.setUpClass[   se    ""$"&"="=C,LC)""$CJ&!$!<!<%(%J%JLC
 'GJ#r,   c                    t         t        |           g | _        t        j
                  | _        t        j                  | _        t        j                         \  }| _        t        j                  r t        j                  |d      t        _        n!t        j                  |dd      t        _        t        j                         \  }| _        t        j                  r t        j                  |d      t        _        n!t        j                  |dd      t        _        g | _        g | _        t'        j(                         | _        | j*                  j-                  t&        j.                        | _        | j*                  j2                  | _        t        j                         \  }| _        t        j                  |d      | _        t'        j:                  | j8                        | _        | j<                  g| j*                  _        y )Nzw+zutf-8)encoding)superr4   setUpbucket_urissysstdoutstdout_savestderrstderr_savetempfilemkstempstdout_filer   r   osfdopenstderr_fileaccumulated_stdoutaccumulated_stderrr>   r?   root_loggerisEnabledForDEBUGis_debugginghandlerslog_handlers_savelog_handler_filelog_handler_streamStreamHandlertemp_log_handler)selfr   	__class__s     r   rF   zGsUtilUnitTestCase.setUph   sd   	
d)+DzzDzzD#++-B ww99R&cj99R8cj#++-B
ww99R&cj99R8cj D D((*D((55gmmDD!--66D ( 0 0 2B iiD1D#11$2I2IJD!%!6!6 7Dr,   c                 :
   t         t        |           | j                  | j                  _        | j                  j                          | j                  j                          | j                  j                  d       | j                  j                         }| j                  j                          t        j                  | j                         t        j                   j                  d       t        j"                  j                  d       t$        j&                  r=t        j                   j                         }t        j"                  j                         }n=	 t        j                   j                         }t        j"                  j                         }| j,                  D cg c]  }t%        j.                  |       c} | j0                  D cg c]  }t%        j.                  |       c} t%        j.                  t3        |            }t%        j.                  t3        |            }|dj5                  | j0                        z  }|dj5                  | j,                        z  }t7        t        j                          t7        t        j"                         | j8                  t        _        | j:                  t        _        t        j                  | j<                         t        j                  | j>                         t%        j.                  | jA                               }| jB                  rb|r`tE        djG                  |      t        j"                         tE        |t        j"                         tE        dt        j"                         | jB                  rb|r`tE        djG                  |      t        j"                         tE        |t        j"                         tE        dt        j"                         | jB                  rd|ratE        djG                  |      t        j"                         tE        |t        j"                         tE        d	t        j"                         y y y # t(        $ r t        j                   j                  d       t        j"                  j                  d       t        j                   j*                  j                         }t        j"                  j*                  j                         }Y vw xY wc c}w c c}w )
Nr    z==== stdout {} ====
file==== end stdout ====
z==== stderr {} ====
==== end stderr ====
z==== log output {} ====
z==== end log output ====
)$rE   r4   tearDownrZ   rU   rY   r^   flushr   r\   seekreadrP   unlinkr[   rH   rI   rK   r   r   UnicodeDecodeErrorbufferrT   ensure_textrS   r   joinr   rJ   rL   rO   rR   idrX   r   format)r_   
log_outputrI   rK   string_idr`   s         r   rg   zGsUtilUnitTestCase.tearDown   sD   	
d,. $ 6 6D!!  #((--/J!!#IId##$JJOOAJJOOA
wwzz fzz f*"" ,0+B+BC+BS__V+BC+/+B+BC+BS__V+BC__-f56F__-f56F
bggd--..F
bggd--..F$$!!CJ!!CJIIdIId
//$'')
$CV)005CJJG&szz**<V)005CJJG&szz**<Z-44S9

K*3::..SZZ@ (7   *



""'')""'')	*
 DCs   <Q5 'TT5BTTc	           	      x   |xs g }t        j                  dj                  |g|z               }	| j                  r&t	        dj                  |	      | j                         t        j                  j                  d       t        j                  j                  d       t        j                  j                         }
t        j                  j                         }|
r| j                  j                  |
       |r| j                  j                  |       t        j                  j                  d       t        j                  j                  d       t        j                  j                          t        j                  j                          t!               }t#        j$                  |      j'                  |       |r2t#        j$                  |      j)                  t"        j*                         	 t-        |      5  | j.                  j1                  ||||dd       ddd       t        j                  j                  d       t        j                  j                  d       t         j2                  r=t        j                  j                         }
t        j                  j                         }n=	 t        j                  j                         }
t        j                  j                         }t#        j$                  |      j9                  |       |j;                          dj                  d	 t        j<                  |j>                        D              }t        j                  | jA                               }| j                  rW|rUt	        d
j                  ||	      | j                         t	        || j                         t	        d| j                         | j                  rW|
rUt	        dj                  ||	      | j                         t	        |
| j                         t	        d| j                         | j                  rW|rUt	        dj                  ||	      | j                         t	        || j                         t	        d| j                         t        j                  j                  d       t        j                  j                  d       t        j                  j                          t        j                  j                          g }|r|j                  |
       |r|j                  |       |r|j                  |       tC        |      dk(  r|d   S tE        |      S # 1 sw Y   ZxY w# t4        $ r t        j                  j                  d       t        j                  j                  d       t        j                  j6                  j                         }
t        j                  j6                  j                         }Y /w xY w# t        j                  j                  d       t        j                  j                  d       t         j2                  r=t        j                  j                         }
t        j                  j                         }n	 t        j                  j                         }
t        j                  j                         }n# t4        $ r t        j                  j                  d       t        j                  j                  d       t        j                  j6                  j                         }
t        j                  j6                  j                         }Y nw xY wt#        j$                  |      j9                  |       |j;                          dj                  d	 t        j<                  |j>                        D              }t        j                  | jA                               }| j                  rW|rUt	        d
j                  ||	      | j                         t	        || j                         t	        d| j                         | j                  rW|
rUt	        dj                  ||	      | j                         t	        |
| j                         t	        d| j                         | j                  rW|rUt	        dj                  ||	      | j                         t	        || j                         t	        d| j                         t        j                  j                  d       t        j                  j                  d       t        j                  j                          t        j                  j                          w xY w)a  Method for calling gslib.command_runner.CommandRunner.

    Passes parallel_operations=False for all tests, optionally saving/returning
    stdout output. We run all tests multi-threaded, to exercise those more
    complicated code paths.
    TODO: Change to run with parallel_operations=True for all tests. At
    present when you do this it causes many test failures.

    Args:
      command_name: The name of the command being run.
      args: Command-line args (arg0 = actual arg, not command name ala bash).
      headers: Dictionary containing optional HTTP headers to pass to boto.
      debug: Debug level to pass in to boto connection (range 0..3).
      return_stdout: If True, will save and return stdout produced by command.
      return_stderr: If True, will save and return stderr produced by command.
      return_log_handler: If True, will return a MockLoggingHandler instance
           that was attached to the command's logger while running.
      cwd: The working directory that should be switched to before running the
           command. The working directory will be reset back to its original
           value after running the command. If not specified, the working
           directory is left unchanged.

    Returns:
      One or a tuple of requested return values, depending on whether
      return_stdout, return_stderr, and/or return_log_handler were specified.
      Return Types:
        stdout - str (binary in Py2, text in Py3)
        stderr - str (binary in Py2, text in Py3)
        log_handler - MockLoggingHandler
     z
RunCommand of {}
rc   r   F)argsheadersdebugparallel_operationsdo_shutdownN
c              3   T   K   | ]   \  }}|rd |z  dj                  |      z    " yw)z%s:
  z
  N)ro   ).0levelrecordss      r   	<genexpr>z0GsUtilUnitTestCase.RunCommand.<locals>.<genexpr>  s2       HneW e
fkk'2
2 Hs   &(z#==== logging RunCommand {} {} ====
z
==== end logging ====
z"==== stdout RunCommand {} {} ====
re   z"==== stderr RunCommand {} {} ====
rf      )#r   rn   ro   rX   r   rq   rL   rH   rI   ri   rK   rj   rS   appendrT   truncater   r>   r?   
addHandlersetLevelrW   r   rA   RunNamedCommandr   rl   rm   removeHandlerr   	iteritemsmessagesrp   lentuple)r_   command_namerw   rx   ry   return_stdoutreturn_stderrreturn_log_handlercwdcommand_linerI   rK   mock_log_handlerrr   rt   	to_returns                   r   
RunCommandzGsUtilUnitTestCase.RunCommand   s   N :2D??388\NT,A#BCL(//='') JJOOAJJOOAZZ__FZZ__F
$$V,
$$V,JJOOAJJOOAJJJJ)+l#../?@%..w}}=8C ++L154;27@E8= 	, 	? ! 
jjooa	jjooa	""	,::??$&::??$& %334DE99  #.>.G.G H j
 OODGGI&c			z:AA))	+ 	JT%5%56/d6F6FG			v9@@))	+ 	F!1!12,43C3CD			v9@@))	+ 	F!1!12,43C3CD 
jjooa	jjooa	jj	jjIvv'(
9~q\E ! " " 	,
**//!

**//!
::$$))+&::$$))+&		, 
jjooa	jjooa	""	,::??$&::??$&! 	,
**//!

**//!
::$$))+&::$$))+&		,
 %334DE99  #.>.G.G H j
 OODGGI&c			z:AA))	+ 	JT%5%56/d6F6FG			v9@@))	+ 	F!1!12,43C3CD			v9@@))	+ 	F!1!12,43C3CD 
jjooa	jjooa	jj	jjs^   2X" ="U7X" 3<V 7V<X" BXX"Bf9/<[,+f9,B^f9^H3f9c                    t         j                  | j                  j                         t         j                  t
        j                  t
        j                  gt
        j                  gdt         j                  t
        j                  t
        j                  di}t        | j                  || j                  t               |      S )Nr"   )ry   )r   API_MAPr=   r+   SUPPORT_MAPr   r%   r&   DEFAULT_MAPr   r<   r@   r   )r'   ry   gsutil_api_maps      r   MakeGsUtilApiz GsUtilUnitTestCase.MakeGsUtilApiA  s     	22>>@##??K$4$45??#&
 	##""//&
N S88+ ZZ13#(	* *r,   c                     |}t        |d      r|j                  }t        j                  || j	                  |      |      S )a  Convenience method for instantiating a test instance of WildcardIterator.

    This makes it unnecessary to specify all the params of that class
    (like bucket_storage_uri_class=mock_storage_service.MockBucketStorageUri).
    Also, naming the factory method this way makes it clearer in the test code
    that WildcardIterator needs to be set up for testing.

    Args are same as for wildcard_iterator.wildcard_iterator(), except
    there are no class args for bucket_storage_uri_class or gsutil_api_class.

    Args:
      uri_or_str: StorageUri or string representing the wildcard string.
      exclude_tuple: (base_url, exclude_pattern), where base_url is
                     top-level URL to list; exclude_pattern is a regex
                     of paths to ignore during iteration.
      debug: debug level to pass to the underlying connection (0..3)

    Returns:
      WildcardIterator, over which caller can iterate.
    uri)exclude_tuple)hasattrr   r	   CreateWildcardIteratorr   )r'   
uri_or_strr   ry   
uri_strings        r   _test_wildcard_iteratorz*GsUtilUnitTestCase._test_wildcard_iteratorV  sD    . Jz5!>>j33J474E4Ee4LBOQ Qr,   c                 P    t        j                  | |||t        j                        S )a  Convenience method for instantiating a testing instance of StorageUri.

    This makes it unnecessary to specify
    bucket_storage_uri_class=mock_storage_service.MockBucketStorageUri.
    Also naming the factory method this way makes it clearer in the test
    code that StorageUri needs to be set up for testing.

    Args, Returns, and Raises are same as for boto.storage_uri(), except there's
    no bucket_storage_uri_class arg.

    Args:
      uri_str: Uri string to create StorageUri for.
      default_scheme: Default scheme for the StorageUri
      debug: debug level to pass to the underlying connection (0..3)
      validate: If True, validate the resource that the StorageUri refers to.

    Returns:
      StorageUri based on the arguments.
    )botostorage_urir:   r;   )uri_strdefault_schemery   validates       r   _test_storage_uriz$GsUtilUnitTestCase._test_storage_uriu  s(    * G^UH 779 9r,   c                    |xs | j                  d      }t        j                  |d|j                         dt        j
                        }|j                  |       | j                  j                  |       	 t        |       t        |      D ];  \  }}| j                  ||dj                  |      j                  t                      = |S # t        $ r0 t        |      D cg c]  }| j                  d       nc c}w }}Y w xY w)	aa  Creates a test bucket.

    The bucket and all of its contents will be deleted after the test.

    Args:
      bucket_name: Create the bucket with this name. If not provided, a
                   temporary test bucket name is constructed.
      test_objects: The number of objects that should be placed in the bucket or
                    a list of object names to place in the bucket. Defaults to
                    0.
      storage_class: storage class to use. If not provided we us standard.
      provider: string provider to use, default gs.

    Returns:
      StorageUri for the created bucket.
    bucketz://F)suppress_consec_slashesr6   )storage_classobjztest {})
bucket_uriobject_namecontents)MakeTempNamer   r   lowerr:   r;   create_bucketrG   r   iter	TypeErrorrange	enumerateCreateObjectrq   encoder   )	r_   bucket_nametest_objectsr   providerr   _inames	            r   CreateBucketzGsUtilUnitTestCase.CreateBucket  s   * <!2!28!<K!!{0023 %!%!<!<>J =9J'M
< \*4
:$(!*!1!1!!4!;!;D!A  C +   M8=l8KL8K1d''.8KLlLMs   =C D)DDDc                     |xs | j                  | j                        }|xs | j                  d      }|j                  |      }||j	                  |       |S )a+  Creates a test object.

    Args:
      bucket_uri: The URI of the bucket to place the object in. If not
                  specified, a new temporary bucket is created.
      object_name: The name to use for the object. If not specified, a temporary
                   test object name is constructed.
      contents: The contents to write to the object. If not specified, the key
                is not written to, which means that it isn't actually created
                yet on the server.

    Returns:
      A StorageUri for the created object.
    )r   r   )r   default_providerr   clone_replace_nameset_contents_from_string)r_   r   r   r   key_uris        r   r   zGsUtilUnitTestCase.CreateObject  s`     Pt00$:O:O0PJ9!2!25!9K++K8G&&x0Nr,   )NNr   FFFN)r   )Nr   )rd   r   T)Nr   Nr#   )NNN)r-   r.   r/   r0   r1   r9   rF   rg   r   r   r   staticmethodr   r   r   __classcell__)r`   s   @r   r4   r4   W   s    )
G 
G8:2Al $$$)FP * *( Q Q< 9 90  $ !!% 	$Lr,   r4   )2r0   
__future__r   r   r   r   r>   rP   rH   rM   r   r   
boto.utilsr   gslibr   r	   gslib.boto_translationr
   gslib.cloud_api_delegatorr   gslib.command_runnerr   gslib.cs_api_mapr   r   gslib.discard_messages_queuer   gslib.gcs_json_apir    gslib.tests.mock_logging_handlerr   gslib.tests.testcaser   gslib.tests.utiltestsr:   r   r   gslib.utils.constantsr   gslib.utils.text_utilr   r   objectr    
skipUnlessRUN_UNIT_TESTSr8   r4   r2   r,   r   <module>r      s    1 & %  '  	 
  
  '  # 2 7 . , ( = ) ? %   % - & -	v . T((*JKo,, o Lor,   