def test_email_uniqueness_case_insensitive(self): UserFactory.create(email="*****@*****.**") with self.assertRaises(ValidationError) as error: UserFactory.create(email="*****@*****.**") self.assertEqual( error.exception.messages, ["That email address is already in use."])
def test_create_user(): # Check there are 0 users before a new user is added number_users = OCDActionUser.objects.count() assert number_users == 0 # Check there is 1 user after a new user is added UserFactory.create() number_users = OCDActionUser.objects.count() assert number_users == 1
def test_get_email_appellation_priority_list(self): user = UserFactory.create(first_name="my_first", last_name="my_last") from accounts.utils import relate_user_method_settings relate_user_method_settings.__dict__ = {} with override_settings( RELATE_USER_FULL_NAME_FORMAT_METHOD=None): self.assertEqual(user.get_email_appellation(), "my_first") relate_user_method_settings.__dict__ = {} with override_settings( RELATE_EMAIL_APPELLATION_PRIORITY_LIST=[""]): relate_user_method_settings.__dict__ = {} self.assertEqual(user.get_email_appellation(), "my_first") relate_user_method_settings.__dict__ = {} with override_settings( RELATE_EMAIL_APPELLATION_PRIORITY_LIST=["whatever"]): self.assertEqual(user.get_email_appellation(), "my_first") relate_user_method_settings.__dict__ = {} # not a list with override_settings( RELATE_EMAIL_APPELLATION_PRIORITY_LIST="whatever"): self.assertEqual(user.get_email_appellation(), "my_first") relate_user_method_settings.__dict__ = {} with override_settings( RELATE_EMAIL_APPELLATION_PRIORITY_LIST=["full_name"], RELATE_USER_FULL_NAME_FORMAT_METHOD=None): self.assertEqual(user.get_email_appellation(), "my_first my_last") # create a user without first_name user = UserFactory.create(last_name="my_last") relate_user_method_settings.__dict__ = {} # the next appelation is email with override_settings( RELATE_USER_FULL_NAME_FORMAT_METHOD=None): self.assertEqual(user.get_email_appellation(), user.email) relate_user_method_settings.__dict__ = {} with override_settings( RELATE_EMAIL_APPELLATION_PRIORITY_LIST=["full_name", "username"], RELATE_USER_FULL_NAME_FORMAT_METHOD=None): # because full_name is None self.assertEqual(user.get_email_appellation(), user.username)
def test_cant_have_same_member_twice(self): u1 = UserFactory.create() u2 = UserFactory.create() try: Team.create(name="test-team-same-member-twice", owner=u1, members=[u2, u2]) except ValueError: ex = sys.exc_info()[1] expect(ex).to_have_an_error_message_of("Can't have the same user twice in the members collection.") return assert False, "Should not have gotten this far"
def test_remove_user(self): user = UserFactory.create() user2 = UserFactory.create() team = TeamFactory.create(owner=self.user, members=[user2]) response = self.delete("/teams/%s/members" % team.name, user=user2.email) expect(response.code).to_equal(200) expect(response.body).to_equal("OK") team = Team.objects.filter(name=team.name).first() expect(team).not_to_be_null() expect(team.members).to_length(0) expect(team.members).not_to_include(user)
def test_get_hikes_not_authenticated(self): user1 = UserFactory.create() hike1 = HikeFactory.create(owner=user1) user2 = UserFactory.create() hike2 = HikeFactory.create(owner=user2) url = reverse('hike-list') self.client.force_authenticate(user=user1) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, hike1.uuid) self.assertNotContains(response, hike2.uuid)
def setUp(self): # feincms page containing zipfelchappe app content self.page = Page.objects.create(title="Projects", slug="projects") ct = self.page.content_type_for(ApplicationContent) ct.objects.create(parent=self.page, urlconf_path=app_settings.ROOT_URLS) # Fixture Data for following tests self.project1 = ProjectFactory.create() self.project2 = ProjectFactory.create() self.user = UserFactory.create() self.admin = UserFactory.create(is_superuser=True, is_staff=True) self.reward = RewardFactory.create(project=self.project1, minimum=20.00, quantity=1) # Fresh Client for every test self.client = Client()
def test_get_return_200_if_not_team_owner(self): self._add_results_for_last() user = UserFactory.create(with_token=True) TeamFactory.create(owner=user) url = "/load-test-result/%s/last/" % self.load_test2.results[1].uuid response = self.fetch_with_headers(url) expect(response.code).to_equal(200)
def test_after_adding_a_editor_to_a_map_a_editor_added_action_is_triggered(self): a_user = UserFactory.create() a_map = MapFactory.create(creator=a_user) another_user = UserFactory.create() a_map.editors.add(another_user) am = ActivityManager() added_to_editors = am.added_to_editors(a_user) self.assertTrue(len(added_to_editors)) action = added_to_editors[0] self.assertEqual(action.actor, a_user) self.assertEqual(action.action_object, another_user) self.assertEqual(action.target, a_map) self.assertEqual(action.verb, ADDED_TO_EDITORS)
def test_add_team_member_twice(self): user = UserFactory.create() team = TeamFactory.create(owner=self.user, members=[user]) response = self.patch("/teams/%s/members" % team.name, user=user.email) expect(response.code).to_equal(409) expect(response.body).to_equal("User already team member")
def test_get_notes(self): user1 = UserFactory.create() note1 = NoteFactory.create(owner=user1) user2 = UserFactory.create() note2 = NoteFactory.create(owner=user2) url = reverse('note-list') self.client.force_authenticate(user=user1) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, note1.uuid) self.assertContains(response, note1.revision) self.assertContains(response, note1.text) self.assertContains(response, note1.title) self.assertNotContains(response, note2.uuid)
def test_custom_get_full_name_method_failed(self): """ Test when RELATE_USER_FULL_NAME_FORMAT_METHOD failed, default method is used. """ user = UserFactory.create(first_name="my_first", last_name="my_last") default_get_full_name = user.get_full_name() custom_get_full_name_path = ( "tests.resource.my_customized_get_full_name_method") get_custom_full_name_method_path = ( "accounts.utils.RelateUserMethodSettingsInitializer" ".custom_full_name_method") with override_settings( RELATE_USER_FULL_NAME_FORMAT_METHOD=custom_get_full_name_path): from accounts.utils import relate_user_method_settings # clear cached value relate_user_method_settings.__dict__ = {} # If custom method works, the returned value is different with # default value. self.assertNotEqual(default_get_full_name, user.get_full_name()) with mock.patch(get_custom_full_name_method_path) as mock_custom_method: # clear cached value relate_user_method_settings.__dict__ = {} # raise an error when calling custom method mock_custom_method.side_effect = Exception() # the value falls back to default value self.assertEqual(user.get_full_name(), default_get_full_name)
def test_get_authenticated(self): """Authenticated users can view add resource page.""" self.login_user(UserFactory.create()) response = self._get(url=self.url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, self.template_name) self.failUnless('form' in response.context)
def test_get_return_200_if_not_team_owner(self): self._add_results() user = UserFactory.create(with_token=True) TeamFactory.create(owner=user) url = "/results/%s/%s/%s/%s/%s" % (self.team.name, self.project.name, self.config.module, self.config.class_name, self.config.test_name) response = self.fetch_with_headers(url) expect(response.code).to_equal(200)
def setUp(self): self.project = ProjectFactory.create() self.user = UserFactory.create() self.backer = BackerFactory.create(user=self.user) self.p1 = PledgeFactory.create( project=self.project, amount=10.00, )
def test_after_removing_a_editor_from_a_map_a_editor_removed_action_is_triggered(self): a_user = UserFactory.create() a_map = MapFactory.create(creator=a_user) another_user = UserFactory.create() a_map.editors.add(another_user) a_map.editors.remove(another_user) am = ActivityManager() removed_from_editors = am.removed_from_editors(a_user) self.assertTrue(len(removed_from_editors)) action = removed_from_editors[0] self.assertEqual(action.actor, a_user) self.assertEqual(action.action_object, another_user) self.assertEqual(action.target, a_map) self.assertEqual(action.verb, REMOVED_FROM_EDITORS)
def test_try_to_delete_a_not_owner_team(self): team = TeamFactory.create(owner=UserFactory.create(with_token=True)) response = self.delete("/teams/%s" % team.name) expect(response.code).to_equal(403) team = Team.objects.filter(name=team.name).first() expect(team).not_to_be_null()
def test_get_return_403_if_not_team_owner(self): user = UserFactory.create(with_token=True) team = TeamFactory.create(owner=user) url = "/teams/%s/projects/%s/load-tests/%s/results/some-result-uuid" % ( team.name, self.project.name, self.load_test.uuid ) response = self.fetch_with_headers(url) expect(response.code).to_equal(403)
def test_authenticate_using_token(self): user = UserFactory.create() exists, auth_user = User.authenticate(email=user.email, password=UserFactory.get_default_password()) expect(auth_user).not_to_be_null() auth_user = User.authenticate_with_token(token=auth_user.token) expect(auth_user).not_to_be_null()
def setUp(self): super(DeleteTeamProjectTest, self).setUp() self.user = UserFactory.create(with_token=True) self.team = TeamFactory.create(owner=self.user) TeamFactory.add_projects(self.team, 1) TeamFactory.add_members(self.team, 2) self.project = self.team.projects[0]
def test_can_add_user(self): team = TeamFactory.create(owner=self.user) user = UserFactory.create() result = self.execute("team-adduser", team.name, user.email) expect(result).to_be_like("User '%s' added to Team '%s'." % (user.email, team.name)) team = Team.objects.filter(name=team.name).first() expect(team.members).to_include(user)
def test_authenticating(self): user = UserFactory.create() exists, auth_user = User.authenticate(email=user.email, password="******") expect(exists).to_be_true() expect(auth_user).not_to_be_null() expect(auth_user.token).not_to_be_null() expect(auth_user.token_expiration).not_to_be_null()
def test_get_last_3_load_tests_for_all_projects_when_owner(self): LoadTestFactory.add_to_project(4, user=self.user, team=self.team, project=self.project) LoadTestFactory.add_to_project(4, user=self.user, team=self.team, project=self.team.projects[1]) team = TeamFactory.create(owner=self.user) TeamFactory.add_projects(team, 1) LoadTestFactory.add_to_project(4, user=self.user, team=team, project=team.projects[0]) LoadTestFactory.add_to_project(4, user=UserFactory.create()) loaded_tests = list(LoadTest.get_by_user(self.user)) expect(loaded_tests).to_length(9)
def test_save_institutional_id_none(self): user = UserFactory.create(institutional_id="1234") users = get_user_model().objects.all() self.assertTrue(users.count(), 1) self.assertEqual(users[0].institutional_id, "1234") user.institutional_id = " " user.save() self.assertIsNone(get_user_model().objects.first().institutional_id)
def test_can_remove_user(self): user = UserFactory.create() team = TeamFactory.create(owner=self.user, members=[user]) result = self.execute("team-removeuser", team.name, user.email) expect(result).to_be_like("User '%s' removed from Team '%s'." % (user.email, team.name)) team = Team.objects.filter(name=team.name).first() expect(team.members).not_to_include(user)
def setUp(self): super(ShowTestResultForTeamProjectAndTestTest, self).setUp() self.user = UserFactory.create(with_token=True) self.team = TeamFactory.create(owner=self.user) TeamFactory.add_projects(self.team, 2) self.project = self.team.projects[0] self.load_test = LoadTestFactory.create(created_by=self.user, team=self.team, project_name=self.project.name, status="Finished") self.load_test.save() self.config = TestConfigurationFactory.build() self.config2 = TestConfigurationFactory.build()
def test_authenticating_with_wrong_pass_returns_none(self): created_user = UserFactory.create() exists, user = User.authenticate(email="*****@*****.**", password="******") expect(exists).to_be_false() expect(user).to_be_null() exists, user = User.authenticate(email=created_user.email, password="******") expect(exists).to_be_true() expect(user).to_be_null()
def setUp(self): super(ShowLoadLastTestResultTest, self).setUp() self.user = UserFactory.create(with_token=True) self.team = TeamFactory.create(owner=self.user) TeamFactory.add_projects(self.team, 1) self.project = self.team.projects[0] self.load_test = LoadTestFactory.create(created_by=self.user, team=self.team, project_name=self.project.name, status="Finished") self.load_test.results.append(TestResultFactory.build()) self.load_test.save() self.result = self.load_test.results[0]
def test_created_by_invalid_user(self): user = UserFactory.create() team = TeamFactory.create() try: team.add_project(name="test-can-create-project", repository="repo", created_by=user) except ValidationError: exc = sys.exc_info()[1] expect(str(exc)).to_include("Only the owner or members of team %s can create projects for it." % team.name) return assert False, "Should not have gotten this far"
def test_remove_user_that_does_not_belong_to_team(self): user = UserFactory.create() team = TeamFactory.create(owner=self.user) response = self.delete("/teams/%s/members" % team.name, user=user.email) expect(response.code).to_equal(400) expect(response.body).to_equal("User not found") team = Team.objects.filter(name=team.name).first() expect(team).not_to_be_null() expect(team.members).to_length(0)
def test_member_table_access(client, user_session): admin = UserFactory.create() portfolio = PortfolioFactory.create(owner=admin) rando = UserFactory.create() PortfolioRoleFactory.create( user=rando, portfolio=portfolio, permission_sets=[PermissionSets.get(PermissionSets.VIEW_PORTFOLIO_ADMIN)], ) url = url_for("portfolios.admin", portfolio_id=portfolio.id) # editable user_session(admin) edit_resp = client.get(url) assert "<select" in edit_resp.data.decode() # not editable user_session(rando) view_resp = client.get(url) assert "<select" not in view_resp.data.decode()
def test_invite(): portfolio = PortfolioFactory.create() inviter = UserFactory.create() member_data = UserFactory.dictionary() invitation = Portfolios.invite(portfolio, inviter, {"user_data": member_data}) assert invitation.role assert invitation.role.portfolio == portfolio assert invitation.role.user is None assert invitation.dod_id == member_data["dod_id"]
def test_add_user(self): user = UserFactory.create() team = TeamFactory.create(owner=self.user) response = self.patch("/teams/%s/members" % team.name, user=user.email) expect(response.code).to_equal(200) expect(response.body).to_equal("OK") team = Team.objects.filter(name=team.name).first() expect(team).not_to_be_null() expect(team.members).to_length(1) expect(team.members).to_include(user)
def test_apiview_put(rf): """Tests updating an object using the API.""" view = WriteableUserAPIView.as_view() user = UserFactory.create(username="******") # Malformed request, only JSON-encoded data is understood request = create_api_request(rf, "put") response = view(request, id=user.id) response_data = json.loads(response.content) assert response.status_code == 400 assert response_data["msg"] == "Invalid JSON data" # Update a field's data new_username = "******" update_data = { "username": new_username, } request = create_api_request(rf, "put", data=update_data) # Requesting unknown resources is a 404 response = view(request, id="11") assert response.status_code == 404 # All fields must be submitted response = view(request, id=user.id) response_data = json.loads(response.content) assert response.status_code == 400 assert "errors" in response_data # Specify missing fields update_data.update({"email": user.email}) request = create_api_request(rf, "put", data=update_data) response = view(request, id=user.id) response_data = json.loads(response.content) # Now all is ok assert response.status_code == 200 assert response_data["username"] == new_username # Email shouldn't have changed assert response_data["email"] == user.email # View with a custom form update_data.update({"password": "******"}) view = WriteableUserSettingsAPIView.as_view() request = create_api_request(rf, "put", data=update_data) response = view(request, id=user.id) response_data = json.loads(response.content) assert response.status_code == 200 assert "password" not in response_data
def test_wrong_password(db_connection, event_loop, test_client): user = event_loop.run_until_complete(UserFactory.create()) response = test_client.post('/auth/login', data={ 'username': user.username, 'password': '******' }) session_cookie = response.cookies.get(settings.SESSION_COOKIE_NAME) assert response.status_code == 401 assert session_cookie is None assert 'username or password are wrong' in response.text
def test_accept_invitation(): portfolio = PortfolioFactory.create() user = UserFactory.create() role = PortfolioRoleFactory.create(user=user, portfolio=portfolio) invite = PortfolioInvitations.create(portfolio.owner, role, user.to_dictionary(), commit=True) assert invite.is_pending accepted_invite = PortfolioInvitations.accept(user, invite.token) assert accepted_invite.is_accepted assert accepted_invite.role.is_active
def test_apiview_search(rf): """Tests filtering through a search query.""" # Note that `UserAPIView` is configured to search in all defined fields, # which are `username` and `full_name` view = UserAPIView.as_view() # Let's create some users to search for UserFactory.create(username='******', full_name='Foo Bar') UserFactory.create(username='******', full_name='Foo Bar') UserFactory.create(username='******', full_name='Foo Bar') # `q=bar` should match 3 users (full names match) request = create_api_request(rf, url='/?q=bar') response = view(request) response_data = json.loads(response.content) assert response.status_code == 200 assert len(response_data['models']) == 3 # `q=baz` should match 1 user request = create_api_request(rf, url='/?q=baz') response = view(request) response_data = json.loads(response.content) assert response.status_code == 200 assert len(response_data['models']) == 1 # Searches are case insensitive; `q=BaZ` should match 1 user request = create_api_request(rf, url='/?q=BaZ') response = view(request) response_data = json.loads(response.content) assert response.status_code == 200 assert len(response_data['models']) == 1
def test_no_root_view_permissions( po_directory, nobody, default, admin, view, no_permission_sets, no_projects, project_foo, project_bar, ): """Tests user-accessible projects when there are no permissions set at the root. """ ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username="******") bar_user = UserFactory.create(username="******") # By setting explicit `view` permissions for `foo_user` in `project_foo`, # only `foo_user` will be able to access that project _require_permission_set(foo_user, project_foo.directory, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), [project_foo.code]) assert items_equal(Project.accessible_by_user(bar_user), []) assert items_equal(Project.accessible_by_user(default), []) assert items_equal(Project.accessible_by_user(nobody), []) # Now let's allow showing `project_bar` to all registered users, but keep # `project_foo` visible only to `foo_user`. _require_permission_set(default, project_bar.directory, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(bar_user), [project_bar.code]) assert items_equal(Project.accessible_by_user(default), [project_bar.code]) assert items_equal(Project.accessible_by_user(nobody), [])
def test_root_view_permissions(po_directory, nobody, default, admin, view, no_projects, no_permission_sets, project_foo, project_bar, root): """Tests user-accessible projects with view permissions at the root.""" ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='******') bar_user = UserFactory.create(username='******') # We'll only give `bar_user` access to all projects server-wide _require_permission_set(bar_user, root, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), []) assert items_equal(Project.accessible_by_user(default), []) assert items_equal(Project.accessible_by_user(nobody), []) # Now we'll also allow `foo_user` access `project_foo` _require_permission_set(foo_user, project_foo.directory, [view]) assert items_equal(Project.accessible_by_user(foo_user), [project_foo.code]) # Let's change server-wide defaults: all registered users have access to # all projects. `foo_user`, albeit having explicit access for # `project_foo`, will be able to access any project because they fall back # and extend with the defaults. _require_permission_set(default, root, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(nobody), []) # Let's give anonymous users access to all projects too _require_permission_set(nobody, root, [view]) assert items_equal(Project.accessible_by_user(nobody), ALL_PROJECTS)
def test_no_update_member_permissions_without_edit_access( client, user_session): portfolio = PortfolioFactory.create() rando = UserFactory.create() rando_pf_role = PortfolioRoleFactory.create( user=rando, portfolio=portfolio, permission_sets=[ PermissionSets.get(PermissionSets.VIEW_PORTFOLIO_ADMIN) ], ) user = UserFactory.create() PortfolioRoleFactory.create( user=user, portfolio=portfolio, permission_sets=[ PermissionSets.get(PermissionSets.VIEW_PORTFOLIO_ADMIN) ], ) user_session(user) form_data = { "members_permissions-0-member_id": rando_pf_role.id, "members_permissions-0-perms_app_mgmt": "edit_portfolio_application_management", "members_permissions-0-perms_funding": "view_portfolio_funding", "members_permissions-0-perms_reporting": "view_portfolio_reports", "members_permissions-0-perms_portfolio_mgmt": "view_portfolio_admin", } response = client.post( url_for("portfolios.edit_members", portfolio_id=portfolio.id), data=form_data, follow_redirects=True, ) assert response.status_code == 404 assert not rando_pf_role.has_permission_set( PermissionSets.EDIT_PORTFOLIO_APPLICATION_MANAGEMENT)
def test_authenticated(db_connection, event_loop, test_client): user = event_loop.run_until_complete(UserFactory.create()) login_response = test_client.post( '/auth/login', data={'username': user.username, 'password': UserFactory.password} ) response = test_client.get( '/admin', cookies=login_response.cookies.get_dict() ) assert response.status_code == 200 assert f'Hi, {user.username}' in response.text
def test_user_does_not_create_log(self): """ `log_superuser_login` should not create a `LogEntry` when users login. """ user = UserFactory.create() self.request.user = user user_logged_in.send( sender=user.__class__, request=self.request, user=user, ) self.assertFalse(LogEntry.objects.count())
def test_update_ppoc_when_not_ppoc(client, user_session): portfolio = PortfolioFactory.create() new_owner = UserFactory.create() user_session(new_owner) response = client.post( url_for("portfolios.update_ppoc", portfolio_id=portfolio.id, _external=True), data={"dod_id": new_owner.dod_id}, follow_redirects=False, ) assert response.status_code == 404
def test_retrieve_filter_list_is_empty_from_another_user(self, test_client, session, logged_user): user_filter = SearchFilterFactory.create(creator=logged_user) another_user = UserFactory.create() session.add(user_filter) session.add(another_user) session.commit() logout(test_client, [302]) login_as(test_client, another_user) res = test_client.get(self.url()) assert res.status_code == 200 assert res.json == []
def test_get_already_logged(db_connection, event_loop, test_client): user = event_loop.run_until_complete(UserFactory.create()) login_response = test_client.post('/auth/login', data={ 'username': user.username, 'password': UserFactory.password }) response = test_client.get('/auth/login', cookies=login_response.cookies.get_dict(), allow_redirects=False) assert response.status_code == 302 assert '<script async defer data-domain="raiseexception.dev"' \ not in response.text
def test_anonymous_pledge(self): # The form must contain the anonymous field. back_url = app_reverse('zipfelchappe_backer_create', app_settings.ROOT_URLS, kwargs={'slug': self.project1.slug}) detail_url = app_reverse('zipfelchappe_project_detail', app_settings.ROOT_URLS, kwargs={'slug': self.project1.slug}) response = self.client.get(back_url) self.assertContains(response, '<input id="id_anonymously"') user1 = UserFactory.create() backer1 = BackerFactory.create(user=user1) p1 = PledgeFactory.create( project=self.project1, amount=8, backer=backer1 ) user2 = UserFactory.create( username='******', email='*****@*****.**', first_name='Bill', last_name='Gates' ) backer = BackerFactory.create(user=user2) p2 = PledgeFactory.create( project=self.project1, amount=11, anonymously=True, backer=backer ) response = self.client.get(detail_url) self.assertFalse(p1.anonymously) self.assertTrue(p2.anonymously) self.assertContains(response, self.project1.title) self.assertContains(response, 'Hans Muster') self.assertContains(response, '19 CHF') self.assertNotContains(response, 'Gates') self.assertNotContains(response, 'Bill') self.assertContains(response, _('Anonymous'))
def test_create_portfolio_failure(client, user_session): user = UserFactory.create() user_session(user) original_portfolio_count = len(PortfoliosQuery.get_all()) response = client.post( url_for("portfolios.create_portfolio"), data={"name": "My project name", "description": "My project description"}, ) assert response.status_code == 400 assert len(PortfoliosQuery.get_all()) == original_portfolio_count
def test_search_by_two_fields(test_client, event_loop, user_fixture): create_user = UserFactory.create(username='******', name='qwerty') event_loop.run_until_complete(create_user) response = test_client.get('/api/users', params={ 'username': user_fixture.username, 'name': user_fixture.name }) data = response.json() assert response.status_code == 200 assert data['data'] == {'users': [user_data(user_fixture)]}
def test_create_invitation(): portfolio = PortfolioFactory.create() user = UserFactory.create() role = PortfolioRoleFactory.create(user=user, portfolio=portfolio) invite = PortfolioInvitations.create(portfolio.owner, role, user.to_dictionary(), commit=True) assert invite.role == role assert invite.inviter == portfolio.owner assert invite.status == InvitationStatus.PENDING assert re.match(r"^[\w\-_]+$", invite.token) assert invite.role.status == PortfolioRoleStatus.PENDING
def test_create_photo(self, client, image): user = UserFactory.create() url = app.url_path_for('create_photo') multipart_form_data = { 'image': ('image.jpg', image), 'user': (None, str(user.id)), 'is_main': (None, 'false') } response = client.post(url, files=multipart_form_data) assert response.status_code == HTTPStatus.CREATED photo = Photo.get() assert photo.id
def test_create_task(): user = UserFactory.create() # Check there are 0 tasks before a new task is added number_tasks = Task.objects.filter(user_id=user.id).count() assert number_tasks == 0 task = TaskFactory.create() # Check there is 1 task after a new task is added number_tasks = Task.objects.filter(user_id=user.id).count() assert number_tasks == 1
async def test_users_watch_without_note(self, guild: Guild): user = UserFactory.create() users = UsersService() await users.watch(guild_xid=guild.xid, user_xid=user.xid) DatabaseSession.expire_all() watches = [w.to_dict() for w in DatabaseSession.query(Watch).all()] assert watches == [{ "guild_xid": guild.xid, "user_xid": user.xid, "note": None }]
def test_delete_filter_from_another_user(self, test_client, session, logged_user): user_filter = SearchFilterFactory.create(creator=logged_user) another_user = UserFactory.create() session.add(user_filter) session.add(another_user) session.commit() logout(test_client, [302]) login_as(test_client, another_user) res = test_client.delete(self.url(user_filter)) assert res.status_code == 404
def test_portfolio_audit_log_only_includes_current_portfolio_events(): owner = UserFactory.create() portfolio = PortfolioFactory.create(owner=owner) other_portfolio = PortfolioFactory.create(owner=owner) # Add some audit events application_1 = ApplicationFactory.create(portfolio=portfolio) application_2 = ApplicationFactory.create(portfolio=other_portfolio) events = AuditLog.get_portfolio_events(portfolio) for event in events: assert event.portfolio_id == portfolio.id assert (not event.portfolio_id == other_portfolio.id or event.resource_id == other_portfolio.id)
def test_post_member(monkeypatch, client, user_session, session): job_mock = Mock() monkeypatch.setattr("atst.jobs.send_mail.delay", job_mock) user = UserFactory.create() application = ApplicationFactory.create(environments=[{ "name": "Naboo" }, { "name": "Endor" }]) (env, env_1) = application.environments user_session(application.portfolio.owner) response = client.post( url_for("applications.create_member", application_id=application.id), data={ "user_data-first_name": user.first_name, "user_data-last_name": user.last_name, "user_data-dod_id": user.dod_id, "user_data-email": user.email, "environment_roles-0-environment_id": env.id, "environment_roles-0-role": "Basic Access", "environment_roles-0-environment_name": env.name, "environment_roles-1-environment_id": env_1.id, "environment_roles-1-role": NO_ACCESS, "environment_roles-1-environment_name": env_1.name, "perms_env_mgmt": True, "perms_team_mgmt": True, "perms_del_env": True, }, ) assert response.status_code == 302 expected_url = url_for( "applications.settings", application_id=application.id, fragment="application-members", _anchor="application-members", _external=True, ) assert response.location == expected_url assert len(application.roles) == 1 environment_roles = application.roles[0].environment_roles assert len(environment_roles) == 1 assert environment_roles[0].environment == env invitation = (session.query(ApplicationInvitation).filter_by( dod_id=user.dod_id).one()) assert invitation.role.application == application assert job_mock.called
def test_has_portfolio_permission(): role_one = PermissionSets.get(PermissionSets.VIEW_PORTFOLIO_FUNDING) role_two = PermissionSets.get(PermissionSets.VIEW_PORTFOLIO_REPORTS) port_role = PortfolioRoleFactory.create( permission_sets=[role_one, role_two]) different_user = UserFactory.create() assert Authorization.has_portfolio_permission( port_role.user, port_role.portfolio, Permissions.VIEW_PORTFOLIO_REPORTS) assert not Authorization.has_portfolio_permission( port_role.user, port_role.portfolio, Permissions.CREATE_TASK_ORDER) assert not Authorization.has_portfolio_permission( different_user, port_role.portfolio, Permissions.VIEW_PORTFOLIO_REPORTS)
def test_user_can_access_decorator_atat_level(set_current_user): ccpo = UserFactory.create_ccpo() rando = UserFactory.create() @user_can_access_decorator(Permissions.VIEW_AUDIT_LOG) def _access_activity_log(*args, **kwargs): return True set_current_user(ccpo) assert _access_activity_log() set_current_user(rando) with pytest.raises(UnauthorizedError): _access_activity_log()