
    &                         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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d Zd Z G d dej8                        Zy)4Base test case class for unit and integration tests.    )absolute_import)print_function)division)unicode_literals)wrapsN)unittest)UTF8)NA_ID)NA_MODE?   c                      t        | dd       | S )z.Wrapper for cases that are not parallelizable.is_parallelizableF)setattr)tests    ,platform/gsutil/gslib/tests/testcase/base.pyNotParallelizabler   )   s     
$#U+	+    c                 <     t                fd       }d|_        |S )zFWrapper function for cases that require running in a separate process.c                       | i |S N )argskwargsfuncs     r   RequiresIsolationFuncz0RequiresIsolation.<locals>.RequiresIsolationFunc3   s       r   T)r   requires_isolation)r   r   s   ` r   RequiresIsolationr   0   s,     	;! ! .2*	r   c                   l    e Zd ZdZd Zd Zd Zd Zd ZddZ	ddZ
dd
ZddZd	d	d	d	eeefdZddZy	)GsUtilTestCaser   c                 T   t         j                  r"| j                  | _        | j                  | _        t        j                  rd| _        d| _	        d| _
        g | _        y t        j                  j                  ddd      j                         | _        d| _	        d| _
        g | _        y )	NXMLs3amzGSUtil
prefer_apiJSONgsgoog)sixPY2assertRegexpMatchesassertRegexassertNotRegexpMatchesassertNotRegexutilRUN_S3_TESTStest_apidefault_providerprovider_custom_metabotoconfiggetuppertempdirsselfs    r   setUpzGsUtilTestCase.setUp>   s    
ww11d 77ddm"d"'d
 DM kkoohfEKKMdm"d"(dDMr   c                     | j                   r?| j                   j                         }t        j                  |d       | j                   r>y y )NT)ignore_errors)r9   popshutilrmtree)r;   tmpdirs     r   tearDownzGsUtilTestCase.tearDownL   s2    
--}}  "fmmF$/ --r   c                 F    | j                  |j                  d      |       y )N
)assertEqualcount)r;   textnumliness      r   assertNumLineszGsUtilTestCase.assertNumLinesQ   s    TZZ%x0r   c                     | j                   S r   )_testMethodNamer:   s    r   GetTestMethodNamez GsUtilTestCase.GetTestMethodNameT   s    r   c                 2    dt        j                  d      z  S )z<Creates a random string of hex characters 8 characters long.z%08xl        )random	randranger:   s    r   MakeRandomTestStringz#GsUtilTestCase.MakeRandomTestStringW   s    F$$V,,,r   c                 ^   dj                  || j                         |      }|dt        dz
   }dj                  || j                               }t	        |      t	        |      z   }|r*|dk(  r |t        kD  r| j                  d|z   |z          ||z  }|dk(  rt        j                  |      }|S )	ag  Creates a temporary name that is most-likely unique.

    Args:
      kind (str): A string indicating what kind of test name this is.
      prefix (str): Prefix prepended to the temporary name.
      suffix (str): Suffix string appended to end of temporary name.

    Returns:
      (str) The temporary name. If `kind` was "bucket", the temporary name may
      have coerced this string, including the supplied `prefix`, such that it
      contains only characters that are valid across all supported storage
      providers (e.g. replacing "_" with "-", converting uppercase letters to
      lowercase, etc.).
    z#{prefix}gsutil-test-{method}-{kind})prefixmethodkindN   z{name}-{rand})namerandbucketzTried to create a psuedo-random bucket name with a specific suffix, but the generated name was too long and there was not enough room for the suffix. Please use shorter strings or perform name randomization manually.
Requested name: )formatrM   MAX_BUCKET_LENGTHrQ   lenfailr0   MakeBucketNameValid)r;   rU   rS   suffixrW   total_name_lens         r   MakeTempNamezGsUtilTestCase.MakeTempName[   s     177d446T 8 CD'"R'(D!!t$2K2K2M!NDYV,N		n/@@		= @DD GMM	N
 fndx%%d+dKr   c                 .    | j                  ||      dz   S )NrS   u   材)ra   )r;   rU   rS   s      r   MakeTempUnicodeNamez"GsUtilTestCase.MakeTempUnicodeName}   s    T&1E99r   Nc                    t        j                  | j                  d            }| j                  j	                  |       	 t        |       t        |      D ]1  \  }}|}|d|z  j                  d      }| j                  |||       3 |S # t        $ r0 t        |      D cg c]  }| j                  d       nc c}w }}Y yw xY w)an  Creates a temporary directory on disk.

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

    Args:
      test_files: The number of test files to place in the directory or a list
                  of test file names.
      contents: The contents for each generated test file.

    Returns:
      The path to the new temporary directory.
    	directoryrc   fileztest %dascii)rB   	file_namecontents)tempfilemkdtempra   r9   appenditer	TypeErrorrange	enumerateencodeCreateTempFile)r;   
