OLD | NEW |
(Empty) | |
| 1 # Copyright 2013 Google Inc. All Rights Reserved. |
| 2 # |
| 3 # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 # you may not use this file except in compliance with the License. |
| 5 # You may obtain a copy of the License at |
| 6 # |
| 7 # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 # |
| 9 # Unless required by applicable law or agreed to in writing, software |
| 10 # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 # See the License for the specific language governing permissions and |
| 13 # limitations under the License. |
| 14 |
| 15 """Contains gsutil base unit test case class.""" |
| 16 |
| 17 import os.path |
| 18 import sys |
| 19 import tempfile |
| 20 |
| 21 import boto |
| 22 |
| 23 from gslib import wildcard_iterator |
| 24 from gslib.command_runner import CommandRunner |
| 25 from gslib.project_id import ProjectIdHandler |
| 26 import gslib.tests.util as util |
| 27 from gslib.tests.util import unittest |
| 28 from tests.integration.s3 import mock_storage_service |
| 29 import base |
| 30 |
| 31 |
| 32 CURDIR = os.path.abspath(os.path.dirname(__file__)) |
| 33 TESTS_DIR = os.path.split(CURDIR)[0] |
| 34 GSLIB_DIR = os.path.split(TESTS_DIR)[0] |
| 35 GSUTIL_DIR = os.path.split(GSLIB_DIR)[0] |
| 36 BOTO_DIR = os.path.join(GSUTIL_DIR, 'boto') |
| 37 |
| 38 |
| 39 class GSMockConnection(mock_storage_service.MockConnection): |
| 40 |
| 41 def __init__(self, *args, **kwargs): |
| 42 kwargs['provider'] = 'gs' |
| 43 super(GSMockConnection, self).__init__(*args, **kwargs) |
| 44 |
| 45 mock_connection = GSMockConnection() |
| 46 |
| 47 |
| 48 class GSMockBucketStorageUri(mock_storage_service.MockBucketStorageUri): |
| 49 |
| 50 def connect(self, access_key_id=None, secret_access_key=None): |
| 51 return mock_connection |
| 52 |
| 53 |
| 54 @unittest.skipUnless(util.RUN_UNIT_TESTS, |
| 55 'Not running integration tests.') |
| 56 class GsUtilUnitTestCase(base.GsUtilTestCase): |
| 57 """Base class for gsutil unit tests.""" |
| 58 |
| 59 @classmethod |
| 60 def setUpClass(cls): |
| 61 base.GsUtilTestCase.setUpClass() |
| 62 cls.mock_bucket_storage_uri = GSMockBucketStorageUri |
| 63 cls.proj_id_handler = ProjectIdHandler() |
| 64 config_file_list = boto.pyami.config.BotoConfigLocations |
| 65 # Use "gsutil_test_commands" as a fake UserAgent. This value will never be |
| 66 # sent via HTTP because we're using MockStorageService here. |
| 67 cls.command_runner = CommandRunner(GSUTIL_DIR, BOTO_DIR, |
| 68 config_file_list, 'gsutil_test_commands', |
| 69 cls.mock_bucket_storage_uri) |
| 70 |
| 71 def setUp(self): |
| 72 super(GsUtilUnitTestCase, self).setUp() |
| 73 self.bucket_uris = [] |
| 74 |
| 75 def RunCommand(self, command_name, args=None, headers=None, debug=0, |
| 76 test_method=None, return_stdout=False, cwd=None): |
| 77 """ |
| 78 Method for calling gslib.command_runner.CommandRunner, passing |
| 79 parallel_operations=False for all tests, optionally saving/returning stdout |
| 80 output. We run all tests multi-threaded, to exercise those more complicated |
| 81 code paths. |
| 82 TODO: change to run with parallel_operations=True for all tests. At |
| 83 present when you do this it causes many test failures. |
| 84 |
| 85 Args: |
| 86 command_name: The name of the command being run. |
| 87 args: Command-line args (arg0 = actual arg, not command name ala bash). |
| 88 headers: Dictionary containing optional HTTP headers to pass to boto. |
| 89 debug: Debug level to pass in to boto connection (range 0..3). |
| 90 parallel_operations: Should command operations be executed in parallel? |
| 91 test_method: Optional general purpose method for testing purposes. |
| 92 Application and semantics of this method will vary by |
| 93 command and test type. |
| 94 cwd: The working directory that should be switched to before running the |
| 95 command. The working directory will be reset back to its original |
| 96 value after running the command. If not specified, the working |
| 97 directory is left unchanged. |
| 98 return_stdout: If true will save and return stdout produced by command. |
| 99 """ |
| 100 if util.VERBOSE_OUTPUT: |
| 101 sys.stderr.write('\nRunning test of %s %s\n' % |
| 102 (command_name, ' '.join(args))) |
| 103 if return_stdout: |
| 104 # Redirect stdout temporarily, to save output to a file. |
| 105 fh, outfile = tempfile.mkstemp() |
| 106 os.close(fh) |
| 107 elif not util.VERBOSE_OUTPUT: |
| 108 outfile = os.devnull |
| 109 else: |
| 110 outfile = None |
| 111 |
| 112 stdout_sav = sys.stdout |
| 113 output = None |
| 114 cwd_sav = None |
| 115 try: |
| 116 cwd_sav = os.getcwd() |
| 117 except OSError: |
| 118 # This can happen if the current working directory no longer exists. |
| 119 pass |
| 120 try: |
| 121 if outfile: |
| 122 fp = open(outfile, 'w') |
| 123 sys.stdout = fp |
| 124 if cwd: |
| 125 os.chdir(cwd) |
| 126 self.command_runner.RunNamedCommand( |
| 127 command_name, args=args, headers=headers, debug=debug, |
| 128 parallel_operations=False, test_method=test_method) |
| 129 finally: |
| 130 if cwd and cwd_sav: |
| 131 os.chdir(cwd_sav) |
| 132 if outfile: |
| 133 fp.close() |
| 134 sys.stdout = stdout_sav |
| 135 with open(outfile, 'r') as f: |
| 136 output = f.read() |
| 137 if return_stdout: |
| 138 os.unlink(outfile) |
| 139 |
| 140 if output is not None and return_stdout: |
| 141 return output |
| 142 |
| 143 @classmethod |
| 144 def _test_wildcard_iterator(cls, uri_or_str, debug=0): |
| 145 """ |
| 146 Convenience method for instantiating a testing instance of |
| 147 WildCardIterator, without having to specify all the params of that class |
| 148 (like bucket_storage_uri_class=mock_storage_service.MockBucketStorageUri). |
| 149 Also naming the factory method this way makes it clearer in the test code |
| 150 that WildcardIterator needs to be set up for testing. |
| 151 |
| 152 Args are same as for wildcard_iterator.wildcard_iterator(), except there's |
| 153 no bucket_storage_uri_class arg. |
| 154 |
| 155 Returns: |
| 156 WildcardIterator.IterUris(), over which caller can iterate. |
| 157 """ |
| 158 return wildcard_iterator.wildcard_iterator( |
| 159 uri_or_str, cls.proj_id_handler, cls.mock_bucket_storage_uri, |
| 160 debug=debug) |
| 161 |
| 162 @staticmethod |
| 163 def _test_storage_uri(uri_str, default_scheme='file', debug=0, |
| 164 validate=True): |
| 165 """ |
| 166 Convenience method for instantiating a testing |
| 167 instance of StorageUri, without having to specify |
| 168 bucket_storage_uri_class=mock_storage_service.MockBucketStorageUri. |
| 169 Also naming the factory method this way makes it clearer in the test |
| 170 code that StorageUri needs to be set up for testing. |
| 171 |
| 172 Args, Returns, and Raises are same as for boto.storage_uri(), except there's |
| 173 no bucket_storage_uri_class arg. |
| 174 """ |
| 175 return boto.storage_uri(uri_str, default_scheme, debug, validate, |
| 176 GSMockBucketStorageUri) |
| 177 |
| 178 def CreateBucket(self, bucket_name=None, test_objects=0, storage_class=None): |
| 179 """Creates a test bucket. |
| 180 |
| 181 The bucket and all of its contents will be deleted after the test. |
| 182 |
| 183 Args: |
| 184 bucket_name: Create the bucket with this name. If not provided, a |
| 185 temporary test bucket name is constructed. |
| 186 test_objects: The number of objects that should be placed in the bucket or |
| 187 a list of object names to place in the bucket. Defaults to |
| 188 0. |
| 189 storage_class: storage class to use. If not provided we us standard. |
| 190 |
| 191 Returns: |
| 192 StorageUri for the created bucket. |
| 193 """ |
| 194 bucket_name = bucket_name or self.MakeTempName('bucket') |
| 195 bucket_uri = boto.storage_uri( |
| 196 'gs://%s' % bucket_name.lower(), |
| 197 suppress_consec_slashes=False, |
| 198 bucket_storage_uri_class=GSMockBucketStorageUri) |
| 199 bucket_uri.create_bucket(storage_class=storage_class) |
| 200 self.bucket_uris.append(bucket_uri) |
| 201 try: |
| 202 iter(test_objects) |
| 203 except TypeError: |
| 204 test_objects = [self.MakeTempName('obj') for _ in range(test_objects)] |
| 205 for i, name in enumerate(test_objects): |
| 206 self.CreateObject(bucket_uri=bucket_uri, object_name=name, |
| 207 contents='test %d' % i) |
| 208 return bucket_uri |
| 209 |
| 210 def CreateObject(self, bucket_uri=None, object_name=None, contents=None): |
| 211 """Creates a test object. |
| 212 |
| 213 Args: |
| 214 bucket: The URI of the bucket to place the object in. If not specified, a |
| 215 new temporary bucket is created. |
| 216 object_name: The name to use for the object. If not specified, a temporary |
| 217 test object name is constructed. |
| 218 contents: The contents to write to the object. If not specified, the key |
| 219 is not written to, which means that it isn't actually created |
| 220 yet on the server. |
| 221 |
| 222 Returns: |
| 223 A StorageUri for the created object. |
| 224 """ |
| 225 bucket_uri = bucket_uri or self.CreateBucket() |
| 226 object_name = object_name or self.MakeTempName('obj') |
| 227 key_uri = bucket_uri.clone_replace_name(object_name) |
| 228 if contents is not None: |
| 229 key_uri.set_contents_from_string(contents) |
| 230 return key_uri |
OLD | NEW |