desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Method used in a few tests to help verify performance counters.'
def _CheckCounters(self, expected_ops, expected_retries):
sample = self.meter.sample() elapsed = (time.time() - self.meter_start) ops_per_min = ((expected_ops / elapsed) * 60) self.assertAlmostEqual(sample.viewfinder.operation.ops_per_min, ops_per_min, delta=(ops_per_min * 0.1)) retries_per_min = ((expected_retries / elapsed) * 60) self.assertAlmostEqu...
'Test activity ids.'
def testActivityIds(self):
self._TestIdRoundTripWithTimestamp(Activity.ConstructActivityId, Activity.DeconstructActivityId)
'Test comment ids.'
def testCommentIds(self):
self._TestIdRoundTripWithTimestamp(Comment.ConstructCommentId, Comment.DeconstructCommentId)
'Test episode ids.'
def testEpisodeIds(self):
self._TestIdRoundTripWithTimestamp(Episode.ConstructEpisodeId, Episode.DeconstructEpisodeId)
'Test operation ids.'
def testOperationIds(self):
self._TestIdRoundTrip(Operation.ConstructOperationId, Operation.DeconstructOperationId)
'Test photo ids.'
def testPhotoIds(self):
self._TestIdRoundTripWithTimestamp(Photo.ConstructPhotoId, Photo.DeconstructPhotoId)
'Test viewpoint ids.'
def testViewpointIds(self):
self._TestIdRoundTrip(Viewpoint.ConstructViewpointId, Viewpoint.DeconstructViewpointId)
'Round-trip id with a timestamp.'
def _TestIdRoundTripWithTimestamp(self, construct, deconstruct):
def _RoundTrip(timestamp, device_id, uniquifier): asset_id = construct(timestamp, device_id, uniquifier) (actual_timestamp, actual_device_id, actual_uniquifier) = deconstruct(asset_id) self.assertEqual(int(timestamp), actual_timestamp) self.assertEqual(device_id, actual_device_id) ...
'Round-trip id.'
def _TestIdRoundTrip(self, construct, deconstruct):
def _RoundTrip(device_id, device_local_id): server_id = construct(device_id, device_local_id) (actual_device_id, actual_device_local_id) = deconstruct(server_id) self.assertEqual(device_id, actual_device_id) self.assertEqual(device_local_id, actual_device_local_id) if IdTestC...
'Test validation of phone numbers.'
def testPhoneNumbers(self):
self.assertEqual(Identity.CanonicalizePhone('+14251234567'), '+14251234567') self.assertEqual(Identity.CanonicalizePhone('+60321345678'), '+60321345678') self.assertEqual(Identity.CanonicalizePhone('+442083661177'), '+442083661177') self.assertEqual(Identity.CanonicalizePhone('+861082301234'), '+8610823...
'Test conversion of Identity objects to strings.'
def testRepr(self):
ident = Identity.CreateFromKeywords(key='Email:foo@example.com', access_token='access_token1', refresh_token='refresh_token1') self.assertIn('foo@example.com', repr(ident)) self.assertIn('scrubbed', repr(ident)) self.assertNotIn('access_token1', repr(ident)) self.assertNotIn('refresh_token1', repr(i...
'Create a series of photo ids and verify sort order. Sort order is by time first (from newest to oldest), then from oldest to newest device id, then from oldest to newest device photo id.'
def testPhotoIdSortOrder(self):
photo_attributes = [(100, 1, 1), (100, 1, 2), (100, 1, 3), (100, 2, 1), (100, 2, 2), (100, 2, 3), (99, 1, 3), (99, 2, 2), (99, 3, 1), (98, 3, 1), (97, 2, 1), (96, 1, 1)] photo_ids = [Photo.ConstructPhotoId(p[0], p[1], p[2]) for p in photo_attributes] self.assertEqual(photo_ids, sorted(photo_ids))
'Verify photo creation and query by photo id.'
@async_test def testQuery(self):
def _OnQuery(p, p2): self.assertEqual(p2.caption, p.caption) self.assertEqual(p2.photo_id, p.photo_id) self.stop() def _OnCreatePhoto(p): Photo.Query(self._client, p.photo_id, None, partial(_OnQuery, p)) photo_id = Photo.ConstructPhotoId(time.time(), self._mobile_dev.device_i...
'Verify update of a photo attribute.'
@async_test def testUpdateAttribute(self):
def _OnUpdate(p): p.aspect_ratio = None p.Update(self._client, self.stop) def _OnQuery(p): p.content_type = 'image/png' p.Update(self._client, partial(_OnUpdate, p)) def _OnCreatePhoto(p): Photo.Query(self._client, p.photo_id, None, _OnQuery) photo_id = Photo.Cons...
'Verify query for a missing photo fails.'
@async_test def testMissing(self):
def _OnQuery(p): assert False, 'photo query should fail with missing key' def _OnMissing(type, value, traceback): self.stop() return True with util.MonoBarrier(_OnQuery, on_exception=_OnMissing) as b: Photo.Query(self._client, str((1L << 63)), None, b.Callba...
'Create a device with an invalid token and verify it is cleared on a push notification.'
@async_test def testInvalidToken(self):
self._mobile_dev.push_token = 'invalid-scheme:push-token' self._mobile_dev.Update(self._client, self._OnDeviceUpdate)
'Try pushing a notification to the device.'
def _OnDeviceUpdate(self):
Device.PushNotification(self._client, self._user.user_id, 'test alert', 1, partial(self._QueryUntilPushTokenNone, 0, self._mobile_dev))
'Query the device until the push token has been cleared.'
def _QueryUntilPushTokenNone(self, count, device):
MAX_RETRIES = 5 assert (count < MAX_RETRIES) if (device.push_token is None): self.assertIsNone(device.alert_user_id) self.stop() else: query_cb = partial(Device.Query, self._client, self._user.user_id, self._mobile_dev.device_id, None, partial(self._QueryUntilPushTokenNone, (coun...
'Tests that multiple allocations from the same sequence do not overlap.'
@async_test def testMultiple(self):
allocs = [IdAllocator('type'), IdAllocator('type')] num_ids = 3000 def _OnAllocated(id_lists): assert (len(id_lists) == 2) id_set1 = set(id_lists[0]) id_set2 = set(id_lists[1]) assert (len(id_set1) == 3000) assert (len(id_set2) == 3000) assert id_set1.isdisjoi...
'Test DBRangeObject.RangeQuery.'
@unittest.skip('needs aws credentials') def testRangeQuery(self):
def _MakeResponse(max_index, request): request_dict = json.loads(request.body) limit = min(request_dict.get('Limit', 2), 2) is_count = request_dict.get('Count') if ('ExclusiveStartKey' in request_dict): start_index = (int(request_dict['ExclusiveStartKey']['RangeKeyElement...
'Test DBObject.BatchQuery.'
def testBatchQuery(self):
keys = [] for i in xrange(3): photo_id = Photo.ConstructPhotoId(time.time(), self._mobile_dev.device_id, 1) episode_id = Episode.ConstructEpisodeId(time.time(), self._mobile_dev.device_id, 1) ph_dict = {'photo_id': photo_id, 'user_id': self._user.user_id, 'episode_id': episode_id} ...
'Test acquiring a lock.'
def testSimpleAcquire(self):
self._TryAcquire('my', '1234') self._TryAcquire('my', '!@#%!@#$', resource_data='some data') self._TryAcquire('my', '12-34', resource_data='the quick brown fox jumped over the lazy dog', detect_abandonment=True)
'Test attempt to acquire a lock that is already owned.'
def testLockAlreadyAcquired(self):
lock = self._TryAcquire('op', 'andy', release_lock=False) self._TryAcquire('op', 'andy', expected_status=Lock.FAILED_TO_ACQUIRE_LOCK) self._TryAcquire('op', 'andy', expected_status=Lock.FAILED_TO_ACQUIRE_LOCK) self._Release(lock) self.assertEqual(lock.acquire_failures, 2)
'Test acquiring an abandoned lock.'
def testAbandonedLock(self):
lock = self._TryAcquire('op', 'id', detect_abandonment=True, release_lock=False) lock.Abandon(self._client, self.stop) self.wait() self._TryAcquire('op', 'id', expected_status=Lock.ACQUIRED_ABANDONED_LOCK)
'Test that renewal mechanism is preventing lock abandonment.'
def testRenewLock(self):
Lock.ABANDONMENT_SECS = 0.3 Lock.LOCK_RENEWAL_SECS = 0.1 lock = self._TryAcquire('op', 'id', detect_abandonment=True, release_lock=False) self.io_loop.add_timeout(timedelta(seconds=0.6), self.stop) self.wait() self._TryAcquire('op', 'id', expected_status=Lock.FAILED_TO_ACQUIRE_LOCK) self._Re...
'Test cases where multiple agents are racing to acquire locks.'
def testRaceToAcquire(self):
lock_to_release = [] def _OnAcquire(update_func, lock, status): lock_to_release.append(lock) update_func() def _Race(update_func): if (len(lock_to_release) == 0): Lock.TryAcquire(self._client, 'op', 'id', partial(_OnAcquire, update_func)) elif (len(lock_to_release...
'Test case where failed lock acquirer tries to update lock after it\'s been released.'
def testRaceToUpdateReleasedLock(self):
def _Race(lock_to_release, update_func): lock_to_release.Release(self._client, callback=update_func) lock_to_release = self._TryAcquire('op', 'id', release_lock=False) self._TryAcquire('op', 'id', expected_status=Lock.FAILED_TO_ACQUIRE_LOCK, test_hook=partial(_Race, lock_to_release), release_lock=Fa...
'Test cases where multiple agents are racing to take over an abandoned lock.'
def testRaceToTakeOver(self):
lock_to_release = [] def _OnAcquire(update_func, lock, status): lock_to_release.append(lock) update_func() def _Race(update_func): if (len(lock_to_release) == 0): Lock.TryAcquire(self._client, 'op', 'id', partial(_OnAcquire, update_func)) else: update_...
'Test Lock.Acquire function.'
def testAcquireLock(self):
hit_exception = False lock = self._RunAsync(Lock.Acquire, self._client, 'tst', 'id0', None) try: self._RunAsync(Lock.Acquire, self._client, 'tst', 'id0', None) try: self.fail("Shouldn't reach this point in try.") finally: self.fail("Shouldn't ...
'Test Lock.Acquire failure in try/except that encounters an error.'
def testAcquireLockWithError(self):
error_was_raised = False lock = self._RunAsync(Lock.Acquire, self._client, 'tst', 'id0', None) try: raise Exception('raise an error') except Exception as e: self.assertEqual(e.message, 'raise an error') error_was_raised = True finally: self._RunAsync(lock....
'Test that Lock.Acquire will succeed with orphaned lock when owner_id matches that of lock.'
def testReaquireLock(self):
lock = self._RunAsync(Lock.Acquire, self._client, 'tst', 'id0', 'owner89') self.assertTrue(lock.AmOwner()) lock = self._RunAsync(Lock.Acquire, self._client, 'tst', 'id0', 'owner89') self.assertTrue(lock.AmOwner()) self._RunAsync(lock.Release, self._client)
'Test releasing a lock that\'s owned by a different agent.'
def testReleaseOtherOwnedLock(self):
lock = self._RunAsync(Lock.Acquire, self._client, 'tst', 'id0', 'owner89') lock2 = self._RunAsync(Lock.Query, self._client, lock.lock_id, None) lock2.owner_id = 'new_owner_id' self._RunAsync(lock2.Update, self._client) self.assertRaises(LockFailedError, self._RunAsync, lock.Release, self._client) ...
'Try to create notification with same id twice to simulate race condition.'
def testSimulateNotificationRaces(self):
notification = Notification(self._user.user_id, 100) notification.name = 'test' notification.timestamp = time.time() notification.sender_id = self._user.user_id notification.sender_device_id = 1 notification.badge = 0 notification.activity_id = 'a123' notification.viewpoint_id = 'v123' ...
'Concurrently create many notifications to force races.'
def testNotificationRaces(self):
op = Operation(1, 'o123') with util.ArrayBarrier(self.stop) as b: for i in xrange(10): Notification.CreateForUser(self._client, op, 1, 'test', callback=b.Callback(), invalidate={'invalid': True}, activity_id='a123', viewpoint_id=('v%d' % i), inc_badge=True) notifications = self.wait() ...
'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):
super(LocalClientTestCase, self).setUp() options.options.localdb_dir = '' self._client = LocalClient(test_SCHEMA) test_SCHEMA.VerifyOrCreate(self._client, self.stop) self.wait()
'Creates a read-only local client. Manually flips the _read_only variable to populate the table, then flips it back.'
def setUp(self):
super(LocalReadOnlyClientTestCase, self).setUp() options.options.localdb_dir = '' self._client = LocalClient(test_SCHEMA, read_only=True) self._client._read_only = False self._RunAsync(test_SCHEMA.VerifyOrCreate, self._client) self._RunAsync(self._client.PutItem, table='LocalTest', key=DBKey(has...
'Verify unlinking an identity causes every referencing contact to be updated.'
def testUnlinkIdentity(self):
timestamp = util.GetCurrentTimestamp() spencer = self._user contact_identity = 'Email:peter.mattis@emailscrubbed.com' contact_name = 'Peter Mattis' contact_given_name = 'Peter' contact_family_name = 'Mattis' contact_rank = 42 contact = Contact.CreateFromKeywords(spencer.user_id, [(con...
'Test that the identity and identities attributes are being properly derived from the identities_properties attribute.'
def testDerivedAttributes(self):
spencer = self._user contact_identity_a = 'Email:peter.mattis@Gmail.com' contact_identity_b = 'Email:peterMattis@emailscrubbed.com' contact_identity_c = 'Email:peterMattis@emailscrubbed.com' timestamp = util.GetCurrentTimestamp() contact = Contact.CreateFromKeywords(spencer.user_id, [(contact_id...
'Test that contact_id generation works correctly when names include non-ascii characters.'
def testUnicodeContactNames(self):
name = u'\xe0\xe0\xe0\u670b\u53cb\u4f60\u597dabc123\U00010000\U00010000\x00\x01\x08\n DCTB ' contact_a = Contact.CreateFromKeywords(1, [('Email:me@my.com', None)], util.GetCurrentTimestamp(), Contact.GMAIL, name=name) contact_b = Contact.CreateFromKeywords(1, [('Email:me@my.com', None)], util.GetCurrent...
'Test the periodic metric upload system.'
@async_test def testMetricsUploadTimer(self):
def _OnQueryMetric(min_metrics, max_metrics, metrics): self.assertTrue(((len(metrics) >= min_metrics) and (len(metrics) <= max_metrics)), ('%d not in [%d-%d]' % (len(metrics), min_metrics, max_metrics))) for m in metrics: self.assertTrue(((m.timestamp % 3) == 0)) payload...
'Test metrics aggregation with data from multiple machines'
@async_test def testMetricsAggregator(self):
num_machines = 5 num_samples = 15 sample_duration = 60.0 group_key = 'agg_test_group_key' fake_time = 0 managers = [] def fake_time_func(): return fake_time def _OnAggregation(aggregator): base_sum = sum(range(1, (num_machines + 1))) base_avg = (base_sum / num_mac...
'Creates a bidirectional friendship between two users.'
def testMakeFriends(self):
(friend, reverse_friend) = self._RunAsync(Friend.MakeFriends, self._client, self._user.user_id, self._user2.user_id) self.assertEqual(friend.user_id, self._user.user_id) self.assertEqual(friend.friend_id, self._user2.user_id) self.assertEqual(reverse_friend.user_id, self._user2.user_id) self.assertE...
'Test friendships that are only recognized by one of the users.'
def testOneSidedFriends(self):
self._RunAsync(Friend.MakeFriendAndUpdate, self._client, self._user.user_id, {'user_id': self._user2.user_id, 'nickname': 'Slick'}) forward_friend = self._RunAsync(Friend.Query, self._client, self._user.user_id, self._user2.user_id, None, must_exist=False) self.assertIsNotNone(forward_friend) reverse_fr...
'Deletes all objects that were created in the context of the model. If validate=True, then validates all objects before the cleanup by comparing them against the database.'
def Cleanup(self, validate=False):
if validate: for (dbo_key, dbo) in self._model.items(): self._ValidateDBObject(dbo_key.db_class, dbo_key.db_key) for (dbo_key, dbo) in self._model.items(): if (dbo is not None): self._RunAsync(dbo.Delete, self.client)
'Gets a DBObject from the model that has the specified class and key. If "must_exist" is true, raises an exception if the object is not present in the model. Otherwise, returns the object, or None if it is not present in the model.'
def GetModelObject(self, cls, key, must_exist=True):
if (not isinstance(key, DBKey)): assert (cls._table.range_key_col is None), 'key must be of type DBKey for range tables' key = DBKey(hash_key=key, range_key=None) dbo_key = DBObjectKey(cls, key) dbo = self._model.get(dbo_key, None) assert ((not must_exist) or (dbo...
'Returns all DBObjects from the model that: 1. Are of the specified class. 2. Have the specified hash key. 3. Match the predicate (predicate takes DBObject as argument). 4. Have a key greater than start_key, if not None. Returns only up to "limit" DBObjects, and return in sorted order if query_forward is True, or rever...
def QueryModelObjects(self, cls, hash_key=None, predicate=None, limit=None, start_key=None, query_forward=True):
matches = [dbo for (key, dbo) in self._model.items() if (dbo and (key.db_class == cls)) if ((hash_key is None) or (key.db_key.hash_key == hash_key)) if ((start_key is None) or ((key.db_key.range_key > start_key) if query_forward else (start_key > key.db_key.range_key))) if ((predicate is None) or predicate(dbo))] ...
'Add the specified DBObject to the list of objects tracked by the model.'
def AddModelObject(self, dbo):
dbo_key = DBObjectKey(dbo.__class__, dbo.GetKey()) self._model[dbo_key] = dbo
'Validates that an object of type "cls" was created in the database, assuming it did not already exist. If it was created, validates that its attributes match those in "db_dict", else validates that its attributes match those of the existing object in the model. All attributes in "db_dict" are explicitly checked, even ...
def ValidateCreateDBObject(self, cls, **db_dict):
dbo = cls.CreateFromKeywords(**db_dict) existing_dbo = self.GetModelObject(dbo.__class__, dbo.GetKey(), must_exist=False) if (not existing_dbo): self.AddModelObject(dbo) existing_dbo = dbo self._ValidateDBObject(dbo.__class__, dbo.GetKey(), must_check_dict=db_dict) return existing_db...
'Validates that an object of type "cls" was created in the database if it did not already exist. Validates that the attributes of the new or existing object were updated to match those in "db_dict". All attributes in "db_dict" are explicitly checked, even if they\'d normally be ignored by ValidateDBObject. Invokes the ...
def ValidateUpdateDBObject(self, cls, **db_dict):
dbo = cls.CreateFromKeywords(**db_dict) existing_dbo = self.GetModelObject(dbo.__class__, dbo.GetKey(), must_exist=False) if (not existing_dbo): self.AddModelObject(dbo) existing_dbo = dbo else: existing_dbo.UpdateFromKeywords(**db_dict) self._ValidateDBObject(dbo.__class__, ...
'Validates that the object with the specified key was deleted from the database.'
def ValidateDeleteDBObject(self, cls, key):
if (not isinstance(key, DBKey)): assert (cls._table.range_key_col is None), 'key must be of type DBKey for range tables' key = DBKey(hash_key=key, range_key=None) dbo_key = DBObjectKey(cls, key) self._model[dbo_key] = None self._ValidateDBObject(cls, key)
'Validates creation of contact along with derived attributes. Returns created contact.'
def ValidateCreateContact(self, user_id, identities_properties, timestamp, contact_source, **op_dict):
contact_dict = op_dict contact_dict['user_id'] = user_id contact_dict['timestamp'] = timestamp if (identities_properties is not None): contact_dict['identities_properties'] = identities_properties contact_dict['identities'] = set([Identity.Canonicalize(identity_properties[0]) for identit...
'Validates that a prospective user has been created for any contact which is not yet associated with Viewfinder user. Returns all resolved users.'
def ValidateCreateProspectiveUsers(self, op_dict, contacts):
users = [] for contact_dict in contacts: if ('user_id' in contact_dict): users.append(self.GetModelObject(User, contact_dict['user_id'])) else: identity_key = contact_dict['identity'] actual_ident = self._RunAsync(Identity.Query, self.client, identity_key, Non...
'Validates that Follower and Followed records have been created or updated in the database for user "user_id" and viewpoint "viewpoint_id". Returns the follower.'
def ValidateFollower(self, user_id, viewpoint_id, labels, last_updated, timestamp=None, adding_user_id=None, viewed_seq=None):
follower_dict = {'user_id': user_id, 'viewpoint_id': viewpoint_id, 'labels': labels} util.SetIfNotNone(follower_dict, 'timestamp', timestamp) util.SetIfNotNone(follower_dict, 'adding_user_id', adding_user_id) util.SetIfNotNone(follower_dict, 'viewed_seq', viewed_seq) follower = self.ValidateUpdateDB...
'Validates that a user and identity have been created in the database if they did not already exist, or were updated if they did. If "device_dict" is defined, validates that a device was created or updated as well.'
def ValidateUpdateUser(self, name, op_dict, user_dict, ident_dict, device_dict=None, is_prospective=False):
user_id = user_dict['user_id'] viewpoint_id = Viewpoint.ConstructViewpointId(user_dict['webapp_dev_id'], 0) viewpoint = self.GetModelObject(User, user_id, must_exist=False) if (viewpoint is None): expected_viewpoint = self.ValidateCreateDBObject(Viewpoint, viewpoint_id=viewpoint_id, user_id=user...
'Validates that all contacts that reference "identity_key" have been updated with the new timestamp.'
def ValidateRewriteContacts(self, identity_key, op_dict):
for co in self.QueryModelObjects(Contact, predicate=(lambda co: (identity_key in co.identities))): contact_dict = co._asdict() contact_dict['timestamp'] = op_dict['op_timestamp'] sort_key = Contact.CreateSortKey(Contact.CalculateContactId(contact_dict), contact_dict['timestamp']) con...
'Validates that all specified users are friends with each other.'
def ValidateFriendsInGroup(self, user_ids):
for (index, user_id) in enumerate(user_ids): for friend_id in user_ids[(index + 1):]: if (user_id != friend_id): user1 = self.GetModelObject(User, user_id) user2 = self.GetModelObject(User, friend_id) self.ValidateUpdateDBObject(Friend, user_id=use...
'Validates that a set of episodes and posts have been created within the specified viewpoint via a sharing or save operation.'
def ValidateCopyEpisodes(self, op_dict, viewpoint_id, ep_dicts):
ph_act_dict = {} for ep_dict in ep_dicts: existing_episode = self.GetModelObject(Episode, ep_dict['existing_episode_id']) new_ep_dict = {'episode_id': ep_dict['new_episode_id'], 'parent_ep_id': ep_dict['existing_episode_id'], 'user_id': op_dict['user_id'], 'viewpoint_id': viewpoint_id, 'timestam...
'Validate that a cover_photo is set on a viewpoint. Selects a new cover_photo if there currently isn\'t one or the current one is no longer shared in the viewpoint. Returns: True if viewpoint\'s cover_photo value changed, otherwise False.'
def ValidateCoverPhoto(self, viewpoint_id, unshare_ep_dicts=None):
current_model_cover_photo = self.GetModelObject(Viewpoint, viewpoint_id).cover_photo exclude_posts_set = set() if (unshare_ep_dicts is not None): exclude_posts_set = set([(episode_id, photo_id) for (episode_id, photo_ids) in unshare_ep_dicts.items() for photo_id in photo_ids]) elif (current_mode...
'Validates that the specified identity was properly unlinked from the attached user.'
def ValidateUnlinkIdentity(self, op_dict, identity_key):
identity = self.GetModelObject(Identity, identity_key, must_exist=False) self.ValidateDeleteDBObject(Identity, identity_key) self.ValidateRewriteContacts(identity_key, op_dict) self.ValidateContactNotifications('unlink_identity', identity_key, op_dict) if identity: self.ValidateUserNotificat...
'Validates that the REMOVED followers label has been removed from viewpoint followers. Removed followers should be revived by any structural changes to their viewpoints.'
def ValidateReviveRemovedFollowers(self, viewpoint_id, op_dict):
follower_matches = (lambda f: (f.viewpoint_id == viewpoint_id)) for follower in self.QueryModelObjects(Follower, predicate=follower_matches): if (follower.IsRemoved() and (not follower.IsUnrevivable())): follower.labels.remove(Follower.REMOVED) follower.labels = follower.labels.c...
'Validates that the given user\'s account has been terminated.'
def ValidateTerminateAccount(self, user_id, op_dict, merged_with=None):
devices = self.QueryModelObjects(Device, predicate=(lambda d: (d.user_id == user_id))) for device in devices: self.ValidateUpdateDBObject(Device, user_id=user_id, device_id=device.device_id, alert_user_id=None) identities = self.QueryModelObjects(Identity, predicate=(lambda i: (i.user_id == user_id)...
'Validates accounting stats for all viewpoints and users.'
def ValidateAccounting(self):
desired_act = {} def _SetOrIncrement(act): key = (act.hash_key, act.sort_key) if (key not in desired_act): desired_act[key] = act else: desired_act[key].IncrementStatsFrom(act) followers = defaultdict(list) (all_followers, _) = self._RunAsync(Follower.Scan...
'Validates the given viewpoint\'s accounting stats by iterating over all viewable photos and adding up the expected stats for each.'
def ValidateViewpointAccounting(self, viewpoint_id):
desired_act = {} def _SetOrIncrement(act): key = (act.hash_key, act.sort_key) if (key not in desired_act): desired_act[key] = act else: desired_act[key].IncrementStatsFrom(act) viewpoint = self._RunAsync(Viewpoint.Query, self.client, viewpoint_id, None) (e...
'Validates that a notification has been created for each follower of the specified viewpoint. If "invalidate" is a dict, then each follower uses that as its invalidation. Otherwise, it is assumed to be a func that returns the invalidation, given the id of the follower. Validates that an activity was created in the view...
def ValidateFollowerNotifications(self, viewpoint_id, activity_dict, op_dict, invalidate, sends_alert=False):
viewpoint = self.GetModelObject(Viewpoint, viewpoint_id) old_timestamp = viewpoint.last_updated new_timestamp = max(old_timestamp, op_dict['op_timestamp']) update_seq = (1 if (viewpoint.update_seq is None) else (viewpoint.update_seq + 1)) self.ValidateUpdateDBObject(Viewpoint, viewpoint_id=viewpoint...
'Validates that a notification was created for each friend of the given user, as well as the user himself.'
def ValidateFriendNotifications(self, name, user_id, op_dict, invalidate):
for friend in self.QueryModelObjects(Friend, predicate=(lambda fr: (fr.user_id == user_id))): self.ValidateNotification(name, friend.friend_id, op_dict, invalidate)
'Validates that a notification was created for each user who references a contact of the specified identity.'
def ValidateContactNotifications(self, name, identity_key, op_dict):
invalidate = {'contacts': {'start_key': Contact.CreateSortKey(None, op_dict['op_timestamp'])}} for co in self.QueryModelObjects(Contact, predicate=(lambda co: (identity_key in co.identities))): self.ValidateNotification(name, co.user_id, op_dict, invalidate)
'Validates that a notification was created for the specified user.'
def ValidateUserNotification(self, name, user_id, op_dict):
self.ValidateNotification(name, user_id, op_dict, {'users': [user_id]})
'Validates that a notification with the specified name and invalidation has been created for "target_user_id". The "op_dict" must contain expected "user_id", "device_id", and "op_timestamp" fields. It may contain "op_id", if its expected value is known to the caller.'
def ValidateNotification(self, name, target_user_id, op_dict, invalidate, activity_id=None, viewpoint_id=None, seq_num_pair=None, sends_alert=False):
notifications = self.QueryModelObjects(Notification, target_user_id) last_notification = (notifications[(-1)] if notifications else None) notification_id = ((last_notification.notification_id + 1) if (last_notification is not None) else 1) if (invalidate is not None): invalidate = deepcopy(inval...
'Create invalidation for entire viewpoint, including all metadata and all collections. NOTE: Make sure to update this when new viewpoint collections are added.'
@classmethod def CreateViewpointInvalidation(cls, viewpoint_id):
return {'viewpoints': [{'viewpoint_id': viewpoint_id, 'get_attributes': True, 'get_followers': True, 'get_activities': True, 'get_episodes': True, 'get_comments': True}]}
'Validate that an older Followed record was deleted and a newer created.'
def _ValidateUpdateFollowed(self, user_id, viewpoint_id, old_timestamp, new_timestamp):
if ((old_timestamp is not None) and (Followed._TruncateToDay(new_timestamp) > Followed._TruncateToDay(old_timestamp))): db_key = DBKey(user_id, Followed.CreateSortKey(viewpoint_id, old_timestamp)) self.ValidateDeleteDBObject(Followed, db_key) self.ValidateCreateDBObject(Followed, user_id=user_id...
'Runs an async function which takes a callback argument. Waits for the function to complete and returns any result.'
def _RunAsync(self, func, *args, **kwargs):
func(callback=self._stop, *args, **kwargs) return self._wait()
'Validates that a model object of type "cls", and with the specified key is equivalent to the actual DBObject that exists (or not) in the database. Always checks attributes in "must_check_dict", even if normally the attribute would be ignored.'
def _ValidateDBObject(self, cls, key, must_check_dict=None):
expected_dbo = self.GetModelObject(cls, key, must_exist=False) if (expected_dbo is not None): expected_dict = self._SanitizeDBObject(expected_dbo, must_check_dict) expected_json = util.ToCanonicalJSON(expected_dict, indent=True) else: expected_json = None actual_dbo = self._RunAs...
'Converts dbo to a dict, and then removes attributes from it that should be ignored when comparing DBObjects with each other.'
def _SanitizeDBObject(self, dbo, must_check_dict):
dbo_dict = dbo._asdict() remove_dict = {Accounting: set(['op_ids']), AccountSettings: set(['sms_count']), Analytics: set(['payload']), Follower: set(['viewed_seq']), IdAllocator: set(['next_id']), Identity: set(['last_fetch', 'token_guesses', 'token_guesses_time', 'json_attrs', 'auth_throttle']), Notification: ...
'Test multiple operations executed by OpManager.'
def testMultipleOps(self):
def _OpMethod(client, callback): self._method_count += 1 callback() if (self._method_count == 3): self.io_loop.add_callback(self.stop) def _OnWait(): self._wait_count += 1 op_mgr = self._CreateOpManager(handlers=[_OpMethod]) op = self._CreateTestOp(user_id=1, ...
'Test scanning for locks which were abandoned due to server failure.'
def testScanAbandonedLocks(self):
def _OpMethod(client, callback): self._method_count += 1 callback() if (self._method_count == 10): self.io_loop.add_callback(self.stop) for i in xrange(10): lock = self._AcquireOpLock(user_id=(i / 2)) lock.Abandon(self._client, self.stop) self.wait() ...
'Abandon an op lock with resource data set, and make sure that the op is run first.'
def testResourceData(self):
def _OpMethod1(client, callback): self._method_count += 1 callback() def _OpMethod2(client, callback): self.assertEqual(self._method_count, 1) callback() self.io_loop.add_callback(self.stop) op = self._CreateTestOp(user_id=100, handler=_OpMethod2) op = self._Creat...
'Test scanning for ops which have failed.'
def testScanFailedOps(self):
def _FlakyOpMethod(client, callback): 'Fails 8 times and then succeeds.' self._method_count += 1 if (self._method_count <= 8): raise Exception('some transient failure') callback() self.io_loop.add_callback(self.stop) self._ExecuteOp(user_i...
'Test simple operation that completes successfully.'
def testSimpleUserOp(self):
self._ExecuteOp(user_id=1, handler=self._OpMethod) self.assertEqual(self._method_count, 1)
'Test simple operation that completes successfully.'
def testUserOpWithArgs(self):
def _OpMethodWithArgs(client, callback, arg1, arg2): assert ((arg1 == 'foo') and (arg2 == 10)) self._method_count += 1 callback() self._ExecuteOp(user_id=1, handler=_OpMethodWithArgs, arg1='foo', arg2=10) self.assertEqual(self._method_count, 1)
'Test multiple operations executed by UserOpManager.'
def testMultipleUserOps(self):
self._CreateTestOp(user_id=1, handler=self._OpMethod) self._CreateTestOp(user_id=1, handler=self._OpMethod) self._CreateTestOp(user_id=2, handler=self._OpMethod) self._ExecuteOp(user_id=1, handler=self._OpMethod) self.assertEqual(self._method_count, 3)
'Test new ops added during UserOpManager execution.'
def testAddUserOpsDuring(self):
def _AddOpMethod3(client, callback): 'Create operation with lower op id.' with util.Barrier(callback) as b: op_dict = self._CreateTestOpDict(user_id=1, handler=self._OpMethod) op_dict['operation_id'] = Operation.ConstructOperationId(1, 1) Operation....
'Test case when UserOpManager cannot acquire lock.'
def testLockFailure(self):
self._AcquireOpLock(user_id=1) self.assertRaises(CannotWaitError, self._ExecuteOp, user_id=1, handler=self._OpMethod)
'Test acquiring an abandoned lock.'
def testAbandonedLock(self):
lock = self._AcquireOpLock(user_id=1) lock.Abandon(self._client, self.stop) self.wait() self._ExecuteOp(user_id=1, handler=self._OpMethod) self.assertEqual(self._method_count, 1)
'Test operation_id=None given to UserOpManager.Execute.'
def testNoneOpId(self):
self._CreateTestOp(user_id=1, handler=self._OpMethod) user_op_mgr = self._CreateUserOpManager(user_id=1, handlers=[self._OpMethod], callback=self.stop) user_op_mgr.Execute() self.wait() self.assertEqual(self._method_count, 1)
'Test unknown operation id given to UserOpManager.Execute.'
def testUnknownOpId(self):
user_op_mgr = self._CreateUserOpManager(user_id=1, handlers=[self._OpMethod], callback=self.stop) user_op_mgr.Execute(operation_id='unk1') self.wait()
'Test multiple calls to UserOpManager.Execute.'
def testMultipleExecuteCalls(self):
user_op_mgr = self._CreateUserOpManager(user_id=1, handlers=[self._OpMethod], callback=self.stop) self._CreateTestOp(user_id=1, handler=self._OpMethod) user_op_mgr.Execute(operation_id='unk1') user_op_mgr.Execute() self.wait() self.assertEqual(self._method_count, 1) self._CreateTestOp(user_i...
'Test multiple UserOpManager.Execute, each with a wait callback for a different op.'
def testMultipleWaits(self):
with util.Barrier(self.stop) as b: user_op_mgr = self._CreateUserOpManager(user_id=1, handlers=[self._OpMethod], callback=b.Callback()) op1 = self._CreateTestOp(user_id=1, handler=self._OpMethod) op2 = self._CreateTestOp(user_id=1, handler=self._OpMethod) user_op_mgr.Execute(operatio...
'Test wait for operation that results in failure.'
def testWaitFailure(self):
def _BuggyOpMethod(client, callback): self._method_count += 1 if (self._method_count == 1): raise Exception('some permanent failure') callback() self.assertRaises(Exception, self._ExecuteOp, 1, _BuggyOpMethod) self.assertEqual(self._method_count, 1) self._RunAsy...
'Test op that fails once and then succeeds.'
def testTransientFailure(self):
def _FlakyOpMethod(client, callback): self._method_count += 1 if (self._method_count == 1): raise Exception('some transient failure') callback() self._ExecuteOp(user_id=1, handler=_FlakyOpMethod, wait_for_op=False) self.assertEqual(self._method_count, 2)
'Test op that continually fails.'
def testPermanentFailure(self):
def _BuggyOpMethod(client, callback): self._method_count += 1 raise Exception('some permanent failure') op = self._CreateTestOp(user_id=1, handler=_BuggyOpMethod) user_op_mgr = self._CreateUserOpManager(user_id=1, handlers=[_BuggyOpMethod], callback=self.stop) user_op_mgr.Execute()...
'Test that a previous operation is retried 3 times before the next operation is attempted.'
def testRerunBeforeContinue(self):
@gen.coroutine def _NextOpMethod(client): self._method_count *= 4 @gen.coroutine def _FlakyOpMethod(client): self._method_count += 1 if (self._method_count <= 2): raise Exception('some transient failure') op = self._CreateTestOp(user_id=1, handler=_FlakyOpMe...
'Test when DynamoDB limits the size of the traceback of a failing op.'
def testLargePermanentFailure(self):
def _BuggyOpMethod(client, callback, blob): raise Exception('some permanent failure') op = self._CreateTestOp(user_id=1, handler=_BuggyOpMethod, blob=('A' * (UserOpManager._MAX_OPERATION_SIZE - 200))) user_op_mgr = self._CreateUserOpManager(user_id=1, handlers=[_BuggyOpMethod], callback=self.s...
'Test op that hits an abortable error.'
def testAbortOfPermissionError(self):
def _BuggyOpMethod(client, callback): self._method_count += 1 raise PermissionError('Not Authorized') op = self._CreateTestOp(user_id=1, handler=_BuggyOpMethod) user_op_mgr = self._CreateUserOpManager(user_id=1, handlers=[_BuggyOpMethod], callback=self.stop) user_op_mgr.Execute() ...
'Provide non-existent op-id to UserOpManager.Execute.'
def testMissingOpId(self):
self._CreateTestOp(user_id=1, handler=self._OpMethod) user_op_mgr = self._CreateUserOpManager(user_id=1, handlers=[self._OpMethod], callback=self.stop) user_op_mgr.Execute(operation_id='unknown') self.wait() self.assertEqual(self._method_count, 1)
'Test creation and invocation of nested operation.'
def testNestedOp(self):
@gen.coroutine def _InnerMethod(client, arg1, arg2): self._method_count += 1 self.assertEqual(arg1, 1) self.assertEqual(arg2, 'hello') self.assertEqual(self._method_count, 2) inner_op = Operation.GetCurrent() self.assertEqual(inner_op.user_id, outer_op.user_id) ...
'Test nested op within nested op.'
def testMultiNestedOp(self):
@gen.coroutine def _InnererMethod(client, arg3): self.assertTrue(Operation.GetCurrent().operation_id.startswith('++')) self.assertEqual(arg3, 3) self._method_count += 1 @gen.coroutine def _InnerMethod(client, arg2): self.assertEqual(arg2, 2) self._method_count += ...
'Test nested op that fails with errors.'
def testNestedOpError(self):
@gen.coroutine def _InnerMethod(client): self._method_count += 1 if (self._method_count < 8): raise Exception('permanent error') @gen.coroutine def _OuterMethod(client): self._method_count += 1 if (self._method_count < 8): (yield Operation.Creat...
'Tests indexing of multiple objects with overlapping field values. Creates 100 users, then queries for specific items.'
@async_test def testIndexing(self):
given_names = ['Spencer', 'Peter', 'Brian', 'Chris'] family_names = ['Kimball', 'Mattis', 'McGinnis', 'Schoenbohm'] emails = ['spencer.kimball@emailscrubbed.com', 'spencer@goviewfinder.com', 'petermattis@emailscrubbed.com', 'peter.mattis@gmail.com', 'peter@goviewfinder.com', 'brian.mcginnis@emailscrubbed.co...
'IndexQuery should not return a result list with any None elements.'
def testIndexQueryForNonExistingItem(self):
user = User.CreateFromKeywords(user_id=1, given_name='Mike', family_name='Purtell', email='mike@time.com') self._RunAsync(user.Update, self._client) results = self._RunAsync(User.IndexQuery, self._client, ('user.given_name={v}', {'v': 'Mike'}), col_names=None) self.assertEqual(len(results), 1) self....
'Tests indexing of items in string set columns.'
def testStringSetIndexing(self):
emails = ['spencer.kimball@emailscrubbed.com', 'spencer@goviewfinder.com', 'petermattis@emailscrubbed.com', 'peter.mattis@gmail.com', 'peter@goviewfinder.com', 'brian.mcginnis@emailscrubbed.com', 'brian@goviewfinder.com', 'chris.schoenbohm@emailscrubbed.com', 'chris@goviewfinder.com'] timestamp = util.GetCurren...