def test_getuser(self): """ Test for retrieving username by prepending @ """ # scenario 1: with @ starting in name and extid crusoe = self.fixtures.crusoe service_twitter = 'twitter' oauth_token = environ.get('TWITTER_OAUTH_TOKEN') oauth_token_type = 'Bearer' # NOQA: S105 externalid = models.UserExternalId( service=service_twitter, user=crusoe, userid=crusoe.email.email, username=crusoe.username, oauth_token=oauth_token, oauth_token_type=oauth_token_type, ) db.session.add(externalid) db.session.commit() result1 = models.getuser('@crusoe') self.assertIsInstance(result1, models.User) self.assertEqual(result1, crusoe) # scenario 2: with @ in name and not extid d_email = '*****@*****.**' daenerys = models.User( username='******', fullname="Daenerys Targaryen", email=d_email ) daenerys_email = models.UserEmail(email=d_email, user=daenerys) db.session.add_all([daenerys, daenerys_email]) db.session.commit() result2 = models.getuser(d_email) self.assertIsInstance(result2, models.User) self.assertEqual(result2, daenerys) result3 = models.getuser('@daenerys') self.assertIsNone(result3) # scenario 3: with no @ starting in name, check by UserEmailClaim j_email = '*****@*****.**' jonsnow = models.User(username='******', fullname="Jon Snow") jonsnow_email_claimed = models.UserEmailClaim(email=j_email, user=jonsnow) db.session.add_all([jonsnow, jonsnow_email_claimed]) db.session.commit() result4 = models.getuser(j_email) self.assertIsInstance(result4, models.User) self.assertEqual(result4, jonsnow) # scenario 5: with no @ anywhere in name, fetch username arya = models.User(username='******', fullname="Arya Stark") db.session.add(arya) db.session.commit() result5 = models.getuser('arya') self.assertEqual(result5, arya) # scenario 6: with no starting with @ name and no UserEmailClaim or UserEmail cersei = models.User(username='******', fullname="Cersei Lannister") db.session.add(cersei) db.session.commit() result6 = models.getuser('*****@*****.**') self.assertIsNone(result6)
def test_merge_users(self): """ Test to verify merger of user accounts and return new user """ # Scenario 1: if first user's created_at date is older than second user's # created_at crusoe = self.fixtures.crusoe bathound = models.User(username="******", fullname="Bathound") db.session.add(bathound) db.session.commit() with self.app.test_request_context('/'): merged = models.merge_users(crusoe, bathound) self.assertEqual(merged, crusoe) self.assertIsInstance(merged, models.User) # because the logic is to merge into older account self.assertEqual(crusoe.status, 0) self.assertEqual(bathound.status, 2) # Scenario 2: if second user's created_at date is older than first user's # created_at tyrion = models.User(username='******', fullname="Tyrion Lannister") db.session.add(tyrion) db.session.commit() subramanian = models.User(username='******', fullname="Tyrion Subramanian") db.session.add(subramanian) db.session.commit() with self.app.test_request_context('/'): merged = models.merge_users(subramanian, tyrion) self.assertEqual(merged, tyrion) self.assertIsInstance(merged, models.User) # because the logic is to merge into older account self.assertEqual(tyrion.status, 0) self.assertEqual(subramanian.status, 2)
def test_user_password_is(self): """ Test to retrieve hashed password for a user """ # scenario 1: no password been set oldmajor = models.User(username='******') assert oldmajor.password_is('oinkoink') is False # scenario 3: if password has been set dumbeldore = models.User('dumbeldore', fullname='Albus Dumberldore') dumbeldore_password = '******' dumbeldore.password = dumbeldore_password assert dumbeldore.password_is(dumbeldore_password) is True
def test_user_all(self): """ Test for User's all method """ # scenario 1: when neither buids or usernames are passed with pytest.raises(Exception): models.User.all() crusoe = models.User.get(username='******') oakley = models.User.get(username='******') expected_result = [oakley, crusoe] # scenario 2: when both buids and usernames are passed lookup_by_both = models.User.all( buids=[crusoe.buid], usernames=[oakley.username] ) assert isinstance(lookup_by_both, list) assert set(lookup_by_both) == set(expected_result) # scenario 3: when only buids are passed lookup_by_buids = models.User.all(buids=[crusoe.buid, oakley.buid]) assert isinstance(lookup_by_buids, list) assert set(lookup_by_buids) == set(expected_result) # scenario 4: when only usernames are passed lookup_by_usernames = models.User.all( usernames=[crusoe.username, oakley.username] ) assert isinstance(lookup_by_usernames, list) assert set(lookup_by_usernames) == set(expected_result) # scenario 5: when defercols is set to True lookup_by_usernames = models.User.all( usernames=[crusoe.username, oakley.username], defercols=True ) assert isinstance(lookup_by_usernames, list) assert set(lookup_by_usernames) == set(expected_result) # scenario 6: when user.status is active hannibal = models.User(username='******') hannibal.status = models.USER_STATUS.ACTIVE db.session.add(hannibal) db.session.commit() lookup_by_buid_status = models.User.all(usernames=[hannibal.username]) assert isinstance(lookup_by_buid_status, list) assert lookup_by_buid_status[0].status == hannibal.status # scenario 7 : when user.status is USER_STATUS.MERGED jykll = models.User() hyde = models.User() db.session.add_all([jykll, hyde]) db.session.commit() with self.app.test_request_context('/'): models.merge_users(jykll, hyde) db.session.commit() lookup_by_buid_merged = models.User.all(buids=[hyde.buid]) assert isinstance(lookup_by_buid_merged, list) assert lookup_by_buid_merged[0].username == jykll.username
def test_useremailclaim_all(self): """ Test for retrieving all UserEmailClaim instances given an email address """ gail = models.User(username='******', fullname='Gail Hawthorne') peeta = models.User(username='******', fullname='Peeta Mallark') email = '*****@*****.**' claim_by_gail = models.UserEmailClaim(user=gail, email=email) claim_by_peeta = models.UserEmailClaim(user=peeta, email=email) db.session.add(claim_by_gail) db.session.add(claim_by_peeta) db.session.commit() result = models.UserEmailClaim.all(email) self.assertCountEqual(set(result), {claim_by_gail, claim_by_peeta})
def test_user_phone(self): """ Test to retrieve UserPhone property phone """ # scenario 1: when there is a phone set as primary crusoe = models.User.get(username='******') crusoe_phone = ( models.UserPhone.query.join(models.User) .filter(models.User.username == 'crusoe') .one() ) assert isinstance(crusoe.phone, models.UserPhone) assert crusoe_phone == crusoe.phone assert crusoe.phone.primary is True # scenario 2: when there is a phone but not as primary snowball = models.User(username='******') snowball_phone = models.UserPhone(phone='+918574808032', user=snowball) db.session.add_all([snowball, snowball_phone]) db.session.commit() assert isinstance(snowball.phone, models.UserPhone) assert snowball_phone == snowball.phone assert snowball.phone.primary is True # scenario 3: when there is no phone on db piglet = models.User.get(username='******') assert piglet.phone == ''
def test_user_password(self): """ Test to set user password """ # Scenario 1: Set None as password castle = models.User(username='******', fullname='Rick Castle') castle.password = None assert castle.pw_hash is None # Scenario 2: Set valid password kate = models.User(username='******', fullname='Detective Kate Beckette') kate.password = '******' db.session.add(kate) db.session.commit() result = models.User.get(buid=kate.buid) assert len(result.pw_hash) == 77 # Argon2 hash assert result.password_is('12thprecinct') is True assert result.pw_expires_at > result.pw_set_at
def test_authtoken_refresh(self): """Test to verify creation of new token while retaining the refresh token.""" hagrid = models.User(username='******', fullname='Rubeus Hagrid') auth_token = models.AuthToken(user=hagrid, algorithm='hmac-sha-1') existing_token = auth_token.token existing_secret = auth_token.secret auth_token.refresh() self.assertNotEqual(existing_token, auth_token.token) self.assertNotEqual(existing_secret, auth_token.secret)
def test_useremailclaim_email(self): """ Test for verifying UserEmailClaim email property """ effie = models.User(username='******', fullname='Miss. Effie Trinket') email = '*****@*****.**' claim_by_effie = models.UserEmailClaim(user=effie, email=email) self.assertIsInstance(claim_by_effie.email, str) self.assertEqual(claim_by_effie.email, email)
def test_make_email_primary(self): """ Test to make an email primary for a user """ mr_whymper = models.User(username='******') whymper_email = '*****@*****.**' whymper_result = mr_whymper.add_email(whymper_email) mr_whymper.primary_email = whymper_result assert whymper_result.email == whymper_email assert whymper_result.primary is True
def test_double_assigned_name(self): """ Names cannot be assigned to both a user and an organization simultaneously """ user = models.User(username="******", fullname="User") org = models.Organization(name="double-assigned", title="Organization", owner=self.fixtures.piglet) db.session.add_all([user, org]) with self.assertRaises(IntegrityError): db.session.commit()
def test_user_is_profile_complete(self): """ Test to check if user profile is complete that is fullname, username and email are present """ crusoe = models.User.get(username='******') assert crusoe.is_profile_complete() is True lena = models.User() db.session.add(lena) db.session.commit() assert lena.is_profile_complete() is False
def test_user(self): """ Test for creation of user object from User model """ user = models.User(username='******', fullname="Lena Audrey Dachshund") db.session.add_all([user]) db.session.commit() lena = models.User.get(username='******') assert isinstance(lena, models.User) assert user.username == 'lena' assert user.fullname == "Lena Audrey Dachshund"
def team_merge_data(test_client): db = models.db db.create_all() user1 = models.User( username='******', fullname="User 1", created_at=db.func.utcnow() - timedelta(days=1), ) user2 = models.User(username='******', fullname="User 2") org = models.Organization( name='test-org-team-merge', title="Organization", owner=user1 ) team = models.Team(title="Team", organization=org) db.session.add_all([user1, user2, org, team]) db.session.commit() yield SimpleNamespace(**locals()) db.session.rollback() db.drop_all()
def test_userclientpermissions_migrate_user(self): """ Test for migrating users and transfering their client permissions """ # scenario 1: when *only* olduser has UserClientPermissions instance old_crusoe = self.fixtures.crusoe new_crusoe = models.User(username='******') models.AuthClientUserPermissions.migrate_user(old_crusoe, new_crusoe) for each in new_crusoe.client_permissions: self.assertIsInstance(each, models.AuthClientUserPermissions) self.assertEqual(new_crusoe.client_permissions[0].user, new_crusoe) # scenario 2: when *both* olduser and newuser have UserClientPermissions instances old_oakley = self.fixtures.oakley auth_client = self.fixtures.auth_client access_permissions_old_oakley = 'siteadmin' access_permissions_new_oakley = 'siteeditor' old_oakley_userclientperms = models.AuthClientUserPermissions( user=old_oakley, auth_client=auth_client, access_permissions=access_permissions_old_oakley, ) new_oakley = models.User(username='******') new_oakley_userclientperms = models.AuthClientUserPermissions( user=new_oakley, auth_client=auth_client, access_permissions=access_permissions_new_oakley, ) db.session.add(old_oakley_userclientperms) db.session.add(new_oakley_userclientperms) db.session.commit() models.AuthClientUserPermissions.migrate_user(old_oakley, new_oakley) result = new_oakley.client_permissions[0] for each in new_oakley.client_permissions: self.assertIsInstance(each, models.AuthClientUserPermissions) received_access_permissions = str(result.access_permissions) expected_access_permissions = " ".join( [access_permissions_old_oakley, access_permissions_new_oakley]) self.assertEqual(expected_access_permissions, received_access_permissions)
def test_userclientpermissions_buid(self): """ Test for UserClientPermissions' buid """ beetee = models.User(username='******', fullname="Beetee") district3 = models.AuthClient(title='District 3') access_permissions = 'siteadmin' result = models.AuthClientUserPermissions( user=beetee, auth_client=district3, access_permissions=access_permissions) self.assertEqual(result.buid, beetee.buid)
def test_userclientpermissions_pickername(self): """ Test for UserClientPermissions' pickername """ finnick = models.User(username='******', fullname="Finnick Odair") district4 = models.AuthClient(title="District 4") access_permissions = 'siteadmin' result = models.AuthClientUserPermissions( user=finnick, auth_client=district4, access_permissions=access_permissions) self.assertEqual(result.pickername, finnick.pickername)
def test_scopemixin_scope(self): """Test to retrieve scope on an ScopeMixin inherited class instance via scope method""" scope = 'tricks' ginny = models.User(username='******', fullname='Ginny Weasley') auth_client = self.fixtures.auth_client ginny_token = models.AuthToken(auth_client=auth_client, user=ginny, scope=scope, validity=0) db.session.add_all([ginny, ginny_token]) db.session.commit() self.assertEqual(ginny_token.scope, (scope, ))
def test_scopemixin__scope_get(self): """Test to retrieve scope with __scope_get on an AuthToken instance """ scope = ['teams', 'email', 'id'] khal = models.User(username='******', fullname='Khal Drogo') auth_client = self.fixtures.auth_client khal_token = models.AuthToken(auth_client=auth_client, user=khal, scope=scope, validity=0) db.session.add_all([khal, khal_token]) db.session.commit() self.assertEqual(khal_token._scope_get(), tuple(sorted(scope)))
def test_user_password_has_expired(self): """ Test to check if password for a user has expired """ alexis = models.User(username='******', fullname='Alexis Castle') alexis.password = '******' alexis.pw_expires_at = utcnow() + timedelta(0, 0, 1) db.session.add(alexis) db.session.commit() result = models.User.get(buid=alexis.buid) assert result is not None assert alexis.password_has_expired() is True
def test_authtoken_is_valid(self): """ Test for verifying if AuthToken's token is valid """ auth_client = self.fixtures.auth_client # scenario 1: when validity is unlimited (0) tomriddle = models.User(username='******', fullname='Tom Riddle') scope = ['id', 'email'] tomriddle_token = models.AuthToken( auth_client=auth_client, user=tomriddle, scope=scope, validity=0 ) self.assertTrue(tomriddle_token.is_valid()) # scenario 2: when validity has not been given draco = models.User(username='******', fullname='Draco Malfoy') draco_token = models.AuthToken(auth_client=auth_client, user=draco, scope=scope) with self.assertRaises(TypeError): draco_token.is_valid() # scenario 3: when validity is limited harry = models.User(username='******', fullname='Harry Potter') harry_token = models.AuthToken( auth_client=auth_client, user=harry, scope=scope, validity=3600, created_at=utcnow(), ) self.assertTrue(harry_token.is_valid()) # scenario 4: when validity is limited *and* the token has expired cedric = models.User(username='******', fullname='Cedric Diggory') cedric_token = models.AuthToken( auth_client=auth_client, user=cedric, scope=scope, validity=1, created_at=utcnow() - timedelta(1), ) self.assertFalse(cedric_token.is_valid())
def test_user_get(self): """ Test for User's get method """ # scenario 1: if both username and buid not passed with pytest.raises(TypeError): models.User.get() crusoe = models.User.get(username='******') piglet = models.User.get(username='******') # scenario 2: if buid is passed lookup_by_buid = models.User.get(buid=crusoe.buid) assert isinstance(lookup_by_buid, models.User) assert lookup_by_buid.buid == crusoe.buid # scenario 3: if username is passed lookup_by_username = models.User.get(username="******") assert isinstance(lookup_by_username, models.User) assert lookup_by_username.username == "crusoe" # scenario 4: if defercols is set to True lookup_by_username = models.User.get(username="******", defercols=True) assert isinstance(lookup_by_username, models.User) assert lookup_by_username.username == "crusoe" # scenario 5: when user.status is active lector = models.User() lector.status = models.USER_STATUS.ACTIVE db.session.add(lector) db.session.commit() lookup_by_buid_status = models.User.get(buid=lector.buid) assert isinstance(lookup_by_buid_status, models.User) assert lookup_by_buid_status.status == lector.status # scenario 6 : when user.status is USER_STATUS.MERGED piglet = models.User.get(username='******') piggy = models.User(username='******') db.session.add(piggy) db.session.commit() with self.app.test_request_context('/'): models.merge_users(piglet, piggy) db.session.commit() lookup_by_buid_merged = models.User.get(buid=piggy.buid) assert isinstance(lookup_by_buid_merged, models.User) assert lookup_by_buid_merged.username == piglet.username
def test_user_email(self): """ Test to retrieve UserEmail property email """ # scenario 1: when there is primary email address crusoe = models.User.get(username='******') assert isinstance(crusoe.email, models.UserEmail) assert crusoe.email == crusoe.email # scenario 2: when there is no primary email address mr_pilkington = models.User(username='******') mr_pilkington_email = models.UserEmail( user=mr_pilkington, email='*****@*****.**' ) db.session.add_all([mr_pilkington, mr_pilkington_email]) db.session.commit() assert mr_pilkington.email.email == mr_pilkington_email.email assert mr_pilkington.email.primary is True # scenario 3: when no email address is on db clover = models.User(username='******') db.session.add(clover) db.session.commit() assert clover.email == ''
def test_scopemixin__scope_set(self): """Test to set scope with __scope_set on an AuthToken instance""" """Test to retrieve scope with __scope_get on an AuthToken instance """ scope = ['teams', 'wars', 'alliances'] sansa = models.User(username='******', fullname='Sansa Stark') auth_client = self.fixtures.auth_client sansa_token = models.AuthToken(auth_client=auth_client, user=sansa, validity=0) sansa_token._scope_set(scope) db.session.add_all([sansa, sansa_token]) db.session.commit() self.assertEqual(sansa_token._scope_get(), tuple(sorted(scope)))
def test_userclientpermissions(self): """ Test for verifying creation of UserClientPermissions instance """ gustav = models.User(username='******') auth_client = self.fixtures.auth_client access_permissions = 'siteadmin' result = models.AuthClientUserPermissions( user=gustav, auth_client=auth_client, access_permissions=access_permissions) db.session.add(result) db.session.commit() self.assertIsInstance(result, models.AuthClientUserPermissions)
def test_useremailclaim_get(self): """ Test for retrieving a UserEmailClaim instance given a user """ katnis = models.User(username='******', fullname='Katnis Everdeen') email = '*****@*****.**' email_claim = models.UserEmailClaim(user=katnis, email=email) db.session.add(email_claim) db.session.commit() result = models.UserEmailClaim.get_for(user=katnis, email=email) self.assertIsInstance(result, models.UserEmailClaim) self.assertEqual(result.email, email) self.assertEqual(result.user, katnis)
def test_authtoken_algorithm(self): """ Test for checking AuthToken's algorithm property """ snape = models.User(username='******', fullname='Professor Severus Snape') valid_algorithm = 'hmac-sha-1' auth_token = models.AuthToken(user=snape) auth_token.algorithm = None self.assertIsNone(auth_token._algorithm) auth_token.algorithm = valid_algorithm self.assertEqual(auth_token._algorithm, valid_algorithm) self.assertEqual(auth_token.algorithm, valid_algorithm) with self.assertRaises(ValueError): auth_token.algorithm = "hmac-sha-2016"
def test_scopemixin__scope(self): """ Test to retrieve scope on an ScopeMixin inherited class instance via _scope method """ scope = 'id' bellatrix = models.User(username='******', fullname='Bellatrix Lestrange') auth_client = self.fixtures.auth_client bellatrix_token = models.AuthToken(auth_client=auth_client, user=bellatrix, scope=scope, validity=0) db.session.add_all([bellatrix, bellatrix_token]) db.session.commit() self.assertEqual(bellatrix_token._scope, scope)
def test_user_is_valid_name(self): """ Test to check if given is a valid username associated with the user """ crusoe = models.User.get(username='******') # scenario 1: not a valid username number_one = models.User(username='******', fullname='Number One') assert number_one.is_valid_name('Number1') is True # Mixed case is now allowed assert number_one.is_valid_name('Number_1') is False # Underscores are not # scenario 2: a valid username but not the username of instance passed assert crusoe.is_valid_name("oakley") is False # scenario 3: a existing username crusoe.is_valid_name("crusoe") is True # scenario 4: a existing org batdog = models.Organization.get(name='batdog') assert crusoe.is_valid_name(batdog.name) is False
def test_user_pickername(self): """ Test to verify fullname and username (if any) """ # scenario 1: when username exists crusoe = models.User.get(username='******') result = crusoe.pickername expected_result = '{fullname} (@{username})'.format( fullname=crusoe.fullname, username=crusoe.username ) assert result == expected_result # scenario 2: when username doesnt exist mr_fedrick = models.User(fullname='Mr. Fedrick') result = mr_fedrick.pickername expected_result = '{fullname}'.format(fullname=mr_fedrick.fullname) assert result == expected_result