desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test a "like" filter'
def test_like_filter(self):
query = SimpleModel.all() query.filter('name like', '% Object') assert (query.count() == 3) query = SimpleModel.all() query.filter('name not like', '% Object') assert (query.count() == 0)
'Test an "=" and "!=" filter'
def test_equals_filter(self):
query = SimpleModel.all() query.filter('name =', 'Simple Object') assert (query.count() == 1) query = SimpleModel.all() query.filter('name !=', 'Simple Object') assert (query.count() == 2)
'Test a filter function as an "or"'
def test_or_filter(self):
query = SimpleModel.all() query.filter('name =', ['Simple Object', 'Sub Object']) assert (query.count() == 2)
'Test Multiple filters which are an "and"'
def test_and_filter(self):
query = SimpleModel.all() query.filter('name like', '% Object') query.filter('name like', 'Simple %') assert (query.count() == 1)
'Test filtering for a value that\'s not set'
def test_none_filter(self):
query = SimpleModel.all() query.filter('ref =', None) assert (query.count() == 2)
'Test filtering Using >, >='
def test_greater_filter(self):
query = SimpleModel.all() query.filter('num >', 1) assert (query.count() == 2) query = SimpleModel.all() query.filter('num >=', 1) assert (query.count() == 3)
'Test filtering Using <, <='
def test_less_filter(self):
query = SimpleModel.all() query.filter('num <', 3) assert (query.count() == 2) query = SimpleModel.all() query.filter('num <=', 3) assert (query.count() == 3)
'Test querying on a list'
def test_query_on_list(self):
assert (SimpleModel.find(strs='A').next().id == self.objs[0].id) assert (SimpleModel.find(strs='B').next().id == self.objs[0].id) assert (SimpleModel.find(strs='C').next().id == self.objs[0].id)
'Test with a "like" expression'
def test_like(self):
query = SimpleModel.all() query.filter('strs like', '%oo%') print query.get_query() assert (query.count() == 1)
'Setup this class'
def setup_class(cls):
cls.objs = []
'Remove our objects'
def teardown_class(cls):
for o in cls.objs: try: o.delete() except: pass
'Testing the order of lists'
def test_list_order(self):
t = SimpleListModel() t.nums = [5, 4, 1, 3, 2] t.strs = ['B', 'C', 'A', 'D', 'Foo'] t.put() self.objs.append(t) time.sleep(3) t = SimpleListModel.get_by_id(t.id) assert (t.nums == [5, 4, 1, 3, 2]) assert (t.strs == ['B', 'C', 'A', 'D', 'Foo'])
'Testing to make sure the old method of encoding lists will still return results'
def test_old_compat(self):
t = SimpleListModel() t.put() self.objs.append(t) time.sleep(3) item = t._get_raw_item() item['strs'] = ['A', 'B', 'C'] item.save() time.sleep(3) t = SimpleListModel.get_by_id(t.id) i1 = sorted(item['strs']) i2 = t.strs i2.sort() assert (i1 == i2)
'We noticed a slight problem with querying, since the query uses the same encoder, it was asserting that the value was at the same position in the list, not just "in" the list'
def test_query_equals(self):
t = SimpleListModel() t.strs = ['Bizzle', 'Bar'] t.put() self.objs.append(t) time.sleep(3) assert (SimpleListModel.find(strs='Bizzle').count() == 1) assert (SimpleListModel.find(strs='Bar').count() == 1) assert (SimpleListModel.find(strs=['Bar', 'Bizzle']).count() == 1)
'Test a not equal filter'
def test_query_not_equals(self):
t = SimpleListModel() t.strs = ['Fizzle'] t.put() self.objs.append(t) time.sleep(3) print SimpleListModel.all().filter('strs !=', 'Fizzle').get_query() for tt in SimpleListModel.all().filter('strs !=', 'Fizzle'): print tt.strs assert ('Fizzle' not in tt.strs)
'Setup this class'
def setup_class(cls):
cls.sequences = []
'Remove our sequences'
def teardown_class(cls):
for s in cls.sequences: try: s.delete() except: pass
'Test the sequence generator without rollover'
def test_sequence_generator_no_rollover(self):
from boto.sdb.db.sequence import SequenceGenerator gen = SequenceGenerator('ABC') assert (gen('') == 'A') assert (gen('A') == 'B') assert (gen('B') == 'C') assert (gen('C') == 'AA') assert (gen('AC') == 'BA')
'Test the sequence generator with rollover'
def test_sequence_generator_with_rollover(self):
from boto.sdb.db.sequence import SequenceGenerator gen = SequenceGenerator('ABC', rollover=True) assert (gen('') == 'A') assert (gen('A') == 'B') assert (gen('B') == 'C') assert (gen('C') == 'A')
'Test a simple counter sequence'
def test_sequence_simple_int(self):
from boto.sdb.db.sequence import Sequence s = Sequence() self.sequences.append(s) assert (s.val == 0) assert (s.next() == 1) assert (s.next() == 2) s2 = Sequence(s.id) assert (s2.val == 2) assert (s.next() == 3) assert (s.val == 3) assert (s2.val == 3)
'Test the fibonacci sequence generator'
def test_fib(self):
from boto.sdb.db.sequence import fib lv = 0 for v in [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]: assert (fib(v, lv) == (lv + v)) lv = fib(v, lv)
'Test the fibonacci sequence'
def test_sequence_fib(self):
from boto.sdb.db.sequence import Sequence, fib s = Sequence(fnc=fib) s2 = Sequence(s.id) self.sequences.append(s) assert (s.val == 1) for v in [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]: assert (s.next() == v) assert (s.val == v) assert (s2.val == v)
'Test the String incrementation sequence'
def test_sequence_string(self):
from boto.sdb.db.sequence import Sequence, increment_string s = Sequence(fnc=increment_string) self.sequences.append(s) assert (s.val == 'A') assert (s.next() == 'B') s.val = 'Z' assert (s.val == 'Z') assert (s.next() == 'AA')
'Set etag attribute by generating hex MD5 checksum on current contents of mock key.'
def set_etag(self):
m = md5() if (not isinstance(self.data, bytes)): m.update(self.data.encode('utf-8')) else: m.update(self.data) hex_md5 = m.hexdigest() self.etag = hex_md5
':type fp: file :param fp: File pointer to the file to MD5 hash. The file pointer will be reset to the beginning of the file before the method returns. :rtype: tuple :return: A tuple containing the hex digest version of the MD5 hash as the first element and the base64 encoded version of the plain digest as the second ...
def compute_md5(self, fp):
tup = compute_md5(fp) self.size = tup[2] return tup[0:2]
'Returns string representation of URI.'
def __repr__(self):
return self.uri
'Create tags from python objects rather than raw xml.'
def test_tagging_from_objects(self):
t = Tags() tag_set = TagSet() tag_set.add_tag('akey', 'avalue') tag_set.add_tag('anotherkey', 'anothervalue') t.add_tag_set(tag_set) self.bucket.set_tags(t) response = self.bucket.get_tags() tags = sorted(response[0], key=(lambda tag: tag.key)) self.assertEqual(tags[0].key, 'akey') ...
'Ensures that calls to the set_xml_acl functions succeed.'
def testSetAclXml(self):
b = self._MakeBucket() k = b.new_key('obj') k.set_contents_from_string('stringdata') bucket_uri = storage_uri(('gs://%s/' % b.name)) bucket_uri.object_name = 'obj' bucket_acl = bucket_uri.get_acl() bucket_uri.object_name = None all_users_read_permission = "<Entry><Scope type='AllUsers...
'Tests that non-resumable uploads work'
def test_non_resumable_upload(self):
(small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0, os.SEEK_END) dst_key = self._MakeKey(set_contents=False) try: dst_key.set_contents_from_file(small_src_file) self.fail('should fail as need to rewind the filepointer') exce...
'Tests a single resumable upload, with no tracker URI persistence'
def test_upload_without_persistent_tracker(self):
res_upload_handler = ResumableUploadHandler() (small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0) dst_key = self._MakeKey(set_contents=False) dst_key.set_contents_from_file(small_src_file, res_upload_handler=res_upload_handler) self.assertEqual(SMALL_KEY_SI...
'Tests that failed resumable upload leaves a correct tracker URI file'
def test_failed_upload_with_persistent_tracker(self):
harness = CallbackTestHarness() tracker_file_name = self.make_tracker_file() res_upload_handler = ResumableUploadHandler(tracker_file_name=tracker_file_name, num_retries=0) (small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0) dst_key = self._MakeKey(set_cont...
'Tests handling of a retryable exception'
def test_retryable_exception_recovery(self):
exception = ResumableUploadHandler.RETRYABLE_EXCEPTIONS[0] harness = CallbackTestHarness(exception=exception) res_upload_handler = ResumableUploadHandler(num_retries=1) (small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0) dst_key = self._MakeKey(set_contents...
'Tests handling of a Broken Pipe (which interacts with an httplib bug)'
def test_broken_pipe_recovery(self):
exception = IOError(errno.EPIPE, 'Broken pipe') harness = CallbackTestHarness(exception=exception) res_upload_handler = ResumableUploadHandler(num_retries=1) (small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0) dst_key = self._MakeKey(set_contents=False) ...
'Tests a resumable upload that fails with a non-retryable exception'
def test_non_retryable_exception_handling(self):
harness = CallbackTestHarness(exception=OSError(errno.EACCES, 'Permission denied')) res_upload_handler = ResumableUploadHandler(num_retries=1) (small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0) dst_key = self._MakeKey(set_contents=False) try: ds...
'Tests resumable upload that fails once and then completes, with tracker file'
def test_failed_and_restarted_upload_with_persistent_tracker(self):
harness = CallbackTestHarness() tracker_file_name = self.make_tracker_file() res_upload_handler = ResumableUploadHandler(tracker_file_name=tracker_file_name, num_retries=1) (small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0) dst_key = self._MakeKey(set_cont...
'Tests resumable upload that fails twice in one process, then completes'
def test_multiple_in_process_failures_then_succeed(self):
res_upload_handler = ResumableUploadHandler(num_retries=3) (small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0) dst_key = self._MakeKey(set_contents=False) dst_key.set_contents_from_file(small_src_file, res_upload_handler=res_upload_handler) self.assertEqual...
'Tests resumable upload that fails completely in one process, then when restarted completes, using a tracker file'
def test_multiple_in_process_failures_then_succeed_with_tracker_file(self):
harness = CallbackTestHarness(fail_after_n_bytes=(LARGE_KEY_SIZE / 2), num_times_to_fail=2) tracker_file_name = self.make_tracker_file() res_upload_handler = ResumableUploadHandler(tracker_file_name=tracker_file_name, num_retries=1) (larger_src_file_as_string, larger_src_file) = self.make_large_file() ...
'Tests resumable upload that successfully uploads some content before it fails, then restarts and completes'
def test_upload_with_inital_partial_upload_before_failure(self):
harness = CallbackTestHarness(fail_after_n_bytes=(LARGE_KEY_SIZE / 2)) res_upload_handler = ResumableUploadHandler(num_retries=1) (larger_src_file_as_string, larger_src_file) = self.make_large_file() larger_src_file.seek(0) dst_key = self._MakeKey(set_contents=False) dst_key.set_contents_from_fi...
'Tests uploading an empty file (exercises boundary conditions).'
def test_empty_file_upload(self):
res_upload_handler = ResumableUploadHandler() empty_src_file = StringIO.StringIO('') empty_src_file.seek(0) dst_key = self._MakeKey(set_contents=False) dst_key.set_contents_from_file(empty_src_file, res_upload_handler=res_upload_handler) self.assertEqual(0, dst_key.size)
'Tests that resumable upload correctly sets passed metadata'
def test_upload_retains_metadata(self):
res_upload_handler = ResumableUploadHandler() headers = {'Content-Type': 'text/plain', 'x-goog-meta-abc': 'my meta', 'x-goog-acl': 'public-read'} (small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0) dst_key = self._MakeKey(set_contents=False) dst_key.set_...
'Tests resumable upload on a file that changes sizes between initial upload start and restart'
def test_upload_with_file_size_change_between_starts(self):
harness = CallbackTestHarness(fail_after_n_bytes=(LARGE_KEY_SIZE / 2)) tracker_file_name = self.make_tracker_file() res_upload_handler = ResumableUploadHandler(tracker_file_name=tracker_file_name, num_retries=0) (larger_src_file_as_string, larger_src_file) = self.make_large_file() larger_src_file.se...
'Tests resumable upload on a file that changes sizes while upload in progress'
def test_upload_with_file_size_change_during_upload(self):
test_file_size = (500 * 1024) test_file = self.build_input_file(test_file_size)[1] harness = CallbackTestHarness(fp_to_change=test_file, fp_change_pos=test_file_size) res_upload_handler = ResumableUploadHandler(num_retries=1) dst_key = self._MakeKey(set_contents=False) try: dst_key.set_c...
'Tests resumable upload on a file that changes one byte of content (so, size stays the same) while upload in progress.'
def test_upload_with_file_content_change_during_upload(self):
def Execute(): res_upload_handler = ResumableUploadHandler(num_retries=1) dst_key = self._MakeKey(set_contents=False) bucket_uri = storage_uri(('gs://' + dst_key.bucket.name)) dst_key_uri = bucket_uri.clone_replace_name(dst_key.name) try: dst_key.set_contents_from...
'Tests resumable upload on a file when the user supplies a Content-Length header. This is used by gsutil, for example, to set the content length when gzipping a file.'
def test_upload_with_content_length_header_set(self):
res_upload_handler = ResumableUploadHandler() (small_src_file_as_string, small_src_file) = self.make_small_file() small_src_file.seek(0) dst_key = self._MakeKey(set_contents=False) try: dst_key.set_contents_from_file(small_src_file, res_upload_handler=res_upload_handler, headers={'Content-Le...
'Tests resumable upload with a syntactically invalid tracker URI'
def test_upload_with_syntactically_invalid_tracker_uri(self):
tmp_dir = self._MakeTempDir() syntactically_invalid_tracker_file_name = os.path.join(tmp_dir, 'synt_invalid_uri_tracker') with open(syntactically_invalid_tracker_file_name, 'w') as f: f.write('ftp://example.com') res_upload_handler = ResumableUploadHandler(tracker_file_name=syntactically_invalid...
'Tests resumable upload with invalid upload ID'
def test_upload_with_invalid_upload_id_in_tracker_file(self):
invalid_upload_id = 'http://pub.storage.googleapis.com/?upload_id=AyzB2Uo74W4EYxyi5dp_-r68jz8rtbvshsv4TX7srJVkJ57CxTY5Dw2' tmpdir = self._MakeTempDir() invalid_upload_id_tracker_file_name = os.path.join(tmpdir, 'invalid_upload_id_tracker') with open(invalid_upload_id_tracker_file_name, 'w') as f: ...
'Tests resumable upload with an unwritable tracker file'
def test_upload_with_unwritable_tracker_file(self):
tmp_dir = self._MakeTempDir() tracker_file_name = self.make_tracker_file(tmp_dir) save_mod = os.stat(tmp_dir).st_mode try: os.chmod(tmp_dir, 0) res_upload_handler = ResumableUploadHandler(tracker_file_name=tracker_file_name) except ResumableUploadException as e: self.assertEq...
'Returns the GSConnection object used to connect to GCS.'
def _GetConnection(self):
return self._conn
'Creates and returns a temporary name for testing that is likely to be unique.'
def _MakeTempName(self):
return ('boto-gs-test-%s' % repr(time.time()).replace('.', '-'))
'Creates and returns a temporary bucket name for testing that is likely to be unique.'
def _MakeBucketName(self):
b = self._MakeTempName() self._buckets.append(b) return b
'Creates and returns temporary bucket for testing. After the test, the contents of the bucket and the bucket itself will be deleted.'
def _MakeBucket(self):
b = self._conn.create_bucket(self._MakeBucketName()) return b
'Creates and returns a Key with provided data. If no bucket is given, a temporary bucket is created.'
def _MakeKey(self, data='', bucket=None, set_contents=True):
if (data and (not set_contents)): raise ValueError('MakeKey called with a non-empty data parameter but set_contents was set to False.') if (not bucket): bucket = self._MakeBucket() key_name = self._MakeTempName() k = bucket.new_key(key_name) if set...
'Creates and returns temporary versioned bucket for testing. After the test, the contents of the bucket and the bucket itself will be deleted.'
def _MakeVersionedBucket(self):
b = self._MakeBucket() b.configure_versioning(True) time.sleep(30) return b
'Creates and returns a temporary directory on disk. After the test, the contents of the directory and the directory itself will be deleted.'
def _MakeTempDir(self):
tmpdir = tempfile.mkdtemp(prefix=self._MakeTempName()) self._tempdirs.append(tmpdir) return tmpdir
'To use this test harness, pass the \'call\' method of the instantiated object as the cb param to the set_contents_from_file() or get_contents_to_file() call.'
def call(self, total_bytes_transferred, unused_total_size):
if self.num_failures: self.transferred_seq_after_first_failure.append(total_bytes_transferred) else: self.transferred_seq_before_first_failure.append(total_bytes_transferred) if ((total_bytes_transferred >= self.fail_after_n_bytes) and (self.num_failures < self.num_times_to_fail)): s...
'Tests that non-resumable downloads work'
def test_non_resumable_download(self):
dst_fp = self.make_dst_fp() (small_src_key_as_string, small_src_key) = self.make_small_key() small_src_key.get_contents_to_file(dst_fp) self.assertEqual(SMALL_KEY_SIZE, get_cur_file_size(dst_fp)) self.assertEqual(small_src_key_as_string, small_src_key.get_contents_as_string())
'Tests a single resumable download, with no tracker persistence'
def test_download_without_persistent_tracker(self):
res_download_handler = ResumableDownloadHandler() dst_fp = self.make_dst_fp() (small_src_key_as_string, small_src_key) = self.make_small_key() small_src_key.get_contents_to_file(dst_fp, res_download_handler=res_download_handler) self.assertEqual(SMALL_KEY_SIZE, get_cur_file_size(dst_fp)) self.as...
'Tests that failed resumable download leaves a correct tracker file'
def test_failed_download_with_persistent_tracker(self):
harness = CallbackTestHarness() tmpdir = self._MakeTempDir() tracker_file_name = self.make_tracker_file(tmpdir) dst_fp = self.make_dst_fp(tmpdir) res_download_handler = ResumableDownloadHandler(tracker_file_name=tracker_file_name, num_retries=0) (small_src_key_as_string, small_src_key) = self.ma...
'Tests handling of a retryable exception'
def test_retryable_exception_recovery(self):
exception = ResumableDownloadHandler.RETRYABLE_EXCEPTIONS[0] harness = CallbackTestHarness(exception=exception) res_download_handler = ResumableDownloadHandler(num_retries=1) dst_fp = self.make_dst_fp() (small_src_key_as_string, small_src_key) = self.make_small_key() small_src_key.get_contents_t...
'Tests handling of a Broken Pipe (which interacts with an httplib bug)'
def test_broken_pipe_recovery(self):
exception = IOError(errno.EPIPE, 'Broken pipe') harness = CallbackTestHarness(exception=exception) res_download_handler = ResumableDownloadHandler(num_retries=1) dst_fp = self.make_dst_fp() (small_src_key_as_string, small_src_key) = self.make_small_key() small_src_key.get_contents_to_file(dst...
'Tests resumable download that fails with a non-retryable exception'
def test_non_retryable_exception_handling(self):
harness = CallbackTestHarness(exception=OSError(errno.EACCES, 'Permission denied')) res_download_handler = ResumableDownloadHandler(num_retries=1) dst_fp = self.make_dst_fp() (small_src_key_as_string, small_src_key) = self.make_small_key() try: small_src_key.get_contents_to_file(dst_fp, c...
'Tests resumable download that fails once and then completes, with tracker file'
def test_failed_and_restarted_download_with_persistent_tracker(self):
harness = CallbackTestHarness() tmpdir = self._MakeTempDir() tracker_file_name = self.make_tracker_file(tmpdir) dst_fp = self.make_dst_fp(tmpdir) (small_src_key_as_string, small_src_key) = self.make_small_key() res_download_handler = ResumableDownloadHandler(tracker_file_name=tracker_file_name, ...
'Tests resumable download that fails twice in one process, then completes'
def test_multiple_in_process_failures_then_succeed(self):
res_download_handler = ResumableDownloadHandler(num_retries=3) dst_fp = self.make_dst_fp() (small_src_key_as_string, small_src_key) = self.make_small_key() small_src_key.get_contents_to_file(dst_fp, res_download_handler=res_download_handler) self.assertEqual(SMALL_KEY_SIZE, get_cur_file_size(dst_fp)...
'Tests resumable download that fails completely in one process, then when restarted completes, using a tracker file'
def test_multiple_in_process_failures_then_succeed_with_tracker_file(self):
harness = CallbackTestHarness(fail_after_n_bytes=(LARGE_KEY_SIZE / 2), num_times_to_fail=2) larger_src_key_as_string = os.urandom(LARGE_KEY_SIZE) larger_src_key = self._MakeKey(data=larger_src_key_as_string) tmpdir = self._MakeTempDir() tracker_file_name = self.make_tracker_file(tmpdir) dst_fp =...
'Tests resumable download that successfully downloads some content before it fails, then restarts and completes'
def test_download_with_inital_partial_download_before_failure(self):
harness = CallbackTestHarness(fail_after_n_bytes=(LARGE_KEY_SIZE / 2)) larger_src_key_as_string = os.urandom(LARGE_KEY_SIZE) larger_src_key = self._MakeKey(data=larger_src_key_as_string) res_download_handler = ResumableDownloadHandler(num_retries=1) dst_fp = self.make_dst_fp() larger_src_key.get...
'Tests downloading a zero-length object (exercises boundary conditions).'
def test_zero_length_object_download(self):
res_download_handler = ResumableDownloadHandler() dst_fp = self.make_dst_fp() k = self._MakeKey() k.get_contents_to_file(dst_fp, res_download_handler=res_download_handler) self.assertEqual(0, get_cur_file_size(dst_fp))
'Tests resumable download with a tracker file containing an invalid etag'
def test_download_with_invalid_tracker_etag(self):
tmp_dir = self._MakeTempDir() dst_fp = self.make_dst_fp(tmp_dir) (small_src_key_as_string, small_src_key) = self.make_small_key() invalid_etag_tracker_file_name = os.path.join(tmp_dir, 'invalid_etag_tracker') f = open(invalid_etag_tracker_file_name, 'w') f.write('3.14159\n') f.close() re...
'Tests resumable download with an inconsistent etag in tracker file'
def test_download_with_inconsistent_etag_in_tracker(self):
tmp_dir = self._MakeTempDir() dst_fp = self.make_dst_fp(tmp_dir) (small_src_key_as_string, small_src_key) = self.make_small_key() inconsistent_etag_tracker_file_name = os.path.join(tmp_dir, 'inconsistent_etag_tracker') f = open(inconsistent_etag_tracker_file_name, 'w') good_etag = small_src_key....
'Tests resumable download with an unwritable tracker file'
def test_download_with_unwritable_tracker_file(self):
tmp_dir = self._MakeTempDir() tracker_file_name = os.path.join(tmp_dir, 'tracker') save_mod = os.stat(tmp_dir).st_mode try: os.chmod(tmp_dir, 0) res_download_handler = ResumableDownloadHandler(tracker_file_name=tracker_file_name) except ResumableDownloadException as e: self.a...
'Tests basic read/write to keys.'
def test_read_write(self):
bucket = self._MakeBucket() bucket_name = bucket.name bucket = self._GetConnection().get_bucket(bucket_name) key_name = 'foobar' k = bucket.new_key(key_name) s1 = 'This is a test of file upload and download' k.set_contents_from_string(s1) tmpdir = self._MakeTempDi...
'Tests get_all_keys.'
def test_get_all_keys(self):
phony_mimetype = 'application/x-boto-test' headers = {'Content-Type': phony_mimetype} tmpdir = self._MakeTempDir() fpath = os.path.join(tmpdir, 'foobar1') fpath2 = os.path.join(tmpdir, 'foobar') with open(fpath2, 'w') as f: f.write('test-data') bucket = self._MakeBucket() k = buc...
'Test the bucket lookup method.'
def test_bucket_lookup(self):
bucket = self._MakeBucket() k = bucket.new_key('foo/bar') phony_mimetype = 'application/x-boto-test' headers = {'Content-Type': phony_mimetype} k.set_contents_from_string('testdata', headers) k = bucket.lookup('foo/bar') self.assertIsInstance(k, bucket.key_class) self.assertEqual(k.conte...
'Test key metadata operations.'
def test_metadata(self):
bucket = self._MakeBucket() k = self._MakeKey(bucket=bucket) key_name = k.name s1 = 'This is a test of file upload and download' mdkey1 = 'meta1' mdval1 = 'This is the first metadata value' k.set_metadata(mdkey1, mdval1) mdkey2 = 'meta2' mdval2 ...
'Test list and iterator.'
def test_list_iterator(self):
bucket = self._MakeBucket() num_iter = len([k for k in bucket.list()]) rs = bucket.get_all_keys() num_keys = len(rs) self.assertEqual(num_iter, num_keys)
'Test bucket and key ACLs.'
def test_acl(self):
bucket = self._MakeBucket() bucket.set_acl('public-read') acl = bucket.get_acl() self.assertEqual(len(acl.entries.entry_list), 2) bucket.set_acl('private') acl = bucket.get_acl() self.assertEqual(len(acl.entries.entry_list), 1) k = self._MakeKey(bucket=bucket) k.set_acl('public-read'...
'Test set/get raw logging subresource.'
def test_logging(self):
bucket = self._MakeBucket() empty_logging_str = "<?xml version='1.0' encoding='UTF-8'?><Logging/>" logging_str = (("<?xml version='1.0' encoding='UTF-8'?><Logging><LogBucket>log-bucket</LogBucket>" + '<LogObjectPrefix>example</LogObjectPrefix>') + '</Logging>') bucket.set_subresource('loggin...
'Test copying a key from one bucket to another.'
def test_copy_key(self):
bucket1 = self._MakeBucket() bucket2 = self._MakeBucket() bucket_name_1 = bucket1.name bucket_name_2 = bucket2.name bucket1 = self._GetConnection().get_bucket(bucket_name_1) bucket2 = self._GetConnection().get_bucket(bucket_name_2) key_name = 'foobar' k1 = bucket1.new_key(key_name) s...
'Test default object acls.'
def test_default_object_acls(self):
bucket = self._MakeBucket() acl = bucket.get_def_acl() self.assertIsNotNone(re.search(PROJECT_PRIVATE_RE, acl.to_xml())) bucket.set_def_acl('public-read') acl = bucket.get_def_acl() public_read_acl = acl self.assertEqual(acl.to_xml(), '<AccessControlList><Entries><Entry><Scope type="AllUs...
'Test default object acls using storage_uri.'
def test_default_object_acls_storage_uri(self):
bucket = self._MakeBucket() bucket_name = bucket.name uri = storage_uri(('gs://' + bucket_name)) acl = uri.get_def_acl() self.assertIsNotNone(re.search(PROJECT_PRIVATE_RE, acl.to_xml()), ('PROJECT_PRIVATE_RE not found in ACL XML:\n' + acl.to_xml())) uri.set_def_acl('public-read') ...
'Test setting and getting of CORS XML documents on Bucket.'
def test_cors_xml_bucket(self):
bucket = self._MakeBucket() bucket_name = bucket.name bucket = self._GetConnection().get_bucket(bucket_name) cors = re.sub('\\s', '', bucket.get_cors().to_xml()) self.assertEqual(cors, CORS_EMPTY) bucket.set_cors(CORS_DOC) cors = re.sub('\\s', '', bucket.get_cors().to_xml()) self.assertE...
'Test setting and getting of CORS XML documents with storage_uri.'
def test_cors_xml_storage_uri(self):
bucket = self._MakeBucket() bucket_name = bucket.name uri = storage_uri(('gs://' + bucket_name)) cors = re.sub('\\s', '', uri.get_cors().to_xml()) self.assertEqual(cors, CORS_EMPTY) cors_obj = Cors() h = handler.XmlHandler(cors_obj, None) xml.sax.parseString(CORS_DOC, h) uri.set_cors...
'Test setting and getting of lifecycle config on Bucket.'
def test_lifecycle_config_bucket(self):
bucket = self._MakeBucket() bucket_name = bucket.name bucket = self._GetConnection().get_bucket(bucket_name) xml = bucket.get_lifecycle_config().to_xml() self.assertEqual(xml, LIFECYCLE_EMPTY) lifecycle_config = LifecycleConfig() lifecycle_config.add_rule('Delete', None, LIFECYCLE_CONDITIONS...
'Test setting and getting of lifecycle config with storage_uri.'
def test_lifecycle_config_storage_uri(self):
bucket = self._MakeBucket() bucket_name = bucket.name uri = storage_uri(('gs://' + bucket_name)) xml = uri.get_lifecycle_config().to_xml() self.assertEqual(xml, LIFECYCLE_EMPTY) lifecycle_config = LifecycleConfig() lifecycle_config.add_rule('Delete', None, LIFECYCLE_CONDITIONS_FOR_DELETE_RUL...
'run one iteration of a simple decision engine'
def run_decider(self):
tries = 0 while True: dtask = self.conn.poll_for_decision_task(self._domain, self._task_list, reverse_order=True) if (dtask.get('taskToken') is not None): break time.sleep(2) tries += 1 if (tries > 10): assert False, 'no decision task occu...
'run one iteration of a simple worker engine'
def run_worker(self):
tries = 0 while True: atask = self.conn.poll_for_activity_task(self._domain, self._task_list, identity='test worker') if (atask.get('activityId') is not None): break time.sleep(2) tries += 1 if (tries > 10): assert False, 'no activity task...
'Subclasses should override this method to do a service call that will always succeed (like fetch a list, even if it\'s empty).'
def sample_service_call(self, conn):
pass
'Creates a named load balancer that can be safely deleted at the end of each test'
def setUp(self):
self.conn = ELBConnection() self.name = 'elb-boto-unit-test' self.availability_zones = ['us-east-1a'] self.listeners = [(80, 8000, 'HTTP')] self.balancer = self.conn.create_load_balancer(self.name, self.availability_zones, self.listeners) self.s3 = boto.connect_s3() self.timestamp = str(int(...
'Deletes the test load balancer after every test. It does not delete EVERY load balancer in your account'
def tearDown(self):
self.balancer.delete()
'Helper to run clean up tasks after instances are removed.'
def post_terminate_cleanup(self):
for (fn, args) in self.post_terminate_cleanups: fn(*args) time.sleep(10) if self.vpc: self.api.delete_vpc(self.vpc.id)
'Helper to remove all instances and kick off additional cleanup once they are terminated.'
def terminate_instances(self):
for instance in self.instances: self.terminate_instance(instance) self.post_terminate_cleanup()
'Test that health checks cannot be created with an invalid \'request_interval\'.'
def test_create_health_check_invalid_request_interval(self):
self.assertRaises(AttributeError, (lambda : HealthCheck(**self.health_check_params(request_interval=5))))
'Test that health checks cannot be created with an invalid \'failure_threshold\'.'
def test_create_health_check_invalid_failure_threshold(self):
self.assertRaises(AttributeError, (lambda : HealthCheck(**self.health_check_params(failure_threshold=0)))) self.assertRaises(AttributeError, (lambda : HealthCheck(**self.health_check_params(failure_threshold=11))))
'Tests the "lookup" function with just a hash key'
def test_lookup_hash(self):
expected = {'Item': {'username': {'S': 'johndoe'}, 'first_name': {'S': 'John'}, 'last_name': {'S': 'Doe'}, 'date_joined': {'N': '1366056668'}, 'friend_count': {'N': '3'}, 'friends': {'SS': ['alice', 'bob', 'jane']}}} self.users.schema = [HashKey('username'), RangeKey('date_joined', data_type=NUMBER)] with m...
'Test the "lookup" function with a hash and range key'
def test_lookup_hash_and_range(self):
expected = {'Item': {'username': {'S': 'johndoe'}, 'first_name': {'S': 'John'}, 'last_name': {'S': 'Doe'}, 'date_joined': {'N': '1366056668'}, 'friend_count': {'N': '3'}, 'friends': {'SS': ['alice', 'bob', 'jane']}}} self.users.schema = [HashKey('username'), RangeKey('date_joined', data_type=NUMBER)] with m...
'Verify the actual parameters sent to the service API.'
def assert_request_parameters(self, params, ignore_params_values=None):
request_params = self.actual_request.params.copy() if (ignore_params_values is not None): for param in ignore_params_values: try: del request_params[param] except KeyError: pass self.assertDictEqual(request_params, params)
'Check returned metadata is parsed correctly'
def test_cloudsearch_results_meta(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') self.assertEqual(results.hits, 30) self.assertEqual(results.docs[0]['fields']['rank'], 1)
'Check num_pages_needed is calculated correctly'
def test_cloudsearch_results_info(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') self.assertEqual(results.num_pages_needed, 3.0)
'Check that information objects are passed back through the API correctly.'
def test_cloudsearch_results_matched(self):
search = SearchConnection(endpoint=HOSTNAME) query = search.build_query(q='Test') results = search(query) self.assertEqual(results.search_service, search) self.assertEqual(results.query, query)
'Check that documents are parsed properly from AWS'
def test_cloudsearch_results_hits(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') hits = list(map((lambda x: x['id']), results.docs)) self.assertEqual(hits, ['12341', '12342', '12343', '12344', '12345', '12346', '12347'])
'Check the results iterator'
def test_cloudsearch_results_iterator(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') results_correct = iter(['12341', '12342', '12343', '12344', '12345', '12346', '12347']) for x in results: self.assertEqual(x['id'], next(results_correct))