test_filesrj   rB   _irW   contents_files           r   CreateTempDirzGsUtilTestCase.CreateTempDir   s     T%6%6{%CDFMM J
: Z(4m		"Q..w7
4-P	 )
 M  J7<Z7HI7H!D%%f-7HIjIJs   B C$B=<CCc                 8   |xs | j                         }|xs | j                  d      }t        |t        j                        r!t
        j                  j                  ||      }n t        j                  j                  |g| }t        j                  |       |S )a
  Creates a temporary fifo file on disk. Should not be used on Windows.

    Args:
      tmpdir: The temporary directory to place the file in. If not specified, a
          new temporary directory is created.
      file_name: The name to use for the file. If not specified, a temporary
          test file name is constructed. This can also be a tuple, where
          ('dir', 'foo') means to create a file named 'foo' inside a
          subdirectory named 'dir'.

    Returns:
      The path to the new temporary fifo.
    fifo)	rx   ra   
isinstancer*   string_typesospathjoinmkfifo)r;   rB   ri   fpaths       r   CreateTempFifozGsUtilTestCase.CreateTempFifo   sx     +t))+F6T..v6I)S--.ggll69-eggll6.I.eIIeLr   c                 
   t        j                  |xs | j                               }|xs | j                  t	        d            }t        |t         j                  t         j                  f      r4t        j                  j                  |t        j                  |            }n:t        t         j                  |      }t        j                  j                  |g| }t        j                  j                  t        j                  j                  |            s2t        j                  t        j                  j                  |             t        |t         j                        r|j                  t               }t#        |d      5 }	||n| j                  t	        d            }t        |t$              rt'        |      }nt        j(                  |      }|	j+                  |       ddd       |t        j,                  |||f       |t.        k7  st1        |      t.        k7  r t        j2                  ||t1        |             t1        |      t4        k7  r t        j6                  |t1        |d             |S # 1 sw Y   xY w)a  Creates a temporary file on disk.

    Note: if mode, uid, or gid are present, they must be validated by
    ValidateFilePermissionAccess and ValidatePOSIXMode before calling this
    function.

    Args:
      tmpdir: The temporary directory to place the file in. If not specified, a
              new temporary directory is created.
      contents: The contents to write to the file. If not specified, a test
                string is constructed and written to the file. Since the file
                is opened 'wb', the contents must be bytes.
      file_name: The name to use for the file. If not specified, a temporary
                 test file name is constructed. This can also be a tuple, where
                 ('dir', 'foo') means to create a file named 'foo' inside a
                 subdirectory named 'dir'.
      mtime: The modification time of the file in POSIX time (seconds since
             UTC 1970-01-01). If not specified, this defaults to the current
             system time.
      mode: The POSIX mode for the file. Must be a base-8 3-digit integer
            represented as a string.
      uid: A POSIX user ID.
      gid: A POSIX group ID.

    Returns:
      The path to the new temporary file.
    rg   wbNrj      )r*   
ensure_strrx   ra   strr{   	text_typebinary_typer}   r~   r   mapisdirdirnamemakedirsdecoder
   open	bytearraybytesensure_binarywriteutimer   intchownr   chmod)
r;   rB   rj   ri   mtimemodeuidgidr   fs
             r   rs   zGsUtilTestCase.CreateTempFile   s   H ^^F:d&8&8&:;F;T..s6{;I)cmmS__=>ggll63>>)#<=ecnni0iggll6.I.e77==/0kk"''//%()%)ll4 e	eT	a&2(8I8I
j/9h	Hi	(?$$X.ggh 
 hhuuen%
e|s3x5(hhuc3s8$
4yGhhuc$l#L 
	s   A!I99Jc                 <   t        |t        j                        rt        j                  ||      }n.t        j                  |j
                  |j                  |z        }|j                  |      s+|xs d}|d|j
                  d|}| j                  |      y)ar  Like assertRegexpMatches, but allows specifying additional re flags.

    Args:
      text: The text in which to search for pattern.
      pattern: The pattern to search for; should be either a string or compiled
          regex returned from re.compile().
      msg: The message to be displayed if pattern is not found in text. The
          values for pattern and text will be included after this message.
      flags: Additional flags from the re module to be included when compiling
          pattern. If pattern is a regex that was compiled with existing flags,
          these, flags will be added via a bitwise-or.
    )flagszRegex didn't matchz: z not found in N)	r{   r*   r|   recompilepatternr   searchfailureException)r;   rH   r   msgr   failure_msgs         r   assertRegexpMatchesWithFlagsz+GsUtilTestCase.assertRegexpMatchesWithFlags   s     '3++,

7%0g

7??'--%2GHg>>$00k0;W__046k!!+..	  r   ) r   )r   )r   N)NN)Nr   )__name__
__module____qualname____doc__r<   rC   rJ   rM   rQ   ra   rd   rx   r   r   r   rs   r   r   r   r   r    r    ;   sU    <0
1 -D:40 !"#!?B/r   r    )r   
__future__r   r   r   r   	functoolsr   os.pathr}   rO   r   r@   rk   r*   r5   gslib.tests.utiltestsr0   r	   gslib.utils.constantsr
   gslib.utils.posix_utilr   r   r[   r   r   TestCaser    r   r   r   <module>r      sd    ; & %  '    	   
    % & ( * L/X&& L/r   