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
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))
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_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 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_user_check_password(self): with self.instance.test_request_context() as request: u = UserFactory(login='******', email='*****@*****.**') self.assertTrue(u.is_authenticated()) self.assertTrue(u.is_active()) self.assertFalse(u.is_anonymous()) password = '******' u.set_password(password) self.assertTrue(u.check_password(password))
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 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
class TestSignInRedirect: def get_redirect_response(self, client, next=None): password = "******" self.user = UserFactory() self.user.set_password(password) self.user.save() EmailAddress.objects.create(user=self.user, email=self.user.email, verified=True) url = reverse("account_login") if next: url += f"?next={next}" return client.post( url, data={ "login": 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 reverse("profile-detail-redirect").endswith( response.redirect_chain[0][0]) 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
class TestUserModel(TestHelper): def setUp(self): self.post = PostFactory() self.user = UserFactory(posts=(self.post, )) db.session.commit() def test_UserModel_password_hashing_must_return_True_for_equals_passwords( self): test_password = '******' self.user.set_password(test_password) self.assertTrue(self.user.check_password(test_password)) def test_UserModel_password_hashing_must_return_False_for_non_equals_passwords( self): self.user.set_password('test_password') self.assertFalse(self.user.check_password('other_pass')) def test_UserModel_must_have_post(self): posts = self.user.posts.all() self.assertListEqual([self.post], posts) def test_UserModel_must_return_empty_list_if_user_have_not_posts(self): self.user.posts.delete() self.assertListEqual([], self.user.posts.all()) def test_UserModel_is_exist_classmethod_must_return_True_for_exist_user( self): self.assertTrue(User.is_exist(username=self.user.username)) def test_UserModel_is_exist_classmethod_must_return_False_for_not_existed_user( self): self.assertFalse( User.is_exist(username='******')) def test_UserModel_is_following_method_must_return_False_if_new_user_not_in_followed_list( self): new_user = UserFactory() self.assertFalse(self.user.is_following(new_user)) def test_UserModel_is_following_method_must_return_True_if_new_user_in_followed_list( self): new_user = UserFactory() self.user.followed.append(new_user) self.assertTrue(self.user.is_following(new_user)) def test_UserModel_follow_method_must_append_new_user_to_followed(self): new_user = UserFactory() self.user.follow(new_user) self.assertIn(new_user, self.user.followed.all()) def test_UserModel_follow_method_must_append_user_to_followers_of_new_user( self): new_user = UserFactory() self.user.follow(new_user) self.assertIn(self.user, new_user.followers.all()) def test_UserModel_unfollow_method_must_remove_new_user_from_followed_list_of_user( self): new_user = UserFactory() self.user.followed.append(new_user) self.user.unfollow(new_user) self.assertNotIn(new_user, self.user.followed.all()) self.assertNotIn(self.user, new_user.followers.all()) def test_UserModel_followed_post_must_returned_list_must_contain_post1_and_post2( self): new_user = UserFactory() post1 = PostFactory(author=new_user) post2 = PostFactory(author=new_user) self.user.followed.append(new_user) user_posts = self.user.followed_posts().all() self.assertIn(post1, user_posts) self.assertIn(post2, user_posts) def test_UserModel_followed_post_must_return_list_of_new_user_posts_with_own_user_posts( self): new_user = UserFactory() post1 = PostFactory(author=new_user) post2 = PostFactory(author=new_user) self.user.followed.append(new_user) expected = [post2, post1, *self.user.posts.all()] self.assertListEqual(expected, list(self.user.followed_posts()))
class GrandChallengeFrameworkTestCase(TestCase): def setUp(self): self.set_up_base() self.set_up_extra() def set_up_base(self): """Function will be run for all subclassed testcases.""" self._create_root_superuser() def set_up_extra(self): """Overwrite this method in child classes.""" pass def _create_root_superuser(self): User = get_user_model() # noqa: N806 try: self.root = User.objects.filter(username="******")[0] except IndexError: self.root = UserFactory(username="******", email="*****@*****.**", is_active=True) self.root.set_password("testpassword") self.root.save() EmailAddress.objects.create(user=self.root, email=self.root.email, verified=True) def _create_dummy_project(self, projectname="testproject"): """ Create a project with some pages and users. In part this is done through admin views, meaning admin views are also tested here. """ # Create three types of users that exist: Root, can do anything, # projectadmin, cam do things to a project he or she owns. And logged in # user # created in _create_main_project_and_root. root = self.root # non-root users are created as if they signed up through the project, # to maximize test coverage. # A user who has created a project projectadmin = self._create_random_user("projectadmin") testproject = self._create_challenge_in_admin(projectadmin, projectname) create_page(testproject, "testpage1") create_page(testproject, "testpage2") # a user who explicitly signed up to testproject participant = self._create_random_user("participant") self._register(participant, testproject) # a user who only signed up but did not register to any project registered_user = self._create_random_user("registered") # TODO: How to do this gracefully? return [testproject, root, projectadmin, participant, registered_user] def _register(self, user, project): """ Register user for the given project, follow actual signup as closely as possible. """ RegistrationRequestFactory(challenge=project, user=user) self.assertTrue( project.is_participant(user), "After registering as user %s , user does not " " appear to be registered." % (user.username), ) def _test_page_can_be_viewed(self, user, page): page_url = reverse( "pages:detail", kwargs={ "challenge_short_name": page.challenge.short_name, "page_title": page.title, }, ) return self._test_url_can_be_viewed(user, page_url) def _test_page_can_not_be_viewed(self, user, page): page_url = reverse( "pages:detail", kwargs={ "challenge_short_name": page.challenge.short_name, "page_title": page.title, }, ) return self._test_url_can_not_be_viewed(user, page_url) def _test_url_can_be_viewed(self, user, url): response, username = self._view_url(user, url) self.assertEqual( response.status_code, 200, "could not load page" "'%s' logged in as user '%s'. Expected HTML200, got HTML%s" % (url, user, str(response.status_code)), ) return response def _test_url_can_not_be_viewed(self, user, url): response, username = self._view_url(user, url) self.assertNotEqual( response.status_code, 200, "could load restricted " "page'%s' logged in as user '%s'" % (url, username), ) return response def _find_errors_in_page(self, response): """ See if there are any errors rendered in the html of response. Used for checking forms. Also checks for 403 response forbidden. Return string error message if anything does not check out, "" if not. """ if response.status_code == 403: return "Could not check for errors, as response was a 403 response\ forbidden. User asking for this url did not have permission." errors = re.search( '<ul class="errorlist">(.*)</ul>', response.content.decode(), re.IGNORECASE, ) if errors: # show a little around the actual error to scan for variables that # might have caused it span = errors.span() wide_start = max(span[0] - 200, 0) wide_end = min(span[1] + 200, len(response.content)) wide_error = response.content[wide_start:wide_end] return wide_error else: # See if there are any new style errors soup = BeautifulSoup(response.content, "html.parser") errors = soup.findAll("span", attrs={"class": "invalid-feedback"}) if len(errors) > 0: return str(errors) return "" def _view_url(self, user, url): self._login(user) url, kwargs = get_http_host(url=url, kwargs={}) response = self.client.get(url, **kwargs) if user is None: username = "******" else: username = user.username return response, username def _signup_user(self, overwrite_data=None): """Create a user in the same way as a new user is signed up on the project. any key specified in data overwrites default key passed to form. For example, signup_user({'username':'******'}) to creates a user called 'user1' and fills the rest with default data. """ if overwrite_data is None: overwrite_data = {} data = { "first_name": "test", "last_name": "test", "username": "******", "email": "*****@*****.**", "password1": "testpassword", "password2": "testpassword", "institution": "test", "department": "test", "country": "NL", "website": "http://www.example.com", "accept_terms": True, } data.update(overwrite_data) # overwrite any key in default if in data self.client.logout() response = self.client.post(reverse("account_signup"), data, follow=True) assert response.status_code == 200 assert response.template_name == ["account/verification_sent.html"] assert get_user_model().objects.get(username=data["username"]) def _create_random_user(self, startname=""): username = startname + "".join( [choice("AEOUY") + choice("QWRTPSDFGHHKLMNB") for x in range(3)]) data = {"username": username, "email": username + "@test.com"} return self._create_user(data) def _create_user(self, data): """ Sign up user in a way as close to production as possible. Check a lot of stuff. Data is a dictionary form_field:for_value pairs. Any unspecified values are given default values. """ username = data["username"] self._signup_user(data) validation_mail = [ e for e in mail.outbox if e.recipients() == [data["email"]] ][0] self.assertTrue( "Please Confirm Your E-mail" in validation_mail.subject, "There was no email sent which had 'Please Confirm Your E-mail' " "in the subject line", ) # validate the user with the link that was emailed pattern = "/testserver(.*)" + PI_LINE_END_REGEX validationlink_result = re.search(pattern, validation_mail.body, re.IGNORECASE) self.assertTrue( validationlink_result, "could not find any link in" "registration email. Tried to match pattern '{}' but found no match in" "this email: {}{}".format(pattern, PI_LINE_END_REGEX, validation_mail.body), ) validationlink = validationlink_result.group(1).strip() response = self.client.post(validationlink, follow=True) self.assertEqual( response.status_code, 200, "Could not load user validation link. Expected" " a redirect (HTTP 200), got HTTP {} instead".format( response.status_code), ) resp = self.client.get("/users/" + username + "/") self.assertEqual( resp.status_code, 200, "Could not access user account after using" "validation link! Expected 200, got {} instead".format( resp.status_code), ) User = get_user_model() # noqa: N806 query_result = User.objects.filter(username=username) return query_result[0] def _try_create_challenge(self, user, short_name, description="test project"): url = reverse("challenges:create") data = { "short_name": short_name, "description": description, "logo": create_uploaded_image(), "banner": create_uploaded_image(), "prefix": "form", "page_set-TOTAL_FORMS": "0", "page_set-INITIAL_FORMS": "0", "page_set-MAX_NUM_FORMS": "", } self._login(user) response = self.client.post(url, data) return response def _create_challenge_in_admin(self, user, short_name, description="test project"): """Create a challenge object as if created through django admin interface.""" response = self._try_create_challenge(user, short_name, description) errors = self._find_errors_in_page(response) if errors: self.assertFalse( errors, f"Error creating project '{short_name}':\n {errors}") # ad.set_base_permissions(request,project) project = Challenge.objects.get(short_name=short_name) return project def _login(self, user, password="******"): """ Log in user an assert whether it worked. Passing None as user will log out. """ self.client.logout() if user is None: return # just log out success = self.client.login(username=user.username, password=password) self.assertTrue( success, "could not log in as user %s using password %s" % (user.username, password), ) return success def assert_email(self, email, email_expected): """ Convenient way to check subject, content, mailto etc at once for an email. email : django.core.mail.message object email_expected : dict like {"subject":"Registration complete","to":"*****@*****.**" } """ for attr in email_expected.keys(): try: found = getattr(email, attr) except AttributeError as e: raise AttributeError( "Could not find attribute '{}' for this email.\ are you sure it exists? - {}".format( attr, str(e))) expected = email_expected[attr] self.assertTrue( expected == found or is_subset(found, expected) or (expected in found), "Expected to find '{}' for email attribute \ '{}' but found '{}' instead".format(expected, attr, found), )
class GrandChallengeFrameworkTestCase(TestCase): def setUp(self): self._create_root_superuser() [ self.testchallenge, self.root, self.challengeadmin, self.participant, self.registered_user, ] = self._create_dummy_project("test-project") def _create_root_superuser(self): self.root = UserFactory( username="******", email="*****@*****.**", is_active=True, is_superuser=True, ) self.root.set_password("testpassword") self.root.save() EmailAddress.objects.create(user=self.root, email=self.root.email, verified=True) def _create_dummy_project(self, projectname="testproject"): """Create a test challenge with some pages and some site users.""" # Create three types of users: # Root = superuser, can do anything, root = self.root # A user who has created a challenge challengeadmin = self._create_random_user("projectadmin") testchallenge = self._create_challenge_in_admin( challengeadmin, projectname) create_page(testchallenge, "testpage1") create_page(testchallenge, "testpage2") # a user who registered for the challenge and was accepted participant = self._create_random_user("participant") self._register(participant, testchallenge) # a user who only signed up to website but did not register to any challenge registered_user = self._create_random_user("registered") return [ testchallenge, root, challengeadmin, participant, registered_user, ] def _register(self, user, challenge): """ Register user for the given challenge, follow actual signup as closely as possible. """ request = RegistrationRequestFactory(challenge=challenge, user=user) request.status = request.ACCEPTED request.save() assert challenge.is_participant(user) def _test_page_can_be_viewed(self, user, page): page_url = reverse( "pages:detail", kwargs={ "challenge_short_name": page.challenge.short_name, "slug": page.slug, }, ) return self._test_url_can_be_viewed(user, page_url) def _test_page_can_not_be_viewed(self, user, page): page_url = reverse( "pages:detail", kwargs={ "challenge_short_name": page.challenge.short_name, "slug": page.slug, }, ) return self._test_url_can_not_be_viewed(user, page_url) def _test_url_can_be_viewed(self, user, url): response, username = self._view_url(user, url) self.assertEqual( response.status_code, 200, "could not load page" "'%s' logged in as user '%s'. Expected HTML200, got HTML%s" % (url, user, str(response.status_code)), ) return response def _test_url_can_not_be_viewed(self, user, url): response, username = self._view_url(user, url) self.assertNotEqual( response.status_code, 200, "could load restricted " "page'%s' logged in as user '%s'" % (url, username), ) return response def _find_errors_in_page(self, response): """ See if there are any errors rendered in the html of response. Used for checking forms. Also checks for 403 response forbidden. Return string error message if anything does not check out, "" if not. """ if response.status_code == 403: return "Could not check for errors, as response was a 403 response\ forbidden. User asking for this url did not have permission." errors = re.search( '<ul class="errorlist">(.*)</ul>', response.content.decode(), re.IGNORECASE, ) if errors: # show a little around the actual error to scan for variables that # might have caused it span = errors.span() wide_start = max(span[0] - 200, 0) wide_end = min(span[1] + 200, len(response.content)) wide_error = response.content[wide_start:wide_end] return wide_error else: # See if there are any new style errors soup = BeautifulSoup(response.content, "html.parser") errors = soup.findAll("span", attrs={"class": "invalid-feedback"}) if len(errors) > 0: return str(errors) return "" def _view_url(self, user, url): self._login(user) url, kwargs = get_http_host(url=url, kwargs={}) response = self.client.get(url, **kwargs) if user is None: username = "******" else: username = user.username return response, username def _signup_user(self, overwrite_data=None): """Create a user in the same way as a new user is signed up on the project. any key specified in data overwrites default key passed to form. For example, signup_user({'username':'******'}) to creates a user called 'user1' and fills the rest with default data. """ if overwrite_data is None: overwrite_data = {} data = { "first_name": "test", "last_name": "test", "username": "******", "email": "*****@*****.**", "password1": "testpassword", "password2": "testpassword", "institution": "test", "department": "test", "country": "NL", "website": "https://www.example.com", "accept_terms": True, } data.update(overwrite_data) # overwrite any key in default if in data self.client.logout() response = self.client.post(reverse("account_signup"), data, follow=True) assert response.status_code == 200 assert response.template_name == ["account/verification_sent.html"] assert get_user_model().objects.get(username=data["username"]) def _create_random_user(self, startname=""): username = startname + "".join( [choice("AEOUY") + choice("QWRTPSDFGHHKLMNB") for x in range(3)]) data = {"username": username, "email": username + "@test.com"} return self._create_user(data) def _create_user(self, data): """ Sign up user in a way as close to production as possible. Check a lot of stuff. Data is a dictionary form_field:for_value pairs. Any unspecified values are given default values. """ username = data["username"] self._signup_user(data) validation_mail = [ e for e in mail.outbox if e.recipients() == [data["email"]] ][0] self.assertTrue( "Please Confirm Your E-mail" in validation_mail.subject, "There was no email sent which had 'Please Confirm Your E-mail' " "in the subject line", ) # validate the user with the link that was emailed pattern = "/testserver(.*)" + PI_LINE_END_REGEX validationlink_result = re.search(pattern, validation_mail.body, re.IGNORECASE) self.assertTrue( validationlink_result, "could not find any link in" "registration email. Tried to match pattern '{}' but found no match in" "this email: {}{}".format(pattern, PI_LINE_END_REGEX, validation_mail.body), ) validationlink = validationlink_result.group(1).strip() response = self.client.post(validationlink, follow=True) self.assertEqual( response.status_code, 200, "Could not load user validation link. Expected" " a redirect (HTTP 200), got HTTP {} instead".format( response.status_code), ) resp = self.client.get("/users/" + username + "/") self.assertEqual( resp.status_code, 200, "Could not access user account after using" "validation link! Expected 200, got {} instead".format( resp.status_code), ) User = get_user_model() # noqa: N806 query_result = User.objects.filter(username=username) return query_result[0] def _try_create_challenge_request(self, user, short_name, title="test project"): url = reverse("challenges:requests-create") data = { "creator": user, "title": title, "short_name": short_name, "contact_email": user.email, "challenge_type": ChallengeRequest.ChallengeTypeChoices.T2, "start_date": datetime.date.today(), "end_date": datetime.date.today() + datetime.timedelta(days=1), "expected_number_of_participants": 10, "abstract": "test", "organizers": "test", "challenge_setup": "test", "data_set": "test", "submission_assessment": "test", "challenge_publication": "test", "code_availability": "test", "expected_number_of_teams": 10, "number_of_tasks": 1, } Verification.objects.get_or_create(user=user, is_verified=True) self._login(user) response = self.client.post(url, data) return response def _create_challenge_in_admin(self, user, short_name, description="test project"): """Create a challenge object as if created through django admin interface.""" Verification.objects.create(user=user, is_verified=True) challenge = Challenge.objects.create(creator=user, short_name=short_name, description=description) return challenge def _login(self, user, password="******"): """ Log in user an assert whether it worked. Passing None as user will log out. """ self.client.logout() if user is None: return # just log out success = self.client.login(username=user.username, password=password) self.assertTrue( success, "could not log in as user %s using password %s" % (user.username, password), ) return success
class TestAUser(OsfTestCase): def setUp(self): super(TestAUser, self).setUp() self.user = UserFactory() self.user.set_password('science') # 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) def _login(self, username, password): '''Log in a user via at the login page.''' res = self.app.get('/account/').maybe_follow() # Fills out login info form = res.forms['signinForm'] # Get the form from its ID form['username'] = username form['password'] = password # submits res = form.submit().maybe_follow() return res def test_can_see_profile_url(self): res = self.app.get(self.user.url).maybe_follow() assert_in(self.user.url, res) def test_can_see_homepage(self): # Goes to homepage res = self.app.get('/').maybe_follow() # Redirects assert_equal(res.status_code, 200) def test_can_log_in(self): # Log in and out self._login(self.user.username, 'science') self.app.get('/logout/') # Goes to home page res = self.app.get('/').maybe_follow() # Clicks sign in button res = res.click('Create an Account or Sign-In').maybe_follow() # Fills out login info form = res.forms['signinForm'] # Get the form from its ID form['username'] = self.user.username form['password'] = '******' # submits res = form.submit().maybe_follow() # Sees dashboard with projects and watched projects assert_in('Projects', res) assert_in('Watchlist', res) def test_sees_flash_message_on_bad_login(self): # Goes to log in page res = self.app.get('/account/').maybe_follow() # Fills the form with incorrect password form = res.forms['signinForm'] form['username'] = self.user.username form['password'] = '******' # Submits res = form.submit() # Sees a flash message assert_in('Log-in failed', res) def test_is_redirected_to_dashboard_already_logged_in_at_login_page(self): res = self._login(self.user.username, 'science') res = self.app.get('/login/').follow() assert_equal(res.request.path, '/dashboard/') def test_sees_projects_in_her_dashboard(self): # the user already has a project project = ProjectFactory(creator=self.user) project.add_contributor(self.user) project.save() # Goes to homepage, already logged in res = self._login(self.user.username, 'science') res = self.app.get('/').maybe_follow() # Clicks Dashboard link in navbar res = res.click('Dashboard', index=0) assert_in('Projects', res) # Projects heading # The project title is listed # TODO: (bgeiger) figure out how to make this assertion work with hgrid view #assert_in(project.title, res) def test_does_not_see_osffiles_in_user_addon_settings(self): res = self._login(self.user.username, 'science') res = self.app.get('/settings/addons/', auth=self.auth, auto_follow=True) assert_not_in('OSF Storage', res) def test_sees_osffiles_in_project_addon_settings(self): project = ProjectFactory(creator=self.user) project.add_contributor(self.user, permissions=['read', 'write', 'admin'], save=True) res = self.app.get('/{0}/settings/'.format(project._primary_key), auth=self.auth, auto_follow=True) assert_in('OSF Storage', res) @unittest.skip("Can't test this, since logs are dynamically loaded") 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_sees_correct_title_home_page(self): # User goes to homepage res = self.app.get('/', auto_follow=True) title = res.html.title.string # page title is correct assert_equal('OSF | Home', title) def test_sees_correct_title_on_dashboard(self): # User goes to dashboard res = self.app.get('/dashboard/', auth=self.auth, auto_follow=True) title = res.html.title.string assert_equal('OSF | Dashboard', title) def test_can_see_make_public_button_if_admin(self): # User is a contributor on a project project = ProjectFactory() project.add_contributor(self.user, permissions=['read', 'write', 'admin'], save=True) # User goes to the project page res = self.app.get(project.url, auth=self.auth).maybe_follow() assert_in('Make Public', res) def test_cant_see_make_public_button_if_not_admin(self): # User is a contributor on a project project = ProjectFactory() project.add_contributor(self.user, permissions=['read', 'write'], save=True) # User goes to the project page res = self.app.get(project.url, auth=self.auth).maybe_follow() assert_not_in('Make Public', res) def test_can_see_make_private_button_if_admin(self): # User is a contributor on a project project = ProjectFactory(is_public=True) project.add_contributor(self.user, permissions=['read', 'write', 'admin'], save=True) # User goes to the project page res = self.app.get(project.url, auth=self.auth).maybe_follow() assert_in('Make Private', res) def test_cant_see_make_private_button_if_not_admin(self): # User is a contributor on a project project = ProjectFactory(is_public=True) project.add_contributor(self.user, permissions=['read', 'write'], save=True) # User goes to the project page res = self.app.get(project.url, auth=self.auth).maybe_follow() assert_not_in('Make Private', res) def test_sees_logs_on_a_project(self): project = ProjectFactory(is_public=True) # User goes to the project's page res = self.app.get(project.url, auth=self.auth).maybe_follow() # Can see log event assert_in('created', res) def test_no_wiki_content_message(self): project = ProjectFactory(creator=self.user) # Goes to project's wiki, where there is no content res = self.app.get('/{0}/wiki/home/'.format(project._primary_key), auth=self.auth) # Sees a message indicating no content assert_in('No wiki content', res) def test_wiki_page_name_non_ascii(self): project = ProjectFactory(creator=self.user) non_ascii = to_mongo_key('WöRlÐé') self.app.get('/{0}/wiki/{1}/'.format(project._primary_key, non_ascii), auth=self.auth, expect_errors=True) project.update_node_wiki(non_ascii, 'new content', Auth(self.user)) assert_in(non_ascii, project.wiki_pages_current) def test_noncontributor_cannot_see_wiki_if_no_content(self): user2 = UserFactory() # user2 creates a public project and adds no wiki content project = ProjectFactory(creator=user2, is_public=True) # self navigates to project res = self.app.get(project.url).maybe_follow() # Should not see wiki widget (since non-contributor and no content) assert_not_in('No wiki content', res) def test_wiki_does_not_exist(self): project = ProjectFactory(creator=self.user) res = self.app.get('/{0}/wiki/{1}/'.format( project._primary_key, 'not a real page yet', ), auth=self.auth, expect_errors=True) assert_in('This wiki page does not currently exist.', res) assert_equal(res.status_code, 404) def test_sees_own_profile(self): res = self.app.get('/profile/', auth=self.auth) td1 = res.html.find('td', text=re.compile(r'Public(.*?)Profile')) td2 = td1.find_next_sibling('td') assert_equal(td2.text, self.user.display_absolute_url) def test_sees_another_profile(self): user2 = UserFactory() res = self.app.get(user2.url, auth=self.auth) td1 = res.html.find('td', text=re.compile(r'Public(.*?)Profile')) td2 = td1.find_next_sibling('td') assert_equal(td2.text, user2.display_absolute_url) # Regression test for https://github.com/CenterForOpenScience/osf.io/issues/1320 @mock.patch('framework.auth.views.mails.send_mail') def test_can_reset_password(self, mock_send_mail): # A registered user user = UserFactory() # goes to the login page url = web_url_for('auth_login') res = self.app.get(url) # and fills out forgot password form form = res.forms['forgotPassword'] form['forgot_password-email'] = user.username # submits res = form.submit() # mail was sent mock_send_mail.assert_called # gets 200 response assert_equal(res.status_code, 200) # URL is /forgotpassword assert_equal(res.request.path, web_url_for('forgot_password'))
def test_set_password(self): user = UserFactory(password='******') assert user.check_password('password123') user.set_password('different_password') assert user.check_password('password123') is False assert user.check_password('different_password') is True
class TestAUser(OsfTestCase): def setUp(self): super(TestAUser, self).setUp() self.user = UserFactory() self.user.set_password('science') # 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) def _login(self, username, password): '''Log in a user via at the login page.''' res = self.app.get('/account/').maybe_follow() # Fills out login info form = res.forms['signinForm'] # Get the form from its ID form['username'] = username form['password'] = password # submits res = form.submit().maybe_follow() return res def test_can_see_profile_url(self): res = self.app.get(self.user.url).maybe_follow() assert_in(self.user.url, res) def test_can_see_homepage(self): # Goes to homepage res = self.app.get('/').maybe_follow() # Redirects assert_equal(res.status_code, 200) def test_can_log_in(self): # Log in and out self._login(self.user.username, 'science') self.app.get('/logout/') # Goes to home page res = self.app.get('/').maybe_follow() # Clicks sign in button res = res.click('Create an Account or Sign-In').maybe_follow() # Fills out login info form = res.forms['signinForm'] # Get the form from its ID form['username'] = self.user.username form['password'] = '******' # submits res = form.submit().maybe_follow() # Sees dashboard with projects and watched projects assert_in('Projects', res) assert_in('Watchlist', res) def test_sees_flash_message_on_bad_login(self): # Goes to log in page res = self.app.get('/account/').maybe_follow() # Fills the form with incorrect password form = res.forms['signinForm'] form['username'] = self.user.username form['password'] = '******' # Submits res = form.submit() # Sees a flash message assert_in('Log-in failed', res) def test_is_redirected_to_dashboard_already_logged_in_at_login_page(self): res = self._login(self.user.username, 'science') res = self.app.get('/login/').follow() assert_equal(res.request.path, '/dashboard/') def test_sees_projects_in_her_dashboard(self): # the user already has a project project = ProjectFactory(creator=self.user) project.add_contributor(self.user) project.save() # Goes to homepage, already logged in res = self._login(self.user.username, 'science') res = self.app.get('/').maybe_follow() # Clicks Dashboard link in navbar res = res.click('Dashboard', index=0) assert_in('Projects', res) # Projects heading # The project title is listed # TODO: (bgeiger) figure out how to make this assertion work with hgrid view #assert_in(project.title, res) def test_does_not_see_osffiles_in_user_addon_settings(self): res = self._login(self.user.username, 'science') res = self.app.get('/settings/addons/', auth=self.auth, auto_follow=True) assert_not_in('OSF Storage', res) def test_sees_osffiles_in_project_addon_settings(self): project = ProjectFactory(creator=self.user) project.add_contributor( self.user, permissions=['read', 'write', 'admin'], save=True) res = self.app.get('/{0}/settings/'.format(project._primary_key), auth=self.auth, auto_follow=True) assert_in('OSF Storage', res) @unittest.skip("Can't test this, since logs are dynamically loaded") 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_sees_correct_title_home_page(self): # User goes to homepage res = self.app.get('/', auto_follow=True) title = res.html.title.string # page title is correct assert_equal('OSF | Home', title) def test_sees_correct_title_on_dashboard(self): # User goes to dashboard res = self.app.get('/dashboard/', auth=self.auth, auto_follow=True) title = res.html.title.string assert_equal('OSF | Dashboard', title) def test_can_see_make_public_button_if_admin(self): # User is a contributor on a project project = ProjectFactory() project.add_contributor( self.user, permissions=['read', 'write', 'admin'], save=True) # User goes to the project page res = self.app.get(project.url, auth=self.auth).maybe_follow() assert_in('Make Public', res) def test_cant_see_make_public_button_if_not_admin(self): # User is a contributor on a project project = ProjectFactory() project.add_contributor( self.user, permissions=['read', 'write'], save=True) # User goes to the project page res = self.app.get(project.url, auth=self.auth).maybe_follow() assert_not_in('Make Public', res) def test_can_see_make_private_button_if_admin(self): # User is a contributor on a project project = ProjectFactory(is_public=True) project.add_contributor( self.user, permissions=['read', 'write', 'admin'], save=True) # User goes to the project page res = self.app.get(project.url, auth=self.auth).maybe_follow() assert_in('Make Private', res) def test_cant_see_make_private_button_if_not_admin(self): # User is a contributor on a project project = ProjectFactory(is_public=True) project.add_contributor( self.user, permissions=['read', 'write'], save=True) # User goes to the project page res = self.app.get(project.url, auth=self.auth).maybe_follow() assert_not_in('Make Private', res) def test_sees_logs_on_a_project(self): project = ProjectFactory(is_public=True) # User goes to the project's page res = self.app.get(project.url, auth=self.auth).maybe_follow() # Can see log event assert_in('created', res) @unittest.skip('"No wiki content" replaced with javascript handling') def test_no_wiki_content_message(self): project = ProjectFactory(creator=self.user) # Goes to project's wiki, where there is no content res = self.app.get('/{0}/wiki/home/'.format(project._primary_key), auth=self.auth) # Sees a message indicating no content assert_in('No wiki content', res) def test_wiki_page_name_non_ascii(self): project = ProjectFactory(creator=self.user) non_ascii = to_mongo_key('WöRlÐé') self.app.get('/{0}/wiki/{1}/'.format( project._primary_key, non_ascii ), auth=self.auth, expect_errors=True) project.update_node_wiki(non_ascii, 'new content', Auth(self.user)) assert_in(non_ascii, project.wiki_pages_current) def test_noncontributor_cannot_see_wiki_if_no_content(self): user2 = UserFactory() # user2 creates a public project and adds no wiki content project = ProjectFactory(creator=user2, is_public=True) # self navigates to project res = self.app.get(project.url).maybe_follow() # Should not see wiki widget (since non-contributor and no content) assert_not_in('No wiki content', res) @unittest.skip(reason='¯\_(ツ)_/¯ knockout.') def test_wiki_does_not_exist(self): project = ProjectFactory(creator=self.user) res = self.app.get('/{0}/wiki/{1}/'.format( project._primary_key, 'not a real page yet', ), auth=self.auth, expect_errors=True) assert_in('No wiki content', res) def test_sees_own_profile(self): res = self.app.get('/profile/', auth=self.auth) td1 = res.html.find('td', text=re.compile(r'Public(.*?)Profile')) td2 = td1.find_next_sibling('td') assert_equal(td2.text, self.user.display_absolute_url) def test_sees_another_profile(self): user2 = UserFactory() res = self.app.get(user2.url, auth=self.auth) td1 = res.html.find('td', text=re.compile(r'Public(.*?)Profile')) td2 = td1.find_next_sibling('td') assert_equal(td2.text, user2.display_absolute_url) # Regression test for https://github.com/CenterForOpenScience/osf.io/issues/1320 @mock.patch('framework.auth.views.mails.send_mail') def test_can_reset_password(self, mock_send_mail): # A registered user user = UserFactory() # goes to the login page url = web_url_for('auth_login') res = self.app.get(url) # and fills out forgot password form form = res.forms['forgotPassword'] form['forgot_password-email'] = user.username # submits res = form.submit() # mail was sent mock_send_mail.assert_called # gets 200 response assert_equal(res.status_code, 200) # URL is /forgotpassword assert_equal(res.request.path, web_url_for('forgot_password'))