class TestCore(OsfTestCase): @mock.patch('website.addons.twofactor.models.push_status_message') def setUp(self, mocked): super(TestCore, self).setUp() self.user = UserFactory() self.user.set_password('badpassword') self.user.save() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') self.user_settings.is_confirmed = True self.user_settings.save() def test_login_valid(self): res = login(username=self.user.username, password='******', two_factor=_valid_code(self.user_settings.totp_secret)) assert_true(isinstance(res, BaseResponse)) assert_equal(res.status_code, 302) def test_login_invalid_code(self): with assert_raises(TwoFactorValidationError): login(username=self.user.username, password='******', two_factor='000000') def test_login_valid_code_invalid_password(self): with assert_raises(PasswordIncorrectError): login(username=self.user.username, password='******', two_factor=_valid_code(self.user_settings.totp_secret))
class TestSearchExceptions(OsfTestCase): """ Verify that the correct exception is thrown when the connection is lost """ @classmethod def setUpClass(cls): super(TestSearchExceptions, cls).setUpClass() if settings.SEARCH_ENGINE == "elastic": cls._es = search.search_engine.es search.search_engine.es = None @classmethod def tearDownClass(cls): super(TestSearchExceptions, cls).tearDownClass() if settings.SEARCH_ENGINE == "elastic": search.search_engine.es = cls._es def test_connection_error(self): """ Ensures that saving projects/users doesn't break as a result of connection errors """ self.user = UserFactory(usename="Doug Bogie") self.project = ProjectFactory(title="Tom Sawyer", creator=self.user, is_public=True) self.user.save() self.project.save()
def test_userfactory(session): user = UserFactory() user.save() assert isinstance(user, User) assert user.id is not None assert user.email is not None assert user.active is not None
def test_uuid_defaults_unique(self, db): user1 = UserFactory() user2 = UserFactory() user1.save() user2.save() assert user1.uuid is not user2.uuid assert isinstance(user1.uuid, UUID)
class TestSignInRedirect: def get_redirect_response(self, client, next=None): password = "******" self.user = UserFactory() self.user.set_password(password) self.user.save() url = reverse("userena_signin") if next: url += f"?next={next}" return client.post( url, data={"identification": self.user.username, "password": password}, follow=True, ) def test_default_redirect(self, client): response = self.get_redirect_response(client) assert response.redirect_chain[0][1] == status.HTTP_302_FOUND assert response.redirect_chain[0][0] == reverse("profile_redirect") assert response.status_code == status.HTTP_200_OK def test_redirect(self, client): expected_url = "/challenges/" response = self.get_redirect_response(client, expected_url) assert response.redirect_chain[0][1] == status.HTTP_302_FOUND assert response.status_code == status.HTTP_200_OK assert response.redirect_chain[0][0] == expected_url def test_no_logout_redirect(self, client): response = self.get_redirect_response(client, settings.LOGOUT_URL) assert response.redirect_chain[0][1] == status.HTTP_302_FOUND assert response.redirect_chain[0][0] == reverse("profile_redirect") assert response.status_code == status.HTTP_200_OK
def test_sees_log_events_on_watched_projects(self): # Another user has a public project u2 = UserFactory(username='******', fullname='Bono') key = ApiKeyFactory() u2.api_keys.append(key) u2.save() project = ProjectFactory(creator=u2, is_public=True) project.add_contributor(u2) auth = Auth(user=u2, api_key=key) # A file was added to the project project.add_file(auth=auth, file_name='test.html', content='123', size=2, content_type='text/html') project.save() # User watches the project watch_config = WatchConfigFactory(node=project) self.user.watch(watch_config) self.user.save() # Goes to her dashboard, already logged in res = self.app.get('/dashboard/', auth=self.auth, auto_follow=True) # Sees logs for the watched project assert_in('Watched Projects', res) # Watched Projects header # The log action is in the feed assert_in('added file test.html', res) assert_in(project.title, res)
def test_update_comments_viewed_timestamp_none(self): user = UserFactory() user.comments_viewed_timestamp = {} user.save() update_comments_viewed_timestamp() user.reload() assert_equal(user.comments_viewed_timestamp, {})
class TestMigrateMailingLists(OsfTestCase): def setUp(self): super(TestMigrateMailingLists, self).setUp() self.user1 = UserFactory(mailing_lists={'mail': True}) self.user2 = UserFactory(mailing_lists={'mail': False}) self.user3 = UserFactory() self.user1.save() self.user2.save() def test_get_users_with_mailing_lists(self): users_with_mailing_list_ids = [ user._id for user in get_users_with_no_mailchimp_mailing_lists() ] assert_equal(len(users_with_mailing_list_ids), 2) assert_true(self.user1._id in users_with_mailing_list_ids) assert_true(self.user2._id in users_with_mailing_list_ids) assert_false(self.user3._id in users_with_mailing_list_ids) def test_migration_of_mailing_lists(self): assert_equal(self.user1.mailchimp_mailing_lists, {}) assert_equal(self.user2.mailchimp_mailing_lists, {}) main() self.user1.reload() self.user2.reload() assert_true(self.user1.mailchimp_mailing_lists.get(u'mail')) assert_false(self.user2.mailchimp_mailing_lists.get(u'mail'))
class TestMigrateMailingLists(OsfTestCase): def setUp(self): super(TestMigrateMailingLists, self).setUp() self.user1 = UserFactory(mailing_lists={'mail': True}) self.user2 = UserFactory(mailing_lists={'mail': False}) self.user3 = UserFactory() self.user1.save() self.user2.save() def test_get_users_with_mailing_lists(self): users_with_mailing_list_ids = [user._id for user in get_users_with_no_mailchimp_mailing_lists()] assert_equal(len(users_with_mailing_list_ids), 2) assert_true(self.user1._id in users_with_mailing_list_ids) assert_true(self.user2._id in users_with_mailing_list_ids) assert_false(self.user3._id in users_with_mailing_list_ids) def test_migration_of_mailing_lists(self): assert_equal(self.user1.mailchimp_mailing_lists, {}) assert_equal(self.user2.mailchimp_mailing_lists, {}) main() self.user1.reload() self.user2.reload() assert_true(self.user1.mailchimp_mailing_lists.get(u'mail')) assert_false(self.user2.mailchimp_mailing_lists.get(u'mail'))
class TestSearchExceptions(OsfTestCase): # Verify that the correct exception is thrown when the connection is lost @classmethod def setUpClass(cls): logging.getLogger('website.project.model').setLevel(logging.CRITICAL) super(TestSearchExceptions, cls).setUpClass() if settings.SEARCH_ENGINE == 'elastic': cls._es = search.search_engine.es search.search_engine.es = None @classmethod def tearDownClass(cls): super(TestSearchExceptions, cls).tearDownClass() if settings.SEARCH_ENGINE == 'elastic': search.search_engine.es = cls._es def test_connection_error(self): # Ensures that saving projects/users doesn't break as a result of connection errors self.user = UserFactory(usename='Doug Bogie') self.project = ProjectFactory( title="Tom Sawyer", creator=self.user, is_public=True, ) self.user.save() self.project.save()
class TestSearchExceptions(OsfTestCase): """ Verify that the correct exception is thrown when the connection is lost """ @classmethod def setUpClass(cls): logging.getLogger('website.project.model').setLevel(logging.CRITICAL) super(TestSearchExceptions, cls).setUpClass() if settings.SEARCH_ENGINE == 'elastic': cls._es = search.search_engine.es search.search_engine.es = None @classmethod def tearDownClass(cls): super(TestSearchExceptions, cls).tearDownClass() if settings.SEARCH_ENGINE == 'elastic': search.search_engine.es = cls._es def test_connection_error(self): # Ensures that saving projects/users doesn't break as a result of connection errors self.user = UserFactory(usename='Doug Bogie') self.project = ProjectFactory( title="Tom Sawyer", creator=self.user, is_public=True, ) self.user.save() self.project.save()
class TestShortUrls(OsfTestCase): def setUp(self): super(TestShortUrls, self).setUp() self.user = UserFactory() # Add an API key for quicker authentication api_key = ApiKeyFactory() self.user.api_keys.append(api_key) self.user.save() self.auth = ('test', api_key._primary_key) self.consolidate_auth = Auth(user=self.user, api_key=api_key) self.project = ProjectFactory(creator=self.user) # A non-project componenet self.component = NodeFactory(category='hypothesis', creator=self.user) self.project.nodes.append(self.component) self.component.save() # Hack: Add some logs to component; should be unnecessary pending # improvements to factories from @rliebz self.component.set_privacy('public', auth=self.consolidate_auth) self.component.set_privacy('private', auth=self.consolidate_auth) self.wiki = NodeWikiFactory(user=self.user, node=self.component) def _url_to_body(self, url): return self.app.get(url, auth=self.auth).maybe_follow( auth=self.auth, ).normal_body def test_profile_url(self): res1 = self.app.get('/{}/'.format( self.user._primary_key)).maybe_follow() res2 = self.app.get('/profile/{}/'.format( self.user._primary_key)).maybe_follow() assert_equal(res1.normal_body, res2.normal_body) def test_project_url(self): assert_equal( self._url_to_body(self.project.deep_url), self._url_to_body(self.project.url), ) def test_component_url(self): assert_equal( self._url_to_body(self.component.deep_url), self._url_to_body(self.component.url), ) def _mock_rendered_file(self, component, fobj): node_settings = component.get_addon('osffiles') cache_dir = get_cache_path(node_settings) cache_file = get_cache_file(fobj.filename, fobj.latest_version_number(component)) cache_file_path = os.path.join(cache_dir, cache_file) ensure_path(cache_dir) with open(cache_file_path, 'w') as fp: fp.write('test content') def test_wiki_url(self): assert_equal( self._url_to_body(self.wiki.deep_url), self._url_to_body(self.wiki.url), )
class TestRegistrations(OsfTestCase): def setUp(self): super(TestRegistrations, self).setUp() ensure_schemas() self.user = UserFactory() # Add an API key for quicker authentication api_key = ApiKeyFactory() self.user.api_keys.append(api_key) self.user.save() self.auth = ('test', api_key._primary_key) self.original = ProjectFactory(creator=self.user, is_public=True) # A registration self.project = RegistrationFactory( creator=self.user, project=self.original, user=self.user, ) def test_can_see_contributor(self): # Goes to project's page res = self.app.get(self.project.url, auth=self.auth).maybe_follow() # Settings is not in the project navigation bar subnav = res.html.select('#projectSubnav')[0] assert_in('Sharing', subnav.text) def test_sees_registration_templates(self): # Browse to original project res = self.app.get('{}register/'.format(self.original.url), auth=self.auth).maybe_follow() # Find registration options options = res.html.find( 'select', id='select-registration-template').find_all('option') # Should see number of options equal to number of registration # templates, plus one for 'Select...' assert_equal(len(options), len(OSF_META_SCHEMAS) + 1) # First option should have empty value assert_equal(options[0].get('value'), '') # All registration templates should be listed in <option> option_values = [option.get('value') for option in options[1:]] for schema in OSF_META_SCHEMAS: assert_in(schema['name'], option_values) def test_registration_nav_not_seen(self): # Goes to project's page res = self.app.get(self.project.url, auth=self.auth).maybe_follow() # Settings is not in the project navigation bar subnav = res.html.select('#projectSubnav')[0] assert_not_in('Registrations', subnav.text) def test_settings_nav_not_seen(self): # Goes to project's page res = self.app.get(self.project.url, auth=self.auth).maybe_follow() # Settings is not in the project navigation bar subnav = res.html.select('#projectSubnav')[0] assert_not_in('Settings', subnav.text)
def test_multiple_users_associated(self): # Create only one ExternalAccount for multiple OSF users # # For some providers (ex: GitHub), the act of completing the OAuth flow # revokes previously generated credentials. In addition, there is often no # way to know the user's id on the external service until after the flow # has completed. # # Having only one ExternalAccount instance per account on the external # service means that connecting subsequent OSF users to the same external # account will not invalidate the credentials used by the OSF for users # already associated. user_a = UserFactory() external_account = ExternalAccountFactory( provider='mock2', provider_id='mock_provider_id', provider_name='Mock Provider', ) user_a.external_accounts.append(external_account) user_a.save() user_b = UserFactory() # Mock the exchange of the code for an access token _prepare_mock_oauth2_handshake_response() # Fake a request context for the callback with self.app.app.test_request_context( path="/oauth/callback/mock2/", query_string="code=mock_code&state=mock_state" ) as ctx: # make sure the user is logged in authenticate(user=user_b, access_token=None, response=None) session = get_session() session.data['oauth_states'] = { self.provider.short_name: { 'state': 'mock_state', }, } session.save() # do the key exchange self.provider.auth_callback(user=user_b) user_a.reload() user_b.reload() external_account.reload() assert_equal( user_a.external_accounts, user_b.external_accounts, ) assert_equal( ExternalAccount.find().count(), 1 )
def test_update_comments_viewed_timestamp(self): user = UserFactory() timestamp = datetime.utcnow().replace(microsecond=0) user.comments_viewed_timestamp = {'abc123': timestamp} user.save() update_comments_viewed_timestamp() user.reload() assert_equal(user.comments_viewed_timestamp, {'abc123': {'node': timestamp}})
def test_verify_reset_password(self): user1 = UserFactory(first_name='Foo', last_name='Bar') user1.save() token = user1.get_reset_password_token() user2 = User.verify_reset_password_token(token) assert user1 == user2
def test_no_two_emails_to_same_person(self, mock_send): user = UserFactory() user.osf_mailing_lists[settings.OSF_HELP_LIST] = True user.save() self.queue_mail(user=user) self.queue_mail(user=user) main(dry_run=False) assert_equal(mock_send.call_count, 1)
def test_roles(db): """Add a role to a user.""" role = Role(name="admin") role.save() user = UserFactory() user.roles.append(role) user.save() assert role in user.roles
def test_multiple_users_associated(self): # Create only one ExternalAccount for multiple OSF users # # For some providers (ex: GitHub), the act of completing the OAuth flow # revokes previously generated credentials. In addition, there is often no # way to know the user's id on the external service until after the flow # has completed. # # Having only one ExternalAccount instance per account on the external # service means that connecting subsequent OSF users to the same external # account will not invalidate the credentials used by the OSF for users # already associated. user_a = UserFactory() external_account = ExternalAccountFactory( provider='mock2', provider_id='mock_provider_id', provider_name='Mock Provider', ) user_a.external_accounts.append(external_account) user_a.save() user_b = UserFactory() # Mock the exchange of the code for an access token _prepare_mock_oauth2_handshake_response() # Fake a request context for the callback with self.app.app.test_request_context( path="/oauth/callback/mock2/", query_string="code=mock_code&state=mock_state" ) as ctx: # make sure the user is logged in authenticate(user=user_b, access_token=None, response=None) session.data['oauth_states'] = { self.provider.short_name: { 'state': 'mock_state', }, } session.save() # do the key exchange self.provider.auth_callback(user=user_b) user_a.reload() user_b.reload() external_account.reload() assert_equal( user_a.external_accounts, user_b.external_accounts, ) assert_equal( ExternalAccount.find().count(), 1 )
def test_login_disabled_user(self): """Logging in to a disabled account fails""" user = UserFactory() user.set_password('Leeloo') user.is_disabled = True user.save() with assert_raises(auth.LoginDisabledError): auth.login(user.username, 'Leeloo')
def test_post_sign_in(self): username = "******" password = "******" user = UserFactory(username=username) user.set_password(password) user.save() data = {"username": username, "password": password} self.post("backoffice:sign-in", data=data) self.response_302()
def user_client(db): """Create logged in user.""" user = UserFactory() user.set_password('user') user.save() client = Client() client.login(username=user.username, password='******') return client
def test_name_fields(self): names = ['Bill Nye', 'William', 'the science guy', 'Sanford', 'the Great'] user = UserFactory(fullname=names[0]) user.given_name = names[1] user.middle_names = names[2] user.family_name = names[3] user.suffix = names[4] user.save() docs = [query_user(name)['results'] for name in names] assert_equal(sum(map(len, docs)), len(docs)) # 1 result each assert_true(all([user._id == doc[0]['id'] for doc in docs]))
def test_was_not_invited(self): referrer = UserFactory() node = NodeFactory(creator=referrer) user = UserFactory() node.add_contributor(user, auth=Auth(referrer)) assert_false(is_invited(user)) user.is_invited = None user.save() main(dry_run=False) user.reload() assert_false(user.is_invited)
def test_name_fields(self): names = ["Bill Nye", "William", "the science guy", "Sanford", "the Great"] user = UserFactory(fullname=names[0]) user.given_name = names[1] user.middle_names = names[2] user.family_name = names[3] user.suffix = names[4] user.save() docs = [query_user(name)["results"] for name in names] assert_equal(sum(map(len, docs)), len(docs)) # 1 result each assert_true(all([user._id == doc[0]["id"] for doc in docs]))
def test_update_comments_viewed_timestamp(self): user = UserFactory() timestamp = datetime.utcnow().replace(microsecond=0) user.comments_viewed_timestamp = {'abc123': timestamp} user.save() update_comments_viewed_timestamp() user.reload() assert_equal(user.comments_viewed_timestamp, {'abc123': { 'node': timestamp }})
def create_request_user(username=None, password=None): if username: user = UserFactory(username=username) else: user = UserFactory() if password: user.set_password(password) else: user.set_password('password') user.save() return user
class TestDisabledUser(OsfTestCase): def setUp(self): super(TestDisabledUser, self).setUp() self.user = UserFactory() self.user.set_password("Korben Dallas") self.user.is_disabled = True self.user.save() def test_profile_disabled_returns_401(self): res = self.app.get(self.user.url, expect_errors=True) assert_equal(res.status_code, 410)
class TestDisabledUser(OsfTestCase): def setUp(self): super(TestDisabledUser, self).setUp() self.user = UserFactory() self.user.set_password('Korben Dallas') self.user.is_disabled = True self.user.save() def test_profile_disabled_returns_401(self): res = self.app.get(self.user.url, expect_errors=True) assert_equal(res.status_code, 410)
def test_merged_user(self): user = UserFactory(fullname='Annie Lennox') merged_user = UserFactory(fullname='Lisa Stansfield') user.save() merged_user.save() assert_equal(len(query_user(user.fullname)['results']), 1) assert_equal(len(query_user(merged_user.fullname)['results']), 1) user.merge_user(merged_user) assert_equal(len(query_user(user.fullname)['results']), 1) assert_equal(len(query_user(merged_user.fullname)['results']), 0)
def test_employment(self): user = UserFactory(fullname="Helga Finn") user.save() institution = "Finn's Fine Filers" docs = query_user(institution)["results"] assert_equal(len(docs), 0) user.jobs.append({"institution": institution, "title": "The Big Finn"}) user.save() docs = query_user(institution)["results"] assert_equal(len(docs), 1)
def test_education(self): user = UserFactory(fullname="Henry Johnson") user.save() institution = "Henry's Amazing School!!!" docs = query_user(institution)["results"] assert_equal(len(docs), 0) user.schools.append({"institution": institution, "degree": "failed all classes"}) user.save() docs = query_user(institution)["results"] assert_equal(len(docs), 1)
def test_merged_user(self): user = UserFactory(fullname="Annie Lennox") merged_user = UserFactory(fullname="Lisa Stansfield") user.save() merged_user.save() assert_equal(len(query_user(user.fullname)["results"]), 1) assert_equal(len(query_user(merged_user.fullname)["results"]), 1) user.merge_user(merged_user) assert_equal(len(query_user(user.fullname)["results"]), 1) assert_equal(len(query_user(merged_user.fullname)["results"]), 0)
def test_user(session, db, request): oldcount = User.query.count() testuser = UserFactory() testuser.save() assert User.query.count() > oldcount, 'User not created' testuser.set_password('magic123') assert verify_password('magic123',User.query.get(testuser.id).password),\ 'Password setting not working' with current_app.app_context(): assert None == testuser.to_dict().get( 'password'), "User displaying password"
def test_get_basket_variable_GET_data_as_superuser(self): """Can we get basket variable data.""" superuser = UserFactory(username="******") superuser.is_superuser = True superuser.save() self.client.force_authenticate(user=superuser) response = self.client.get(self.API_PATH) results = json.loads(response.content)["results"] basket = results[0] self.assertEqual(self.basket_variable.basket_id, basket["basket_id"]) self.assertEqual(str(self.basket_variable.variable_id), basket["variable_id"]) superuser.delete()
def test_create_basket_superuser(self): """Only user with permissions should be able to create a basket.""" client = APIClient() dummy_user = UserFactory(username="******") dummy_user.is_superuser = True dummy_user.save() client.force_authenticate(user=dummy_user) request = client.get(self.API_PATH) self.assertEqual(200, request.status_code) dummy_user.delete()
def test_change_name(self): # Add a user, change her name, and verify that only the new name is # found in search. user = UserFactory(fullname='Barry Mitchell') fullname_original = user.fullname user.fullname = user.fullname[::-1] user.save() docs_original = query_user(fullname_original)['results'] assert_equal(len(docs_original), 0) docs_current = query_user(user.fullname)['results'] assert_equal(len(docs_current), 1)
class TestSearching(OsfTestCase): '''Test searching using the search bar. NOTE: These may affect the Solr database. May need to migrate after running these. ''' def setUp(self): super(TestSearching, self).setUp() import website.search.search as search search.delete_all() self.user = UserFactory() # Add an API key for quicker authentication api_key = ApiKeyFactory() self.user.api_keys.append(api_key) self.user.save() self.auth = ('test', api_key._primary_key) @unittest.skip(reason='¯\_(ツ)_/¯ knockout.') def test_a_user_from_home_page(self): user = UserFactory() # Goes to home page res = self.app.get('/').maybe_follow() # Fills search form form = res.forms['searchBar'] form['q'] = user.fullname res = form.submit().maybe_follow() # The username shows as a search result assert_in(user.fullname, res) @unittest.skip(reason='¯\_(ツ)_/¯ knockout.') def test_a_public_project_from_home_page(self): project = ProjectFactory(title='Foobar Project', is_public=True) # Searches a part of the name res = self.app.get('/').maybe_follow() project.reload() form = res.forms['searchBar'] form['q'] = 'Foobar' res = form.submit().maybe_follow() # A link to the project is shown as a result assert_in('Foobar Project', res) @unittest.skip(reason='¯\_(ツ)_/¯ knockout.') def test_a_public_component_from_home_page(self): component = NodeFactory(title='Foobar Component', is_public=True) # Searches a part of the name res = self.app.get('/').maybe_follow() component.reload() form = res.forms['searchBar'] form['q'] = 'Foobar' res = form.submit().maybe_follow() # A link to the component is shown as a result assert_in('Foobar Component', res)
class TestCore(OsfTestCase): def setUp(self): self.user = UserFactory() self.user.add_addon('menbib') self.user.save() self.settings = self.user.get_addon('menbib') self.settings.access_token = '12345' self.settings.refresh_token = 'abcde' self.settings.save() def test_get_addon_returns_menbib_user_settings(self): result = self.user.get_addon('menbib') assert_true(isinstance(result, AddonMenbibUserSettings))
def create_fake_user(): email = fake.email() name = fake.name() parsed = utils.impute_names(name) user = UserFactory(username=email, fullname=name, is_registered=True, is_claimed=True, date_registered=fake.date_time(), emails=[email], **parsed ) user.set_password('faker123') user.save() logger.info('Created user: {0} <{1}>'.format(user.fullname, user.username)) return user
def test_error_message_user_already_registered(self, user, testapp): user = UserFactory(active=True) # A registered user user.save() # Goes to registration page res = testapp.get(url_for('auth.register')) # Fills out form, but username is already registered form = res.forms['registerForm'] form['username'] = user.username form['email'] = '*****@*****.**' form['password'] = '******' form['confirm'] = 'secret' # Submits res = form.submit() # sees error assert 'Username already registered' in res
def test_disabled_user(self): """Test that disabled users are not in search index""" user = UserFactory(fullname='Bettie Page') user.save() # Ensure user is in search index assert_equal(len(query_user(user.fullname)['results']), 1) # Disable the user user.is_disabled = True user.save() # Ensure user is not in search index assert_equal(len(query_user(user.fullname)['results']), 0)
def test_education(self): user = UserFactory(fullname='Henry Johnson') user.save() institution = 'Henry\'s Amazing School!!!' docs = query_user(institution)['results'] assert_equal(len(docs), 0) user.schools.append({ 'institution': institution, 'degree': 'failed all classes', }) user.save() docs = query_user(institution)['results'] assert_equal(len(docs), 1)
def test_employment(self): user = UserFactory(fullname='Helga Finn') user.save() institution = 'Finn\'s Fine Filers' docs = query_user(institution)['results'] assert_equal(len(docs), 0) user.jobs.append({ 'institution': institution, 'title': 'The Big Finn', }) user.save() docs = query_user(institution)['results'] assert_equal(len(docs), 1)
def test_disabled_user(self): # Test that disabled users are not in search index user = UserFactory(fullname='Bettie Page') user.save() # Ensure user is in search index assert_equal(len(query_user(user.fullname)['results']), 1) # Disable the user user.is_disabled = True user.save() # Ensure user is not in search index assert_equal(len(query_user(user.fullname)['results']), 0)
def test_callback_wrong_user(self): # Reject temporary credentials not assigned to the user # # This prohibits users from associating their external account with # another user's OSF account by using XSS or similar attack vector to # complete the OAuth flow using the logged-in user but their own account # on the external service. # # If the OSF were to allow login via OAuth with the provider in question, # this would allow attackers to hijack OSF accounts with a simple script # injection. # mock a successful call to the provider to exchange temp keys for # permanent keys httpretty.register_uri( httpretty.POST, 'http://mock1a.com/callback', body='oauth_token=perm_token' '&oauth_token_secret=perm_secret' '&oauth_callback_confirmed=true', ) user = UserFactory() account = ExternalAccountFactory( provider="mock1a", provider_name='Mock 1A', oauth_key="temp_key", oauth_secret="temp_secret", temporary=True ) account.save() # associate this ExternalAccount instance with the user user.external_accounts.append(account) user.save() malicious_user = UserFactory() # Fake a request context for the callback with self.app.app.test_request_context( path="/oauth/callback/mock1a/", query_string="oauth_token=temp_key&oauth_verifier=mock_verifier" ): # make sure the user is logged in authenticate(user=malicious_user, access_token=None, response=None) with assert_raises(PermissionsError): # do the key exchange self.provider.auth_callback(user=malicious_user)
class TestCore(OsfTestCase): def setUp(self): super(TestCore, self).setUp() self.user = UserFactory() self.user.add_addon('box') self.user.save() self.settings = self.user.get_addon('box') self.settings.save() def test_get_addon_returns_box_user_settings(self): result = self.user.get_addon('box') assert_true(isinstance(result, BoxUserSettings))
def test_sees_error_message_if_user_already_registered(self, user, testapp): """Show error if user already registered.""" user = UserFactory(active=True) # A registered user user.save() # Goes to registration page res = testapp.get(url_for('public.register')) # Fills out form, but username is already registered form = res.forms['registerForm'] form['username'] = user.username form['email'] = '*****@*****.**' form['password'] = '******' form['confirm'] = 'secret' # Submits res = form.submit() # sees error assert 'Username already registered' in res
class TestShortUrls(OsfTestCase): def setUp(self): super(TestShortUrls, self).setUp() self.user = UserFactory() # Add an API key for quicker authentication api_key = ApiKeyFactory() self.user.api_keys.append(api_key) self.user.save() self.auth = ('test', api_key._primary_key) self.consolidate_auth = Auth(user=self.user, api_key=api_key) self.project = ProjectFactory(creator=self.user) # A non-project componenet self.component = NodeFactory(category='hypothesis', creator=self.user) self.project.nodes.append(self.component) self.component.save() # Hack: Add some logs to component; should be unnecessary pending # improvements to factories from @rliebz self.component.set_privacy('public', auth=self.consolidate_auth) self.component.set_privacy('private', auth=self.consolidate_auth) self.wiki = NodeWikiFactory(user=self.user, node=self.component) def _url_to_body(self, url): return self.app.get( url, auth=self.auth ).maybe_follow( auth=self.auth, ).normal_body def test_project_url(self): assert_equal( self._url_to_body(self.project.deep_url), self._url_to_body(self.project.url), ) def test_component_url(self): assert_equal( self._url_to_body(self.component.deep_url), self._url_to_body(self.component.url), ) def test_wiki_url(self): assert_equal( self._url_to_body(self.wiki.deep_url), self._url_to_body(self.wiki.url), )