desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Tests index updates in real-time.'
@async_test def testRealTimeIndexing(self):
def _QueryAndVerify(p, barrier_cb, query, is_in): def _Verify(keys): ids = [key.hash_key for key in keys] if is_in: self.assertTrue((p.photo_id in ids)) else: self.assertFalse((p.photo_id in ids)) barrier_cb() Photo.Inde...
'Tests metaphone queries.'
@async_test @unittest.skipIf((platform.python_implementation() == 'PyPy'), 'metaphone queries broken on pypy') def testMetaphoneQueries(self):
def _QueryAndVerify(p, barrier_cb, query_expr, match): def _Verify(keys): ids = [key.hash_key for key in keys] if match: self.assertTrue((p.photo_id in ids)) else: self.assertFalse(ids) barrier_cb() Photo.IndexQueryKeys(...
'Tests location queries.'
@async_test def disabled_t_estLocationQueries(self):
def _QueryAndVerify(episode_ids, barrier_cb, loc_search, matches): def _Verify(keys): ids = [key.hash_key for key in keys] self.assertEqual(len(ids), len(matches)) [self.assertTrue((episode_ids[m] in ids)) for m in matches] barrier_cb() Episode.IndexQu...
'Tests placemark queries.'
@async_test def disabled_t_estPlacemarkQueries(self):
def _QueryAndVerify(episode_ids, barrier_cb, search, matches): def _Verify(keys): ids = [key.hash_key for key in keys] self.assertEqual(len(ids), len(matches)) [self.assertTrue((episode_ids[m] in ids)) for m in matches] barrier_cb() Episode.IndexQueryK...
'Tests querying of User objects.'
@async_test def testQuerying(self):
def _QueryAndVerify(barrier_cb, query_expr, id_set): def _Verify(keys): ids = [key.hash_key for key in keys] if (not id_set): self.assertFalse(ids) else: [self.assertTrue((i in id_set)) for i in ids] barrier_cb() User.In...
'Tests start_key, end_key, and limit support in IndexQueryKeys and IndexQuery.'
@async_test def testRangeSupport(self):
name = 'Rumpelstiltskin' vp_id = 'v0' def _QueryAndVerify(cls, barrier_cb, query_expr, start_key, end_key, limit): def _FindIndex(list, db_key): for (i, item) in enumerate(list): if (item.GetKey() == db_key): return i return (-1) de...
'Test various interesting Unicode characters.'
def testUnicode(self):
base_name = escape.utf8(u'\xe0\xe0\xe0\u670b\u53cb\u4f60\u597dabc123\U00010000\U00010000\x00\x01\x08\n DCTB ') timestamp = time.time() contact_id_lookup = dict() def _CreateContact(index): name = (base_name + str(index)) identity_key = ('Email:%s' % name) return Contact.Creat...
'Try to update permission labels to the empty set.'
def testUpdatePermissions(self):
follower_dict = {'user_id': 1, 'viewpoint_id': 'vp1', 'labels': [Follower.ADMIN]} follower = self.UpdateDBObject(Follower, **follower_dict) self.assertRaises(PermissionError, follower.SetLabels, [])
'Sets up _client as a test emulation of DynamoDB. Creates the full database schema, a test user, and two devices (one for mobile, one for web-application).'
def setUp(self):
options.options.localdb = True options.options.fileobjstore = True options.options.localdb_dir = '' super(DBBaseTestCase, self).setUp() options.options.localdb_dir = '' self._client = local_client.LocalClient(vf_schema.SCHEMA) object_store.InitObjectStore(temporary=True) self._temp_dir =...
'Cleanup after test is complete.'
def tearDown(self):
self._RunAsync(server_log.LogBatchPersistor.Instance().close) self._RunAsync(OpManager.Instance().Drain) shutil.rmtree(self._temp_dir) super(DBBaseTestCase, self).tearDown() self.assertIs(Operation.GetCurrent().operation_id, None)
'Update (or create if it doesn\'t exist) a DB object. Returns the object.'
def UpdateDBObject(self, cls, **db_dict):
o = cls.CreateFromKeywords(**db_dict) self._RunAsync(o.Update, self._client) return o
'Creates a new, registered user from the fields in "user_dict". If "device_dict" is defined, then creates a new device from those fields. Returns a tuple containing the new user and device (if "device_dict" was given).'
def _CreateUserAndDevice(self, user_dict, ident_dict, device_dict=None):
webapp_dev_id = self._RunAsync(Device._allocator.NextId, self._client) (user, identity) = self._RunAsync(User.CreateProspective, self._client, user_dict['user_id'], webapp_dev_id, ident_dict['key'], util._TEST_TIME) user = self._RunAsync(User.Register, self._client, user_dict, ident_dict, util._TEST_TIME, r...
'Verifies detection of multiple corruption issues.'
def testMultipleCorruptions(self):
self._CreateTestViewpoint('vp1', self._user.user_id, [], delete_followed=True) self._CreateTestViewpoint('vp2', self._user.user_id, [], delete_followed=True) self._RunAsync(self._checker.CheckAllViewpoints) corruption_text = ' ---- viewpoint vp1 ----\n missing followed (1 ...
'Verifies the --email command line option.'
def testEmail(self):
self._CreateTestViewpoint('vp1', self._user.user_id, [], delete_followed=True) options.options.email = 'kimball.andy@emailscrubbed.com' self._RunAsync(self._checker.CheckAllViewpoints) corruption_text = ' ---- viewpoint vp1 ----\n missing followed (1 instance)\n em...
'Test running dbchk with locking.'
def testExclusiveLock(self):
self._CreateTestViewpoint('vp1', self._user.user_id, []) self._RunAsync(self._checker.CheckAllViewpoints) corruption_text = ' ---- viewpoint vp1 ----\n empty viewpoint (1 instance)\n\npython dbchk.py --devbox --repair=True --viewpoints=vp1' self.assertEqual(se...
'Test detection of last scan and smart-scan setting.'
def testSmartScan(self):
vp1 = self._RunAsync(Viewpoint.Query, self._client, self._user.private_vp_id, None) vp1.last_updated = (time.time() - constants.SECONDS_PER_DAY) self._RunAsync(vp1.Update, self._client) vp2 = self._RunAsync(Viewpoint.Query, self._client, self._user2.private_vp_id, None) vp2.last_updated = (time.time...
'Verifies detection of empty viewpoint records.'
def testEmptyViewpoints(self):
def _Validate(viewpoint_id): self._validator.ValidateDeleteDBObject(Follower, DBKey(self._user.user_id, viewpoint_id)) self._validator.ValidateDeleteDBObject(Follower, DBKey(self._user2.user_id, viewpoint_id)) sort_key = Followed.CreateSortKey(viewpoint_id, 0) self._validator.Validat...
'Verifies detection of invalid viewpoint metadata.'
def testInvalidViewpointMetadata(self):
viewpoint = self._CreateTestViewpoint('vp1', self._user.user_id, []) self._RunAsync(Activity.CreateShareNew, self._client, self._user.user_id, 'vp1', 'a1', (time.time() - 10), 0, [{'new_episode_id': 'ep1', 'photo_ids': []}], []) viewpoint = Viewpoint.CreateFromKeywords(viewpoint_id='vp1') viewpoint._col...
'Verifies detection and repair of missing Followed records.'
def testMissingFollowed(self):
def _Validate(follower_id, viewpoint_id, last_updated): sort_key = Followed.CreateSortKey(viewpoint_id, last_updated) self._validator.ValidateCreateDBObject(Followed, user_id=follower_id, sort_key=sort_key, date_updated=Followed._TruncateToDay(last_updated), viewpoint_id=viewpoint_id) invali...
'Verifies detection of multiple share_new activities.'
def testMultipleShareNew(self):
self._CreateTestViewpoint('vp1', self._user.user_id, [self._user2.user_id]) self._RunAsync(Activity.CreateShareNew, self._client, self._user.user_id, 'vp1', 'a1', (time.time() + 1), 0, [{'new_episode_id': 'ep2', 'photo_ids': []}], [self._user2.user_id]) self._RunAsync(Activity.CreateShareNew, self._client, ...
'Verifies detection of missing activities.'
def testMissingActivities(self):
self._CreateTestViewpoint('vp1', self._user.user_id, [self._user2.user_id]) self._CreateTestEpisode('vp1', 'ep1', self._user.user_id) self._CreateTestEpisode('vp1', 'ep2', self._user.user_id) self._CreateTestEpisode('vp1', 'ep3', self._user.user_id) self._CreateTestViewpoint('vp2', self._user.user_i...
'Verifies detection of activities that refer to some missing posts.'
def testMissingSomePosts(self):
self._CreateTestViewpoint('vp1', self._user.user_id, []) self._CreateTestEpisode('vp1', 'ep1', self._user.user_id) self._CreateTestPhotoAndPosts('ep1', self._user.user_id, {'photo_id': 'p10'}) self._RunAsync(Activity.CreateShareNew, self._client, self._user.user_id, 'vp1', 'a1', (time.time() + 1), 0, [{...
'Verifies detection of activities that refer to all missing posts from an episode.'
def testMissingAllPostsFromEpisode(self):
self._CreateTestViewpoint('vp1', self._user.user_id, []) self._CreateTestEpisode('vp1', 'ep1', self._user.user_id) self._RunAsync(Activity.CreateShareNew, self._client, self._user.user_id, 'vp1', 'a1', (time.time() + 1), 0, [{'new_episode_id': 'ep1', 'photo_ids': ['p10', 'p11']}], [self._user2.user_id]) ...
'Verifies detection and repair of bad accounting entries at the viewpoint level. We also test user-level OWNED_BY since it\'s a 1-1 mapping with default viewpoint:OWNED_BY.'
def testBadViewpointAccounting(self):
accounting = {} ph_dicts = [{'photo_id': 'p0', 'tn_size': 1, 'med_size': 10, 'full_size': 100, 'orig_size': 1000}, {'photo_id': 'p1', 'tn_size': 2, 'med_size': 20, 'full_size': 200, 'orig_size': 2000}, {'photo_id': 'p2', 'tn_size': 4, 'med_size': 40, 'full_size': 400, 'orig_size': 4000}, {'photo_id': 'p3', 'tn_...
'Verifies detection and repair of bad accounting entries at the user level.'
def testBadUserAccounting(self):
ph_dicts = [{'photo_id': 'p0', 'tn_size': 1, 'med_size': 10, 'full_size': 100, 'orig_size': 1000}, {'photo_id': 'p1', 'tn_size': 2, 'med_size': 20, 'full_size': 200, 'orig_size': 2000}] self._CreateTestViewpoint('vp1', self._user.user_id, [self._user2.user_id]) self._CreateTestEpisode('vp1', 'ep1', self._us...
'Verifies detection and repair of bad accounting entries at the user level for a REMOVED follower.'
def testBadRemovedUserAccounting(self):
ph_dicts = [{'photo_id': 'p0', 'tn_size': 1, 'med_size': 10, 'full_size': 100, 'orig_size': 1000}, {'photo_id': 'p1', 'tn_size': 2, 'med_size': 20, 'full_size': 200, 'orig_size': 2000}] self._CreateTestViewpoint('vp1', self._user.user_id, []) self._RunAsync(Activity.CreateShareNew, self._client, self._user....
'Test various corruption code paths for bad cover_photos.'
def testBadCoverPhoto(self):
ph_dicts = [{'photo_id': 'p0'}, {'photo_id': 'p1'}, {'photo_id': 'p2'}] self._CreateTestEpisode(self._user.private_vp_id, 'ep1', self._user.user_id) self._CreateTestPhotoAndPosts('ep1', self._user.user_id, ph_dicts[0], unshared=True) self._CreateTestPhotoAndPosts('ep1', self._user.user_id, ph_dicts[1], ...
'Create viewpoint_id for testing purposes.'
def _CreateTestViewpoint(self, viewpoint_id, user_id, follower_ids, delete_followed=False):
vp_dict = {'viewpoint_id': viewpoint_id, 'user_id': user_id, 'timestamp': util._TEST_TIME, 'last_updated': util._TEST_TIME, 'type': Viewpoint.EVENT} (viewpoint, _) = self._RunAsync(Viewpoint.CreateNewWithFollowers, self._client, follower_ids, **vp_dict) if delete_followed: for f_id in ([user_id] + f...
'Create episode for testing purposes.'
def _CreateTestEpisode(self, viewpoint_id, episode_id, user_id):
ep_dict = {'episode_id': episode_id, 'user_id': user_id, 'viewpoint_id': viewpoint_id, 'publish_timestamp': time.time(), 'timestamp': time.time()} return self._RunAsync(Episode.CreateNew, self._client, **ep_dict)
'Create comment for testing purposes.'
def _CreateTestComment(self, viewpoint_id, comment_id, user_id, message):
comment = Comment.CreateFromKeywords(viewpoint_id=viewpoint_id, comment_id=comment_id, user_id=user_id, message=message) self._RunAsync(comment.Update, self._client) return comment
'Create photo/post/user_post for testing purposes.'
def _CreateTestPhotoAndPosts(self, episode_id, user_id, ph_dict, unshared=False, removed=False):
self._CreateTestPhoto(ph_dict) self._CreateTestPost(episode_id, ph_dict['photo_id'], unshared=unshared, removed=removed)
'Create post for testing purposes.'
def _CreateTestPost(self, episode_id, photo_id, unshared=False, removed=False):
post = Post.CreateFromKeywords(episode_id=episode_id, photo_id=photo_id) if unshared: post.labels.add(Post.UNSHARED) if (unshared or removed): post.labels.add(Post.REMOVED) self._RunAsync(post.Update, self._client)
'Create photo for testing purposes.'
def _CreateTestPhoto(self, ph_dict):
photo = Photo.CreateFromKeywords(**ph_dict) self._RunAsync(photo.Update, self._client)
'Create accounting entry for testing purposes.'
def _CreateTestAccounting(self, act):
self._RunAsync(act.Update, self._client)
'Updates a viewpoint with the given selected cover_photo.'
def _SetCoverPhotoOnViewpoint(self, viewpoint_id, episode_id, photo_id):
viewpoint = self._RunAsync(Viewpoint.Query, self._client, viewpoint_id, None) viewpoint.cover_photo = Viewpoint.ConstructCoverPhoto(episode_id, photo_id) self._RunAsync(viewpoint.Update, self._client)
'Call dbchk.Dispatch after setting the specified options.'
def _RunDbChk(self, option_dict=None):
if option_dict: [setattr(options.options, name, value) for (name, value) in option_dict.iteritems()] self._RunAsync(dbchk.Dispatch, self._client)
'Creates a episode with id pre-allocated on mobile device. Then updates the episode.'
def testCreateAndUpdate(self):
with EnterOpContext(Operation(1, 'o1')): timestamp = time.time() episode_id = Episode.ConstructEpisodeId(timestamp, self._mobile_dev.device_id, 15) ep_dict = {'user_id': self._user.user_id, 'episode_id': episode_id, 'viewpoint_id': self._user.private_vp_id, 'timestamp': time.time(), 'publish...
'Create an episode in a non-default viewpoint.'
def testAnotherViewpoint(self):
vp_dict = {'viewpoint_id': 'vp1', 'user_id': 1, 'timestamp': time.time(), 'type': Viewpoint.EVENT} self._RunAsync(Viewpoint.CreateNew, self._client, **vp_dict) ep_dict = {'viewpoint_id': 'vp1', 'episode_id': 'ep1', 'user_id': 1, 'timestamp': 100, 'publish_timestamp': 100} episode = self._RunAsync(Episod...
'Explicit migration.'
def testMaybeMigrate(self):
(obj_list, _) = self._RunAsync(TestRename.Scan, self._client, col_names=None) for obj in obj_list: self._RunAsync(Version.MaybeMigrate, self._client, obj, [TEST_VERSION, TEST_VERSION2]) (obj_list, _) = self._RunAsync(TestRename.Scan, self._client, col_names=None) self._Validate(obj_list[0], obj_...
'Test the upgrade.py tool against the TestRename table.'
def testUpgradeTool(self):
options.options.migrator = 'TEST_VERSION' self._RunAsync(upgrade.UpgradeTable, self._client, TestRename._table) options.options.migrator = 'TEST_VERSION2' self._RunAsync(upgrade.UpgradeTable, self._client, TestRename._table) list = self._RunAsync(TestRename.RangeQuery, self._client, 't1', range_desc...
'Test migration with mutations turned off.'
@async_test def testNoMutation(self):
def _OnQuery(o): Version.SetMutateItems(True) assert (o.attr0 is None), o.attr0 assert (o.attr1 == 1000), o.attr1 assert (o._version == 0), o._version self.stop() def _OnUpgrade(): TestRename.KeyQuery(self._client, DBKey(hash_key='t1', range_key=1), col_names=['at...
'Verify that comments sort ascending by timestamp.'
def testSortOrder(self):
timestamp = time.time() comment_id1 = Comment.ConstructCommentId(timestamp, 0, 0) comment_id2 = Comment.ConstructCommentId((timestamp + 1), 0, 0) self.assertGreater(comment_id2, comment_id1)
'Test basic locking mechanism.'
def testLocking(self):
job1 = Job(self._client, 'test_job') self.assertTrue(self._RunAsync(job1.AcquireLock)) job2 = Job(self._client, 'test_job') self.assertFalse(self._RunAsync(job2.AcquireLock)) self._RunAsync(job1._lock.Abandon, self._client) job1._lock = None self.assertFalse(self._RunAsync(job2.AcquireLock, ...
'Test fetching/writing metrics.'
def testMetrics(self):
job = Job(self._client, 'test_job') prev_runs = self._RunAsync(job.FindPreviousRuns) self.assertEqual(len(prev_runs), 0) other_job = Job(self._client, 'other_test_job') other_job.Start() self._RunAsync(other_job.RegisterRun, Job.STATUS_SUCCESS) other_job.Start() self._RunAsync(other_job....
'Creates a user with just a given name.'
def testPartialCreate(self):
user_dict = {'user_id': 5, 'given_name': 'Spencer'} (user, device) = self._CreateUserAndDevice(user_dict=user_dict, ident_dict={'key': 'Email:spencer.kimball@foo.com', 'authority': 'Test'}, device_dict=None) user._version = None user.signing_key = None user_dict['labels'] = [User.REGISTERED] use...
'Creates a user via an OAUTH user dictionary.'
def testRegister(self):
(u, dev) = self._CreateUserAndDevice(user_dict={'user_id': 4, 'given_name': 'Spencer', 'family_name': 'Kimball', 'locale': 'en:US'}, ident_dict={'key': 'Local:0_0.1', 'authority': 'Test'}, device_dict={'device_id': 20, 'version': 'alpha-1.0', 'os': 'iOS 5.0.1', 'platform': 'iPhone 4S', 'country': 'US', 'langu...
'Register from web application.'
def testRegisterViaWebApp(self):
(u, dev) = self._CreateUserAndDevice(user_dict={'user_id': 4, 'name': 'Spencer Kimball'}, ident_dict={'key': 'Test:1', 'authority': 'Test'}, device_dict=None) self.assertEqual(u.name, 'Spencer Kimball') self.assertTrue((u.webapp_dev_id > 0)) self.assertIsNone(dev)
'Register with no mobile device, then add one.'
def testAddDevice(self):
(u, dev) = self._CreateUserAndDevice(user_dict={'user_id': 4, 'name': 'Spencer Kimball'}, ident_dict={'key': 'Local:1', 'authority': 'Test'}, device_dict=None) (u2, dev2) = self._CreateUserAndDevice(user_dict={'user_id': 4}, ident_dict={'key': 'Local:1', 'authority': 'Test'}, device_dict={'device_id': 30}) ...
'Update a user.'
def testQueryUpdate(self):
(u, d) = self._CreateDefaultUser() (u2, d2) = self._CreateUserAndDevice(user_dict={'user_id': u.user_id, 'email': 'spencer.kimball@emailscrubbed.com'}, ident_dict={'key': 'Email:spencer@emailscrubbed.com', 'authority': 'Facebook'}, device_dict=None) self.assertEqual(u.email, u2.email)
'Verify the per-device allocation of user ids.'
def testAllocateAssetIds(self):
self._RunAsync(User.AllocateAssetIds, self._client, self._user.user_id, 5) user = self._RunAsync(User.Query, self._client, self._user.user_id, None) self.assertEqual(user.asset_id_seq, 6) self._RunAsync(User.AllocateAssetIds, self._client, self._user.user_id, 100) user = self._RunAsync(User.Query, s...
'Test query of partial row data.'
def testPartialQuery(self):
(u, dev) = self._CreateDefaultUser() u2 = self._RunAsync(User.Query, self._client, u.user_id, ['given_name', 'family_name']) self.assertEqual(u2.email, None) self.assertEqual(u2.given_name, u.given_name) self.assertEqual(u2.family_name, u.family_name)
'Test query of a non-existent user.'
def testMissing(self):
try: self._RunAsync(User.Query, self._client, (1L << 63), None) assert False, 'user query should fail with missing key' except Exception as e: pass
'Verify the health report generation and retrieval.'
@async_test def testHealthReport(self):
cluster_name = 'test' interval = MetricInterval('testint', 60) group_key = Metric.EncodeGroupKey(cluster_name, interval) num_machines = 5 num_samples = (TREND_SAMPLE_SIZE + 1) fake_time = 0 def fake_time_func(): return fake_time managers = [] criteria_list = [] criteria_c...
'Verify the health reports with no data are properly saved to the db.'
@async_test def testEmptyHealthReport(self):
cluster_name = 'test' interval = MetricInterval('testint', 60) group_key = Metric.EncodeGroupKey(cluster_name, interval) num_machines = 5 num_samples = (TREND_SAMPLE_SIZE + 1) managers = [] criteria_list = [] criteria_called = [0] def _blankCriteria(): criteria_called[0] += 1...
'Verify that multiple applies for the same operation ID only increment the stats once.'
def testOperationReplay(self):
act = Accounting.CreateViewpointOwnedBy('vp1', 1) act.num_photos = 1 op = Operation(1, 'o1') with EnterOpContext(op): self._RunAsync(Accounting.ApplyAccounting, self._client, act) accounting = self._RunAsync(Accounting.Query, self._client, act.hash_key, act.sort_key, None) assert...
'Test the optional indexer expansion settings.'
def testOptions(self):
value = 'one two three' pos_single = [[0], [1], [2]] pos_mphone = [[0], [1], [2], [2]] self._VerifyIndex(FullTextIndexer(metaphone=Indexer.Option.NO), value, ['te:one', 'te:two', 'te:three'], pos_single) self._VerifyIndex(FullTextIndexer(metaphone=Indexer.Option.YES), value, ['te:one', 'te:two...
'Verifies operation of the full-text indexer, including stop words, punctuation separation and position lists.'
def testFullTextIndexer(self):
tok = FullTextIndexer() self._VerifyIndex(tok, 'one two three', ['te:one', 'te:two', 'te:three'], [[0], [1], [2]]) self._VerifyIndex(tok, 'one-two.three', ['te:one', 'te:two', 'te:three'], [[0], [1], [2]]) self._VerifyIndex(tok, 'one_two=three', ['te:one', 'te:two', 'te:three'], [[0], [1], [2]]) ...
'Verifies query string generation.'
def testQueryString(self):
indexer = SecondaryIndexer() self.assertEqual(indexer.GetQueryString(self.col, 'foo'), '"te:foo"') tok = FullTextIndexer() self.assertEqual(tok.GetQueryString(self.col, 'foo'), 'te:foo') self.assertEqual(tok.GetQueryString(self.col, 'foo bar'), '(te:foo + te:bar)') self.assertEqual(tok....
'Verifies position works up to 2^16 words and then is ignored after.'
def TestLongPosition(self):
tok = FullTextIndexer() value = (('test ' * (1 << (16 + 1))) + 'test2') positions = [range((1 << 16)), []] self._VerifyIndex(tok, value, ['te:test', 'te:test2'], positions)
'Test secondary indexer emits column values.'
def testSecondaryIndexer(self):
indexer = SecondaryIndexer() self._VerifyIndex(indexer, 'foo', ['te:foo'], None) self._VerifyIndex(indexer, 'bar', ['te:bar'], None) self._VerifyIndex(indexer, 'baz', ['te:baz'], None)
'Unit test the CryptColumn object.'
def testCryptColumn(self):
def _Roundtrip(value): self._crypt_inst.Set(value) self.assertTrue(((value is None) or self._crypt_inst.IsModified())) delayed_value = self._crypt_inst.Get() if (value is None): self.assertIsNone(delayed_value) else: self.assertEqual(delayed_value, del...
'Verify that db_crypt key can be rotated.'
def testDbKeyRotation(self):
@contextmanager def _OverrideSecret(secret, secret_value): try: old_secret_value = secrets.GetSharedSecretsManager()._secrets[secret] secrets.GetSharedSecretsManager()._secrets[secret] = secret_value if hasattr(_CryptValue, '_crypter'): del _CryptValue...
'Verify round-trip of various post-ids.'
def testPostIdConstruction(self):
def _RoundTripPostId(original_episode_id, original_photo_id): post_id = Post.ConstructPostId(original_episode_id, original_photo_id) (new_episode_id, new_photo_id) = Post.DeconstructPostId(post_id) self.assertEqual(original_episode_id, new_episode_id) self.assertEqual(original_photo_...
'Verify that post_id sorts like (episode_id, photo_id) does.'
def testPostIdOrdering(self):
def _Compare(episode_id1, photo_id1, episode_id2, photo_id2): result = cmp(episode_id1, episode_id2) if (result == 0): result = cmp(photo_id1, photo_id2) post_id1 = Post.ConstructPostId(episode_id1, photo_id1) post_id2 = Post.ConstructPostId(episode_id2, photo_id2) ...
'Clears all rows from the \'Test\' DynamoDB table.'
def setUp(self):
super(DynamoDBClientTestCase, self).setUp() options.options.domain = 'goviewfinder.com' secrets.InitSecretsForTest() self._client = dynamodb_client.DynamoDBClient(schema=vf_schema.SCHEMA) self._ClearTestTable(self.stop) self.wait(timeout=30)
'Put an item and verify get.'
@async_test_timeout(timeout=30) def testPutAndGet(self):
exp_attrs = {u'a0': ((2 ** 64) + 1), u'a1': 1354137666.996147, u'a2': u'test value\xe0\u670b'} def _VerifyGet(barrier_cb, result): self.assertEqual(exp_attrs, result.attributes) self.assertEqual(result.read_units, 0.5) barrier_cb() def _VerifyConsistentGet(barrier_cb, result): ...
'Verify operation with various attribute values.'
@async_test_timeout(timeout=30) def testPutValues(self):
def _VerifyGet(result): self.assertEqual({u'a1': 0, u'a2': u'str', u'a3': set([0]), u'a4': set([u'str\xe0\u670b'])}, result.attributes) self.assertEqual(result.read_units, 0.5) self.stop() def _OnPut(result): self._client.GetItem(table=_table.name, key=DBKey(u'1', 1), callback=_V...
'Update an item multiple times, varying update actions and return_values.'
@async_test_timeout(timeout=30) def testUpdate(self):
def _OnFourthUpdate(result): self.assertEquals(result.write_units, 1) self.assertEquals(result.return_values, {u'thk': u'2', u'trk': 2, u'a1': 10, u'a2': 'update str 2', u'a3': set([1, 2, 3, 4, 5, 6])}) self.stop() def _OnThirdUpdate(result): self.assertEquals(result.write_...
'Update an item with no attributes set, other than the key. This should result in a false-positive from dynamodb that the record was updated, even though the record is not actually created.'
@async_test_timeout(timeout=30) def testUpdateNoAttributes(self):
def _VerifyGet(result): self.assertFalse((result == True)) self.stop() def _OnUpdate(result): self.assertEquals(result.write_units, 1) self._client.GetItem(table=_table.name, key=DBKey(u'2', 2), attributes=[u'a1', u'a2'], must_exist=False, callback=_VerifyGet) self._client.Up...
'Update an item by deleting its attributes.'
@async_test_timeout(timeout=30) def testUpdateWithDelete(self):
def _OnDeleteUpdate(result): self.assertEquals(result.write_units, 1) self.assertEquals(result.return_values, {u'a0': 1, u'thk': u'2', u'trk': 2}) self.stop() def _OnUpdate(result): self.assertEquals(result.write_units, 1) self._client.UpdateItem(table=_table.name, key=DB...
'Adds a range of values and queries with start key and limit.'
@async_test_timeout(timeout=30) def testQuery(self):
num_items = 10 def _OnQuery(exp_count, result): for i in xrange(exp_count): self.assertEqual(len(result.items), exp_count) self.assertEqual(result.items[i], {u'thk': u'test_query', u'trk': i, u'a1': i, u'a2': ('test-%d' % i)}) self.stop() def _OnPutItems(): se...
'Clears the contents of the \'Test\' table by scanning the rows and deleting items by composite key.'
def _ClearTestTable(self, callback):
def _OnScan(result): with util.Barrier(callback) as b: for item in result.items: self._client.DeleteItem(table=_table.name, key=DBKey(item['thk'], item['trk']), callback=b.Callback()) self._client.Scan(table=_table.name, callback=_OnScan, attributes=['thk', 'trk'])
'Verify exceptions are propagated on a bad request.'
@async_test_timeout(timeout=30) def testBadRequest(self):
def _OnPut(result): assert False, 'Put should fail' def _OnError(type, value, callback): self.assertEqual(type, DynamoDBResponseError) self.stop() with util.Barrier(_OnPut, _OnError) as b: self._client.PutItem(table=_table.name, key=DBKey(u'1', 1), attributes={'a2': ''}...
'Verify exceptions propagated from the DynamoDB client are raised in the stack context of the caller.'
@async_test_timeout(timeout=30) def testExceptionPropagationInStackContext(self):
entered = [False, False] def _OnPut1(): assert False, 'Put1 should fail' def _OnError1(type, value, tb): if entered[0]: print 'in error1 again!' assert (not entered[0]), 'already entered error 1' entered[0] = True if all(entered): ...
'Verify that performance counters are working correctly for DynamoDB.'
@async_test_timeout(timeout=30) def testPerformanceCounters(self):
meter = counters.Meter(counters.counters.viewfinder.dynamodb) def _PutComplete(): self.stop() self._client._scheduler._Pause() with util.Barrier(_PutComplete) as b: self._client.PutItem(table=_table.name, key=DBKey(u'1', 1), attributes={'a1': 100, 'a2': 'test value'}, callback=b.Callb...
'Put items and verify getting them in a batch.'
@async_test_timeout(timeout=30) def testBatchGetItem(self):
attrs = {'a0': 123.456, 'a2': 'test value', 'a4': set(['foo', 'bar'])} attrs2 = {'a0': 1, 'a1': (-12345678901234567890L), 'a3': set([1, 2, 3])} with util.Barrier(self.stop) as b: self._client.PutItem(table=_table.name, key=DBKey(u'1', 1), attributes=attrs, callback=b.Callback()) self._cli...
'Creates a read-only local client. Manually flips the _read_only variable to populate the table, then flips it back.'
def setUp(self):
super(DynamoDBReadOnlyClientTestCase, self).setUp() options.options.domain = 'goviewfinder.com' secrets.InitSecretsForTest() self._client = dynamodb_client.DynamoDBClient(schema=vf_schema.SCHEMA, read_only=True) self._client._read_only = False self._RunAsync(self._ClearTestTable) self._RunAs...
'Clears the contents of the \'Test\' table by scanning the rows and deleting items by composite key.'
def _ClearTestTable(self, callback):
def _OnScan(result): with util.Barrier(callback) as b: for item in result.items: self._client.DeleteItem(table=_table.name, key=DBKey(item['thk'], item['trk']), callback=b.Callback()) self._client.Scan(table=_table.name, callback=_OnScan, attributes=['thk', 'trk'])
'Returns the value of the column in a format that is convenient for use in Python. If \'asdict\' is true, then convert to a Python dict if this column type supports it.'
def Get(self, asdict=False):
raise NotImplementedError()
'Loads the value of the column from the format that is stored in the database. Sets the IsModified bit to false.'
def Load(self, value):
raise NotImplementedError()
'Updates the value of the column with any type that can be converted into the column type. Sets the IsModified bit to true if the value of the column actually changes.'
def Set(self, value):
raise NotImplementedError()
'Called on completion of an update.'
def OnUpdate(self):
self.SetModified(False)
'Returns an index term dict in conjunction with PUT. If the term dict is empty, returns an empty term dict. In either case, the previous set of index terms is queried and the difference between the old and new sets is used to delete or add this object\'s key to the term posting lists.'
def IndexTerms(self):
assert self.col_def.indexer try: if self.Get(): index_terms = self.col_def.indexer.Index(self.col_def, self.Get()) else: index_terms = {} except: logging.exception(('generation of index terms for %s' % repr(self.Get()))) index_terms = {}...
'Ensure that "value" has a type that matches the type of the column.'
def _CheckType(self, value):
def _CheckSingleValue(single_value): assert (single_value != ''), value if (self.col_def.value_type in ['S', 'SS']): is_expected_type = (type(single_value) in [str, unicode]) else: assert (self.col_def.value_type in ['N', 'NS']), self.col_def is_expected_t...
'Returns the value in the raw db format by default.'
def Get(self, asdict=False):
return self._value
'Stores the raw db value by default.'
def Load(self, value):
self._CheckType(value) self._value = value
'Stores the raw db value by default.'
def Set(self, value):
assert (value != ''), 'DynamoDB does not support setting attributes to the empty string' if (value != self._value): assert ((not self.col_def.read_only) or (self._value is None)), ('cannot modify read-only column "%s": %s=>%s' % (self.col_def.name, self._value, ...
'Returns PUT and the new value if modified. If new value is None, returns DELETE.'
def Update(self):
assert self.IsModified() if (self._value is not None): return db_client.UpdateAttr(value=self._value, action='PUT') else: return db_client.UpdateAttr(value=None, action='DELETE')
'Gets the value as a Location or dict object.'
def Get(self, asdict=False):
if asdict: return self._value._asdict() else: return self._value
'Stores the raw db str as a Location object in memory.'
def Load(self, value):
assert isinstance(value, (str, unicode)), value self._value = UnpackLocation(value)
'Converts \'value\' to a Location and store.'
def Set(self, value):
if (value is None): location = None elif isinstance(value, dict): location = Location(**value) elif isinstance(value, (str, unicode)): location = UnpackLocation(value) else: assert isinstance(value, Location), value location = value if (location != self._value...
'Returns PUT and the new value if modified. If new value is None, returns DELETE.'
def Update(self):
assert self.IsModified() if (self._value is not None): return db_client.UpdateAttr(value=PackLocation(self._value), action='PUT') else: return db_client.UpdateAttr(value=None, action='DELETE')
'Gets the value as a Placemark or dict object.'
def Get(self, asdict=False):
if asdict: return dict([(k, v) for (k, v) in self._value._asdict().items() if ((v is not None) and (v != ''))]) else: return self._value
'Stores the raw db str as a Placemark object in memory.'
def Load(self, value):
assert isinstance(value, (str, unicode)), value self._value = UnpackPlacemark(value)
'Converts \'value\' to a Placemark and store.'
def Set(self, value):
if (value is None): placemark = None elif isinstance(value, dict): placemark = Placemark(value.get('iso_country_code', ''), value.get('country', ''), value.get('state', ''), value.get('locality', ''), value.get('sublocality', ''), value.get('thoroughfare', ''), value.get('subthoroughfare', '')) ...
'Returns PUT and the new value if modified. If new value is None, returns DELETE.'
def Update(self):
assert self.IsModified() if (self._value is not None): return db_client.UpdateAttr(value=PackPlacemark(self._value), action='PUT') else: return db_client.UpdateAttr(value=None, action='DELETE')
'Returns the JSON-encoded string converted to a Python data type.'
def Get(self, asdict=False):
if self._value: return json.loads(self._value) else: return None
'Stores the raw string value loaded from the db.'
def Load(self, value):
assert isinstance(value, (str, unicode)), value self._value = value
'Converts \'value\' to a JSON-encoded string before storing it.'
def Set(self, value):
value = util.ToCanonicalJSON(value) if (value != self._value): self.SetModified(True) self._value = value
'Returns the decrypted value.'
def Decrypt(self):
crypter = _CryptValue._GetCrypter() return json.loads(crypter.Decrypt(self._encrypted_value))