Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(98)

Side by Side Diff: third_party/gsutil/gslib/test_wildcard_iterator.py

Issue 10199002: Upgrade gsutil to 3.4 (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Addressed comments Created 8 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « third_party/gsutil/gslib/test_util.py ('k') | third_party/gsutil/gslib/thread_pool.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 # 2 #
3 # Copyright 2010 Google Inc. 3 # Copyright 2010 Google Inc.
4 # 4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a 5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the 6 # copy of this software and associated documentation files (the
7 # "Software"), to deal in the Software without restriction, including 7 # "Software"), to deal in the Software without restriction, including
8 # without limitation the rights to use, copy, modify, merge, publish, dis- 8 # without limitation the rights to use, copy, modify, merge, publish, dis-
9 # tribute, sublicense, and/or sell copies of the Software, and to permit 9 # tribute, sublicense, and/or sell copies of the Software, and to permit
10 # persons to whom the Software is furnished to do so, subject to the fol- 10 # persons to whom the Software is furnished to do so, subject to the fol-
(...skipping 19 matching lines...) Expand all
30 import time 30 import time
31 import unittest 31 import unittest
32 32
33 # Put local libs at front of path so tests will run latest lib code rather 33 # Put local libs at front of path so tests will run latest lib code rather
34 # than whatever code is found on user's PYTHONPATH. 34 # than whatever code is found on user's PYTHONPATH.
35 sys.path.insert(0, '.') 35 sys.path.insert(0, '.')
36 sys.path.insert(0, 'boto') 36 sys.path.insert(0, 'boto')
37 from boto import InvalidUriError 37 from boto import InvalidUriError
38 from gslib import test_util 38 from gslib import test_util
39 from gslib import wildcard_iterator 39 from gslib import wildcard_iterator
40 from wildcard_iterator import ResultType 40 from gslib.project_id import ProjectIdHandler
41 from tests.s3 import mock_storage_service
42 from wildcard_iterator import ContainsWildcard
41 43
42 44
43 class CloudWildcardIteratorTests(unittest.TestCase): 45 class CloudWildcardIteratorTests(unittest.TestCase):
44 """CloudWildcardIterator test suite""" 46 """CloudWildcardIterator test suite"""
45 47
46 def GetSuiteDescription(self): 48 def GetSuiteDescription(self):
47 return 'CloudWildcardIterator test suite' 49 return 'CloudWildcardIterator test suite'
48 50
49 @classmethod 51 @classmethod
50 def SetUpClass(cls): 52 def SetUpClass(cls):
51 """Creates 2 mock buckets, each containing 3 objects""" 53 """Creates 2 mock buckets, each containing 4 objects, including 1 nested."""
52 54 cls.immed_child_obj_names = ['abcd', 'abdd', 'ade$']
55 cls.all_obj_names = ['abcd', 'abdd', 'ade$', 'nested1/nested2/xyz1',
56 'nested1/nested2/xyz2']
53 cls.base_uri_str = 'gs://gslib_test_%d' % int(time.time()) 57 cls.base_uri_str = 'gs://gslib_test_%d' % int(time.time())
54 cls.test_bucket0_uri, cls.test_bucket0_obj_uri_strs = ( 58 cls.test_bucket0_uri, cls.test_bucket0_obj_uri_strs = (
55 cls.__SetUpOneMockBucket(0) 59 cls.__SetUpOneMockBucket(0)
56 ) 60 )
57 cls.test_bucket1_uri, cls.test_bucket1_obj_uri_strs = ( 61 cls.test_bucket1_uri, cls.test_bucket1_obj_uri_strs = (
58 cls.__SetUpOneMockBucket(1) 62 cls.__SetUpOneMockBucket(1)
59 ) 63 )
60 cls.created_test_data = True 64 cls.created_test_data = True
61 65
62 @classmethod 66 @classmethod
63 def __SetUpOneMockBucket(cls, bucket_num): 67 def __SetUpOneMockBucket(cls, bucket_num):
64 """Creates a mock bucket containing 3 objects. 68 """Creates a mock bucket containing 4 objects, including 1 nested.
65
66 Args: 69 Args:
67 bucket_num: number for building bucket name. 70 bucket_num: Number for building bucket name.
68 71
69 Returns: 72 Returns:
70 tuple: (bucket name, set of object URI strings) 73 tuple: (bucket name, set of object URI strings).
71 """ 74 """
72
73 bucket_uri = test_util.test_storage_uri( 75 bucket_uri = test_util.test_storage_uri(
74 '%s_%s' % (cls.base_uri_str, bucket_num)) 76 '%s_%s' % (cls.base_uri_str, bucket_num))
75 bucket_uri.create_bucket() 77 bucket_uri.create_bucket()
76 obj_uri_strs = set() 78 obj_uri_strs = set()
77 for obj_name in ['abcd', 'abdd', 'ade$']: 79 for obj_name in cls.all_obj_names:
78 obj_uri = test_util.test_storage_uri('%s%s' % (bucket_uri, obj_name)) 80 obj_uri = test_util.test_storage_uri('%s%s' % (bucket_uri, obj_name))
79 key = obj_uri.new_key() 81 key = obj_uri.new_key()
80 key.set_contents_from_string('') 82 key.set_contents_from_string('')
81 obj_uri_strs.add(str(obj_uri)) 83 obj_uri_strs.add(str(obj_uri))
82 return (bucket_uri, obj_uri_strs) 84 return (bucket_uri, obj_uri_strs)
83 85
84 @classmethod 86 @classmethod
85 def TearDownClass(cls): 87 def TearDownClass(cls):
86 """Cleans up bucket and objects created by SetUpClass""" 88 """Cleans up bucket and objects created by SetUpClass"""
87
88 if hasattr(cls, 'created_test_data'): 89 if hasattr(cls, 'created_test_data'):
89 for test_obj_uri_str in cls.test_bucket0_obj_uri_strs: 90 for test_obj_uri_str in cls.test_bucket0_obj_uri_strs:
90 test_util.test_storage_uri(test_obj_uri_str).delete_key() 91 test_util.test_storage_uri(test_obj_uri_str).delete_key()
91 for test_obj_uri_str in cls.test_bucket1_obj_uri_strs: 92 for test_obj_uri_str in cls.test_bucket1_obj_uri_strs:
92 test_util.test_storage_uri(test_obj_uri_str).delete_key() 93 test_util.test_storage_uri(test_obj_uri_str).delete_key()
93 cls.test_bucket0_uri.delete_bucket() 94 cls.test_bucket0_uri.delete_bucket()
94 cls.test_bucket1_uri.delete_bucket() 95 cls.test_bucket1_uri.delete_bucket()
95 96
96 def TestNoOpObjectIterator(self): 97 def TestNoOpObjectIterator(self):
97 """Tests that bucket-only URI iterates just that one URI""" 98 """Tests that bucket-only URI iterates just that one URI"""
98 99 results = list(
99 results = list(test_util.test_wildcard_iterator(self.test_bucket0_uri, 100 test_util.test_wildcard_iterator(self.test_bucket0_uri).IterUris())
100 ResultType.URIS))
101 self.assertEqual(1, len(results)) 101 self.assertEqual(1, len(results))
102 self.assertEqual(str(self.test_bucket0_uri), str(results[0])) 102 self.assertEqual(str(self.test_bucket0_uri), str(results[0]))
103 103
104 def TestMatchingAllObjects(self): 104 def TestMatchingAllObjects(self):
105 """Tests matching all objects, based on wildcard""" 105 """Tests matching all objects, based on wildcard"""
106
107 actual_obj_uri_strs = set( 106 actual_obj_uri_strs = set(
108 str(u) for u in test_util.test_wildcard_iterator( 107 str(u) for u in test_util.test_wildcard_iterator(
109 self.test_bucket0_uri.clone_replace_name('*'), ResultType.URIS)) 108 self.test_bucket0_uri.clone_replace_name('**')).IterUris())
110 self.assertEqual(self.test_bucket0_obj_uri_strs, actual_obj_uri_strs) 109 self.assertEqual(self.test_bucket0_obj_uri_strs, actual_obj_uri_strs)
111 110
112 def TestMatchingObjectSubset(self): 111 def TestMatchingObjectSubset(self):
113 """Tests matching a subset of objects, based on wildcard""" 112 """Tests matching a subset of objects, based on wildcard"""
114
115 exp_obj_uri_strs = set( 113 exp_obj_uri_strs = set(
116 [str(self.test_bucket0_uri.clone_replace_name('abcd')), 114 [str(self.test_bucket0_uri.clone_replace_name('abcd')),
117 str(self.test_bucket0_uri.clone_replace_name('abdd'))]) 115 str(self.test_bucket0_uri.clone_replace_name('abdd'))])
118 actual_obj_uri_strs = set( 116 actual_obj_uri_strs = set(
119 str(u) for u in test_util.test_wildcard_iterator( 117 str(u) for u in test_util.test_wildcard_iterator(
120 self.test_bucket0_uri.clone_replace_name('ab??'), ResultType.URIS)) 118 self.test_bucket0_uri.clone_replace_name('ab??')).IterUris())
121 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs) 119 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs)
122 120
123 def TestMatchingNonWildcardedUri(self): 121 def TestMatchingNonWildcardedUri(self):
124 """Tests matching a single named object""" 122 """Tests matching a single named object"""
125
126 exp_obj_uri_strs = set([str(self.test_bucket0_uri.clone_replace_name('abcd') 123 exp_obj_uri_strs = set([str(self.test_bucket0_uri.clone_replace_name('abcd')
127 )]) 124 )])
128 actual_obj_uri_strs = set( 125 actual_obj_uri_strs = set(
129 str(u) for u in test_util.test_wildcard_iterator( 126 str(u) for u in test_util.test_wildcard_iterator(
130 self.test_bucket0_uri.clone_replace_name('abcd'), ResultType.URIS)) 127 self.test_bucket0_uri.clone_replace_name('abcd')).IterUris())
131 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs) 128 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs)
132 129
133 def TestWildcardedObjectUriWithVsWithoutPrefix(self): 130 def TestWildcardedObjectUriWithVsWithoutPrefix(self):
134 """Tests that wildcarding w/ and w/o server prefix get same result""" 131 """Tests that wildcarding w/ and w/o server prefix get same result"""
135 132 # (It's just more efficient to query w/o a prefix; wildcard
133 # iterator will filter the matches either way.)
136 with_prefix_uri_strs = set( 134 with_prefix_uri_strs = set(
137 str(u) for u in test_util.test_wildcard_iterator( 135 str(u) for u in test_util.test_wildcard_iterator(
138 self.test_bucket0_uri.clone_replace_name('abcd'), ResultType.URIS)) 136 self.test_bucket0_uri.clone_replace_name('abcd')).IterUris())
139 # By including a wildcard at the start of the string no prefix can be 137 # By including a wildcard at the start of the string no prefix can be
140 # used in server request. 138 # used in server request.
141 no_prefix_uri_strs = set( 139 no_prefix_uri_strs = set(
142 str(u) for u in test_util.test_wildcard_iterator( 140 str(u) for u in test_util.test_wildcard_iterator(
143 self.test_bucket0_uri.clone_replace_name('?bcd'), ResultType.URIS)) 141 self.test_bucket0_uri.clone_replace_name('?bcd')).IterUris())
144 self.assertEqual(with_prefix_uri_strs, no_prefix_uri_strs) 142 self.assertEqual(with_prefix_uri_strs, no_prefix_uri_strs)
145 143
144 def TestWildcardedObjectUriNestedSubdirMatch(self):
145 """Tests wildcarding with a nested subdir"""
146 uri_strs = set()
147 prefixes = set()
148 for blr in test_util.test_wildcard_iterator(
149 self.test_bucket0_uri.clone_replace_name('*')):
150 if blr.HasPrefix():
151 prefixes.add(blr.GetPrefix().name)
152 else:
153 uri_strs.add(blr.GetUri().uri)
154 exp_obj_uri_strs = set(['%s_0/%s' % (self.base_uri_str, x)
155 for x in self.immed_child_obj_names])
156 self.assertEqual(exp_obj_uri_strs, uri_strs)
157 self.assertEqual(1, len(prefixes))
158 self.assertTrue('nested1/' in prefixes)
159
160 def TestWildcardedObjectUriNestedSubSubdirMatch(self):
161 """Tests wildcarding with a nested sub-subdir"""
162 for final_char in ('', '/'):
163 uri_strs = set()
164 prefixes = set()
165 for blr in test_util.test_wildcard_iterator(
166 self.test_bucket0_uri.clone_replace_name('nested1/*%s' % final_char)):
167 if blr.HasPrefix():
168 prefixes.add(blr.GetPrefix().name)
169 else:
170 uri_strs.add(blr.GetUri().uri)
171 self.assertEqual(0, len(uri_strs))
172 self.assertEqual(1, len(prefixes))
173 self.assertTrue('nested1/nested2/' in prefixes)
174
146 def TestNoMatchingWildcardedObjectUri(self): 175 def TestNoMatchingWildcardedObjectUri(self):
147 """Tests that we raise an exception for non-matching wildcarded URI""" 176 """Tests that get back an empty iterator for non-matching wildcarded URI"""
148 177 res = list(test_util.test_wildcard_iterator(
149 try: 178 self.test_bucket0_uri.clone_replace_name('*x0')).IterUris())
150 for unused_ in test_util.test_wildcard_iterator( 179 self.assertEqual(0, len(res))
151 self.test_bucket0_uri.clone_replace_name('*x0'), ResultType.URIS):
152 self.fail('Expected WildcardException not raised.')
153 except wildcard_iterator.WildcardException, e:
154 # Expected behavior.
155 self.assertTrue(str(e).find('No matches') != -1)
156 180
157 def TestWildcardedInvalidObjectUri(self): 181 def TestWildcardedInvalidObjectUri(self):
158 """Tests that we raise an exception for wildcarded invalid URI""" 182 """Tests that we raise an exception for wildcarded invalid URI"""
159
160 try: 183 try:
161 for unused_ in test_util.test_wildcard_iterator( 184 for unused_ in test_util.test_wildcard_iterator(
162 'badscheme://asdf', ResultType.URIS): 185 'badscheme://asdf').IterUris():
163 self.assertFalse('Expected InvalidUriError not raised.') 186 self.assertFalse('Expected InvalidUriError not raised.')
164 except InvalidUriError, e: 187 except InvalidUriError, e:
165 # Expected behavior. 188 # Expected behavior.
166 self.assertTrue(e.message.find('Unrecognized scheme') != -1) 189 self.assertTrue(e.message.find('Unrecognized scheme') != -1)
167 190
168 def TestWildcardedInvalidResultType(self):
169 """Tests that we raise an exception for wildcard with invalid ResultType"""
170
171 try:
172 test_util.test_wildcard_iterator('gs://asdf/*', 'invalid')
173 self.fail('Expected WildcardException not raised.')
174 except wildcard_iterator.WildcardException, e:
175 # Expected behavior.
176 self.assertTrue(str(e).find('Invalid ResultType') != -1)
177
178 def TestSingleMatchWildcardedBucketUri(self): 191 def TestSingleMatchWildcardedBucketUri(self):
179 """Tests matching a single bucket based on a wildcarded bucket URI""" 192 """Tests matching a single bucket based on a wildcarded bucket URI"""
180
181 exp_obj_uri_strs = set(['%s_1/' % self.base_uri_str]) 193 exp_obj_uri_strs = set(['%s_1/' % self.base_uri_str])
182 actual_obj_uri_strs = set( 194 actual_obj_uri_strs = set(
183 str(u) for u in test_util.test_wildcard_iterator('%s*1' % 195 str(u) for u in test_util.test_wildcard_iterator(
184 self.base_uri_str, 196 '%s*1' % self.base_uri_str).IterUris())
185 ResultType.URIS))
186 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs) 197 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs)
187 198
188 def TestMultiMatchWildcardedBucketUri(self): 199 def TestMultiMatchWildcardedBucketUri(self):
189 """Tests matching a multiple buckets based on a wildcarded bucket URI""" 200 """Tests matching a multiple buckets based on a wildcarded bucket URI"""
190
191 exp_obj_uri_strs = set(['%s_%s/' % 201 exp_obj_uri_strs = set(['%s_%s/' %
192 (self.base_uri_str, i) for i in range(2)]) 202 (self.base_uri_str, i) for i in range(2)])
193 actual_obj_uri_strs = set( 203 actual_obj_uri_strs = set(
194 str(u) for u in test_util.test_wildcard_iterator('%s*' % 204 str(u) for u in test_util.test_wildcard_iterator(
195 self.base_uri_str, 205 '%s*' % self.base_uri_str).IterUris())
196 ResultType.URIS))
197 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs) 206 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs)
198 207
199 def TestMultiLevelWildcardUri(self): 208 def TestWildcardBucketAndObjectUri(self):
200 """Tests matching with both bucket and object wildcards""" 209 """Tests matching with both bucket and object wildcards"""
201 210 exp_obj_uri_strs = set([str(self.test_bucket0_uri.clone_replace_name(
202 exp_obj_uri_strs = set([str(self.test_bucket0_uri.clone_replace_name('abcd' 211 'abcd'))])
203 ))])
204 actual_obj_uri_strs = set( 212 actual_obj_uri_strs = set(
205 str(u) for u in test_util.test_wildcard_iterator('%s_0*/abc*' % 213 str(u) for u in test_util.test_wildcard_iterator(
206 self.base_uri_str, 214 '%s_0*/abc*' % self.base_uri_str).IterUris())
207 ResultType.URIS))
208 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs) 215 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs)
209 216
210 def TestBucketOnlyWildcardWithResultTypeKeys(self): 217 def TestWildcardUpToFinalCharSubdirPlusObjectName(self):
211 """Tests that bucket-only wildcard with ResultType.KEYS raises exception""" 218 """Tests wildcard subd*r/obj name"""
219 exp_obj_uri_strs = set([str(self.test_bucket0_uri.clone_replace_name(
220 'nested1/nested2/xyz1'))])
221 x=list(test_util.test_wildcard_iterator(
222 '%s**' % self.test_bucket0_uri.uri).IterUris())
223 actual_obj_uri_strs = set(
224 str(u) for u in test_util.test_wildcard_iterator(
225 '%snested1/nest*2/xyz1' % self.test_bucket0_uri.uri).IterUris())
226 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs)
212 227
228 def TestPostRecursiveWildcard(self):
229 """Tests that wildcard containing ** followed by an additional wildcard work s"""
230 exp_obj_uri_strs = set([str(self.test_bucket0_uri.clone_replace_name(
231 'nested1/nested2/xyz2'))])
232 actual_obj_uri_strs = set(
233 str(u) for u in test_util.test_wildcard_iterator(
234 '%s**/*y*2' % self.test_bucket0_uri.uri).IterUris())
235 self.assertEqual(exp_obj_uri_strs, actual_obj_uri_strs)
236
237 def TestCallingGetKeyOnProviderOnlyWildcardIteration(self):
238 """Tests that attempting iterating provider-only wildcard raises"""
213 try: 239 try:
214 for unused_ in test_util.test_wildcard_iterator( 240 from gslib.bucket_listing_ref import BucketListingRefException
215 '%s*1' % self.base_uri_str, ResultType.KEYS): 241 for iter_result in wildcard_iterator.wildcard_iterator(
216 self.fail('Expected WildcardException not raised.') 242 'gs://', ProjectIdHandler(),
217 except wildcard_iterator.WildcardException, e: 243 bucket_storage_uri_class=mock_storage_service.MockBucketStorageUri):
218 # Expected behavior. 244 iter_result.GetKey()
219 self.assertTrue(str(e).find('with ResultType.KEYS iteration') != -1) 245 self.fail('Expected BucketListingRefException not raised.')
246 except BucketListingRefException, e:
247 self.assertTrue(str(e).find(
248 'Attempt to call GetKey() on Key-less BucketListingRef') != -1)
220 249
221 250
222 class FileIteratorTests(unittest.TestCase): 251 class FileIteratorTests(unittest.TestCase):
223 """FileWildcardIterator test suite""" 252 """FileWildcardIterator test suite"""
224 253
225 def GetSuiteDescription(self): 254 def GetSuiteDescription(self):
226 return 'FileWildcardIterator test suite' 255 return 'FileWildcardIterator test suite'
227 256
228 @classmethod 257 @classmethod
229 def SetUpClass(cls): 258 def SetUpClass(cls):
230 """Creates a test dir containing 3 files and one nested subdirectory + file. 259 """
260 Creates a test dir containing 3 files and one nested subdirectory + file.
231 """ 261 """
232 262
233 # Create the test directories. 263 # Create the test directories.
234 cls.test_dir = tempfile.mkdtemp() 264 cls.test_dir = tempfile.mkdtemp()
235 nested_subdir = '%s%sdir1%sdir2' % (cls.test_dir, os.sep, os.sep) 265 nested_subdir = '%s%sdir1%sdir2' % (cls.test_dir, os.sep, os.sep)
236 os.makedirs(nested_subdir) 266 os.makedirs(nested_subdir)
237 267
238 # Create the test files. 268 # Create the test files.
239 immed_child_filenames = ['abcd', 'abdd', 'ade$', 'dir1'] 269 immed_child_filenames = ['abcd', 'abdd', 'ade$', 'dir1']
240 immed_child_filepaths = ['%s%s%s' % (cls.test_dir, os.sep, f) 270 immed_child_filepaths = ['%s%s%s' % (cls.test_dir, os.sep, f)
(...skipping 12 matching lines...) Expand all
253 [('file://%s' % o) for o in filepaths] 283 [('file://%s' % o) for o in filepaths]
254 ) 284 )
255 285
256 cls.all_uri_strs = set( 286 cls.all_uri_strs = set(
257 ['file://%s' % nested_subdir] 287 ['file://%s' % nested_subdir]
258 ).union(cls.all_file_uri_strs) 288 ).union(cls.all_file_uri_strs)
259 289
260 @classmethod 290 @classmethod
261 def TearDownClass(cls): 291 def TearDownClass(cls):
262 """Cleans up test dir and file created by SetUpClass""" 292 """Cleans up test dir and file created by SetUpClass"""
263
264 if hasattr(cls, 'test_dir'): 293 if hasattr(cls, 'test_dir'):
265 shutil.rmtree(cls.test_dir) 294 shutil.rmtree(cls.test_dir)
266 295
296 def TestContainsWildcard(self):
297 """Tests ContainsWildcard call"""
298 self.assertTrue(ContainsWildcard('a*.txt'))
299 self.assertTrue(ContainsWildcard('a[0-9].txt'))
300 self.assertFalse(ContainsWildcard('0-9.txt'))
301 self.assertTrue(ContainsWildcard('?.txt'))
302
267 def TestNoOpDirectoryIterator(self): 303 def TestNoOpDirectoryIterator(self):
268 """Tests that directory-only URI iterates just that one URI""" 304 """Tests that directory-only URI iterates just that one URI"""
269 305 results = list(test_util.test_wildcard_iterator('file:///tmp/').IterUris())
270 results = list(test_util.test_wildcard_iterator('file:///tmp/',
271 ResultType.URIS))
272 self.assertEqual(1, len(results)) 306 self.assertEqual(1, len(results))
273 self.assertEqual('file:///tmp/', str(results[0])) 307 self.assertEqual('file:///tmp/', str(results[0]))
274 308
275 def TestMatchingAllFiles(self): 309 def TestMatchingAllFiles(self):
276 """Tests matching all files, based on wildcard""" 310 """Tests matching all files, based on wildcard"""
277
278 uri = test_util.test_storage_uri('file://%s/*' % self.test_dir) 311 uri = test_util.test_storage_uri('file://%s/*' % self.test_dir)
279 actual_uri_strs = set(str(u) for u in 312 actual_uri_strs = set(str(u) for u in
280 test_util.test_wildcard_iterator(uri, ResultType.KEYS) 313 test_util.test_wildcard_iterator(uri).IterUris()
281 ) 314 )
282 self.assertEqual(self.immed_child_uri_strs, actual_uri_strs) 315 self.assertEqual(self.immed_child_uri_strs, actual_uri_strs)
283 316
284 def TestMatchingFileSubset(self): 317 def TestMatchingFileSubset(self):
285 """Tests matching a subset of files, based on wildcard""" 318 """Tests matching a subset of files, based on wildcard"""
286
287 exp_uri_strs = set( 319 exp_uri_strs = set(
288 ['file://%s/abcd' % self.test_dir, 'file://%s/abdd' % self.test_dir] 320 ['file://%s/abcd' % self.test_dir, 'file://%s/abdd' % self.test_dir]
289 ) 321 )
290 uri = test_util.test_storage_uri('file://%s/ab??' % self.test_dir) 322 uri = test_util.test_storage_uri('file://%s/ab??' % self.test_dir)
291 actual_uri_strs = set(str(u) for u in 323 actual_uri_strs = set(str(u) for u in
292 test_util.test_wildcard_iterator(uri, ResultType.KEYS) 324 test_util.test_wildcard_iterator(uri).IterUris()
293 ) 325 )
294 self.assertEqual(exp_uri_strs, actual_uri_strs) 326 self.assertEqual(exp_uri_strs, actual_uri_strs)
295 327
296 def TestMatchingNonWildcardedUri(self): 328 def TestMatchingNonWildcardedUri(self):
297 """Tests matching a single named file""" 329 """Tests matching a single named file"""
298
299 exp_uri_strs = set(['file://%s/abcd' % self.test_dir]) 330 exp_uri_strs = set(['file://%s/abcd' % self.test_dir])
300 uri = test_util.test_storage_uri('file://%s/abcd' % self.test_dir) 331 uri = test_util.test_storage_uri('file://%s/abcd' % self.test_dir)
301 actual_uri_strs = set(str(u) for u in 332 actual_uri_strs = set(
302 test_util.test_wildcard_iterator(uri, ResultType.KEYS) 333 str(u) for u in test_util.test_wildcard_iterator(uri).IterUris())
303 )
304 self.assertEqual(exp_uri_strs, actual_uri_strs) 334 self.assertEqual(exp_uri_strs, actual_uri_strs)
305 335
306 def TestMatchingFilesIgnoringOtherRegexChars(self): 336 def TestMatchingFilesIgnoringOtherRegexChars(self):
307 """Tests ignoring non-wildcard regex chars (e.g., ^ and $)""" 337 """Tests ignoring non-wildcard regex chars (e.g., ^ and $)"""
308 338
309 exp_uri_strs = set(['file://%s/ade$' % self.test_dir]) 339 exp_uri_strs = set(['file://%s/ade$' % self.test_dir])
310 uri = test_util.test_storage_uri('file://%s/ad*$' % self.test_dir) 340 uri = test_util.test_storage_uri('file://%s/ad*$' % self.test_dir)
311 actual_uri_strs = set(str(u) for u in 341 actual_uri_strs = set(
312 test_util.test_wildcard_iterator(uri, ResultType.KEYS) 342 str(u) for u in test_util.test_wildcard_iterator(uri).IterUris())
313 )
314 self.assertEqual(exp_uri_strs, actual_uri_strs) 343 self.assertEqual(exp_uri_strs, actual_uri_strs)
315 344
316 def TestRecursiveDirectoryOnlyWildcarding(self): 345 def TestRecursiveDirectoryOnlyWildcarding(self):
317 """Tests recusive expansion of directory-only '**' wildcard""" 346 """Tests recusive expansion of directory-only '**' wildcard"""
318
319 uri = test_util.test_storage_uri('file://%s/**' % self.test_dir) 347 uri = test_util.test_storage_uri('file://%s/**' % self.test_dir)
320 actual_uri_strs = set(str(u) for u in 348 actual_uri_strs = set(
321 test_util.test_wildcard_iterator(uri, ResultType.KEYS) 349 str(u) for u in test_util.test_wildcard_iterator(uri).IterUris())
322 )
323 self.assertEqual(self.all_file_uri_strs, actual_uri_strs) 350 self.assertEqual(self.all_file_uri_strs, actual_uri_strs)
324 351
325 def TestRecursiveDirectoryPlusFileWildcarding(self): 352 def TestRecursiveDirectoryPlusFileWildcarding(self):
326 """Tests recusive expansion of '**' directory plus '*' wildcard""" 353 """Tests recusive expansion of '**' directory plus '*' wildcard"""
327
328 uri = test_util.test_storage_uri('file://%s/**/*' % self.test_dir) 354 uri = test_util.test_storage_uri('file://%s/**/*' % self.test_dir)
329 actual_uri_strs = set(str(u) for u in 355 actual_uri_strs = set(
330 test_util.test_wildcard_iterator(uri, ResultType.KEYS) 356 str(u) for u in test_util.test_wildcard_iterator(uri).IterUris())
331 )
332 self.assertEqual(self.all_file_uri_strs, actual_uri_strs) 357 self.assertEqual(self.all_file_uri_strs, actual_uri_strs)
333 358
334 def TestInvalidRecursiveDirectoryWildcard(self): 359 def TestInvalidRecursiveDirectoryWildcard(self):
335 """Tests that wildcard containing '***' raises exception""" 360 """Tests that wildcard containing '***' raises exception"""
336
337 try: 361 try:
338 uri = test_util.test_storage_uri('file://%s/***/abcd' % self.test_dir) 362 uri = test_util.test_storage_uri('file://%s/***/abcd' % self.test_dir)
339 for unused_ in test_util.test_wildcard_iterator(uri, ResultType.KEYS): 363 for unused_ in test_util.test_wildcard_iterator(uri).IterUris():
340 self.fail('Expected WildcardException not raised.') 364 self.fail('Expected WildcardException not raised.')
341 except wildcard_iterator.WildcardException, e: 365 except wildcard_iterator.WildcardException, e:
342 # Expected behavior. 366 # Expected behavior.
343 self.assertTrue(str(e).find('more than 2 consecutive') != -1) 367 self.assertTrue(str(e).find('more than 2 consecutive') != -1)
344 368
345 def TestMissingDir(self): 369 def TestMissingDir(self):
346 """Tests that wildcard raises exception when directory doesn't exist""" 370 """Tests that wildcard gets empty iterator when directory doesn't exist"""
347 371 res = list(
348 try: 372 test_util.test_wildcard_iterator('file://no_such_dir/*').IterUris())
349 for unused_ in test_util.test_wildcard_iterator('file://no_such_dir/*', 373 self.assertEqual(0, len(res))
350 ResultType.KEYS):
351 self.fail('Expected WildcardException not raised.')
352 except wildcard_iterator.WildcardException, e:
353 # Expected behavior.
354 self.assertTrue(str(e).find('No matches') != -1)
355 374
356 def TestExistingDirNoFileMatch(self): 375 def TestExistingDirNoFileMatch(self):
357 """Tests that wildcard raises exception when there's no match""" 376 """Tests that wildcard returns empty iterator when there's no match"""
358 377 uri = test_util.test_storage_uri(
359 try: 378 'file://%s/non_existent*' % self.test_dir)
360 uri = test_util.test_storage_uri( 379 res = list(test_util.test_wildcard_iterator(uri).IterUris())
361 'file://%s/non_existent*' % self.test_dir) 380 self.assertEqual(0, len(res))
362 for unused_ in test_util.test_wildcard_iterator(uri, ResultType.KEYS):
363 self.fail('Expected WildcardException not raised.')
364 except wildcard_iterator.WildcardException, e:
365 # Expected behavior.
366 self.assertTrue(str(e).find('No matches') != -1)
367 381
368 382
369 if __name__ == '__main__': 383 if __name__ == '__main__':
370 if sys.version_info[:3] < (2, 5, 1): 384 if sys.version_info[:3] < (2, 5, 1):
371 sys.exit('These tests must be run on at least Python 2.5.1\n') 385 sys.exit('These tests must be run on at least Python 2.5.1\n')
372 test_loader = unittest.TestLoader() 386 test_loader = unittest.TestLoader()
373 test_loader.testMethodPrefix = 'Test' 387 test_loader.testMethodPrefix = 'Test'
374 for suite in (test_loader.loadTestsFromTestCase(CloudWildcardIteratorTests), 388 for suite in (test_loader.loadTestsFromTestCase(CloudWildcardIteratorTests),
375 test_loader.loadTestsFromTestCase(FileIteratorTests)): 389 test_loader.loadTestsFromTestCase(FileIteratorTests)):
376 # Seems like there should be a cleaner way to find the test_class. 390 # Seems like there should be a cleaner way to find the test_class.
377 test_class = suite.__getattribute__('_tests')[0] 391 test_class = suite.__getattribute__('_tests')[0]
378 # We call SetUpClass() and TearDownClass() ourselves because we 392 # We call SetUpClass() and TearDownClass() ourselves because we
379 # don't assume the user has Python 2.7 (which supports classmethods 393 # don't assume the user has Python 2.7 (which supports classmethods
380 # that do it, with camelCase versions of these names). 394 # that do it, with camelCase versions of these names).
381 try: 395 try:
382 print 'Setting up %s...' % test_class.GetSuiteDescription() 396 print 'Setting up %s...' % test_class.GetSuiteDescription()
383 test_class.SetUpClass() 397 test_class.SetUpClass()
384 print 'Running %s...' % test_class.GetSuiteDescription() 398 print 'Running %s...' % test_class.GetSuiteDescription()
385 unittest.TextTestRunner(verbosity=2).run(suite) 399 unittest.TextTestRunner(verbosity=2).run(suite)
386 finally: 400 finally:
387 print 'Cleaning up after %s...' % test_class.GetSuiteDescription() 401 print 'Cleaning up after %s...' % test_class.GetSuiteDescription()
388 test_class.TearDownClass() 402 test_class.TearDownClass()
389 print '' 403 print ''
OLDNEW
« no previous file with comments | « third_party/gsutil/gslib/test_util.py ('k') | third_party/gsutil/gslib/thread_pool.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698