def setUp(self): self.user = UserFactory(username='******', password='******') self.other_user = UserFactory(username='******', password='******') self.question = QuestionFactory(asked_by=self.other_user, asked_to=self.user, text=self.LOREM_IPSUM) self.answer = AnswerFactory(question=self.question)
def test_user_update_authenticated_as_superuser(self): view = UserRetrieveUpdateDestroyView.as_view() user1 = UserFactory.create_superuser(username='******', email="*****@*****.**", password="******") user2 = UserFactory.create(email="*****@*****.**") self.client.force_authenticate(user=user1) response = self.client.put(reverse('user-retrieve-update-destroy', kwargs={"user_id": user2.id}), { 'username': user2.username, "id": user2.id, "name": "test2", "birth_date": user2.birth_date, "email": user2.email, "password": user2.password, }, format='json', secure=True) self.assertEqual(response.status_code, 200) user_new = User.objects.get(id=user2.id) self.assertEqual(user_new.name, "test2")
def test_project_join_request_reject(self): user = UserFactory.create() user2 = UserFactory.create() project = ProjectFactory.create() project.add_member(user, role=self.project_role_admin) join_request = ProjectJoinRequestFactory.create(requested_by=user2, project=project, role=ProjectRole.get_default_role(), status=ProjectJoinRequest.Status.PENDING) minput = dict(status=self.genum(ProjectJoinRequest.Status.REJECTED)) # without login self.query_check( self.projet_accept_reject_mutation, minput=minput, variables={'projectId': project.id, 'joinRequestId': join_request.id}, assert_for_error=True ) # with login self.force_login(user) content = self.query_check(self.projet_accept_reject_mutation, minput=minput, variables={'projectId': project.id, 'joinRequestId': join_request.id}) self.assertEqual( content['data']['project']['acceptRejectProject']['result']['status'], self.genum(ProjectJoinRequest.Status.REJECTED), content )
def test_lead_group_query(self): query = ''' query MyQuery ($id: ID!) { project(id: $id) { leadGroups(ordering: "id") { results { id title project { id } leadCounts } totalCount } } } ''' project = ProjectFactory.create() project2 = ProjectFactory.create() member_user = UserFactory.create() non_member_user = UserFactory.create() project.add_member(member_user) project2.add_member(member_user) lead_group1 = LeadGroupFactory.create(project=project) lead_group2 = LeadGroupFactory.create(project=project) lead_group3 = LeadGroupFactory.create(project=project2) LeadFactory.create_batch(4, project=project, lead_group=lead_group1) LeadFactory.create_batch(2, project=project, lead_group=lead_group2) LeadFactory.create_batch(2, project=project, lead_group=lead_group3) self.force_login(member_user) content = self.query_check(query, variables={'id': project.id}) self.assertEqual( content['data']['project']['leadGroups']['totalCount'], 2) self.assertEqual( set(result['id'] for result in content['data']['project'] ['leadGroups']['results']), set([str(lead_group1.id), str(lead_group2.id)])) self.assertListIds(content['data']['project']['leadGroups']['results'], [lead_group1, lead_group2], content) # login with non_member_user self.force_login(non_member_user) content = self.query_check(query, variables={'id': project.id}) self.assertEqual( content['data']['project']['leadGroups']['totalCount'], 0) # with different project self.force_login(member_user) content = self.query_check(query, variables={'id': project2.id}) self.assertEqual( content['data']['project']['leadGroups']['totalCount'], 1) self.assertEqual( content['data']['project']['leadGroups']['results'][0]['id'], str(lead_group3.id)) self.assertEqual( content['data']['project']['leadGroups']['results'][0] ['leadCounts'], 2)
def setUp(self): super().setUp() self.project = ProjectFactory.create() self.user = UserFactory.create() self.another_user = UserFactory.create() self.project.add_member(self.user) self.uc1, self.uc2 = UnifiedConnectorFactory.create_batch( 2, project=self.project) self.fake_lead = ConnectorLeadFactory.create() # NOTE: Some other as noise, making sure they don't conflict with others another_project_with_access = ProjectFactory.create() another_project_without_access = ProjectFactory.create() uc_wc = UnifiedConnectorFactory.create( project=another_project_with_access) uc_wtc = UnifiedConnectorFactory.create( project=another_project_without_access) uc_wc_source = ConnectorSourceFactory.create( unified_connector=uc_wc, source=ConnectorSource.Source.RELIEF_WEB) uc_wtc_source = ConnectorSourceFactory.create( unified_connector=uc_wtc, source=ConnectorSource.Source.RELIEF_WEB) ConnectorSourceLeadFactory.create_batch(2, source=uc_wc_source, connector_lead=self.fake_lead) ConnectorSourceLeadFactory.create_batch(2, source=uc_wtc_source, connector_lead=self.fake_lead)
def test_entry_review_comment_basic_api(self): user1 = UserFactory.create() user2 = UserFactory.create() user3 = UserFactory.create() user4 = UserFactory.create() self.project.add_member(user1, role=self.project_role_member, badges=[ProjectMembership.BadgeType.QA]) self.project.add_member(user2, role=self.project_role_member, badges=[ProjectMembership.BadgeType.QA]) self.project.add_member(user3, role=self.project_role_member, badges=[ProjectMembership.BadgeType.QA]) self.force_login(user1) data = { 'entry': self.entry.pk, 'text': 'This is a test comment', 'commentType': self.genum(EntryReviewComment.CommentType.COMMENT), 'mentionedUsers': [user1.pk, user2.pk, user3.pk], } comment_pk = self._query_check( data, okay=True )['data']['project']['entryReviewCommentCreate']['result']['id'] assert self.entry.entryreviewcomment_set.count() == 1 # Update only allowd by comment creater data['text'] = 'This is updated text comment' content = self._query_check( data, review_comment_id=comment_pk, okay=True)['data']['project']['entryReviewCommentUpdate'] self.assertEqual(content['result']['textHistory'][0]['text'], data['text']) self.assertEqual(content['result']['text'], data['text']) self.force_login(user2) self._query_check(data, review_comment_id=comment_pk, okay=False) self.force_login(user2) data = { 'entry': self.entry.pk, 'text': 'This is a test comment', 'commentType': self.genum(EntryReviewComment.CommentType.COMMENT), 'mentionedUsers': [user1.pk, user2.pk, user3.pk], } self._query_check(data, okay=True) assert self.entry.entryreviewcomment_set.count() == 2 self.force_login(user4) data = { 'entry': self.entry.pk, 'text': 'This is a test comment', 'commentType': self.genum(EntryReviewComment.CommentType.COMMENT), 'mentionedUsers': [user1.pk, user2.pk, user3.pk], } self._query_check(data, assert_for_error=True)
def setUp(self): super().setUp() self.project = ProjectFactory.create() self.member_user = UserFactory.create() self.non_member_user = UserFactory.create() self.readonly_member_user = UserFactory.create() self.project.add_member(self.member_user) self.project.add_member(self.readonly_member_user, role=self.project_role_reader_non_confidential)
def test_analysis_pillars_entries_query(self): query = ''' query MyQuery ($projectId: ID!, $analysisPillarId: ID!) { project(id: $projectId) { analysisPillar (id: $analysisPillarId) { id title entries { totalCount results { id } } } } } ''' now = datetime.datetime.now() member_user = UserFactory.create() non_member_user = UserFactory.create() af = AnalysisFrameworkFactory.create() project = ProjectFactory.create(analysis_framework=af) another_project = ProjectFactory.create(analysis_framework=af) project.add_member(member_user, role=self.project_role_reader_non_confidential) analysis = AnalysisFactory.create(project=project, team_lead=member_user, end_date=now) analysis_pillar = AnalysisPillarFactory.create(analysis=analysis, assignee=member_user) def _query_check(**kwargs): return self.query_check( query, variables={'projectId': project.id, 'analysisPillarId': analysis_pillar.pk}, **kwargs, ) # -- Without login _query_check(assert_for_error=True) # --- With login self.force_login(non_member_user) content = _query_check() self.assertEqual(content['data']['project']['analysisPillar'], None, content) self.force_login(member_user) content = _query_check() self.assertEqual(content['data']['project']['analysisPillar']['entries']['totalCount'], 0, content) self.assertEqual(len(content['data']['project']['analysisPillar']['entries']['results']), 0, content) # Let's add some entries lead_published_on = now - datetime.timedelta(days=1) # To fit within analysis end_date EntryFactory.create_batch(10, lead=LeadFactory.create(project=project, published_on=lead_published_on)) EntryFactory.create_batch(8, lead=LeadFactory.create(project=another_project, published_on=lead_published_on)) content = _query_check() self.assertEqual(content['data']['project']['analysisPillar']['entries']['totalCount'], 10, content) self.assertEqual(len(content['data']['project']['analysisPillar']['entries']['results']), 10, content)
def test_user_group_query(self): # Try with random user query = ''' query Query($id: ID!) { userGroup(id: $id) { id title modifiedAt globalCrisisMonitoring description customProjectFields createdAt clientId currentUserRole membershipsCount memberships { role member { id displayName } } createdBy { id displayName } modifiedBy { id displayName } } } ''' another_user = UserFactory.create() ug_without_membership = UserGroupFactory.create(members=[another_user]) # Without login, throw error self.query_check(query, assert_for_error=True, variables={'id': str(ug_without_membership.pk)}) # -- Create new user and login -- user = UserFactory.create() self.force_login(user) # with login, non-member usergroup will give zero members but membershipsCount 1 content = self.query_check(query, variables={'id': str(ug_without_membership.pk)}) self.assertEqual(content['data']['userGroup']['membershipsCount'], 1, content) self.assertEqual(len(content['data']['userGroup']['memberships']), 0, content) # -- Create new user groups w/wo user as member # with login, non-member usergroup will give real members ug_with_membership = UserGroupFactory.create(members=[user, another_user]) content = self.query_check(query, variables={'id': str(ug_with_membership.pk)}) self.assertEqual(content['data']['userGroup']['membershipsCount'], 2, content) self.assertEqual(len(content['data']['userGroup']['memberships']), 2, content) self.assertEqual(content['data']['userGroup']['currentUserRole'], self.genum(GroupMembership.Role.NORMAL), content)
def test_user_view_authenticated_as_user_other(self): view = UserRetrieveUpdateDestroyView.as_view() user1 = UserFactory.create(email='*****@*****.**') user2 = UserFactory.create(email='*****@*****.**') self.client.force_authenticate(user=user1) response = self.client.get(reverse('user-retrieve-update-destroy', kwargs={"user_id": user2.id}), secure=True) self.assertEqual(response.status_code, 404)
def test_get_twibbons_success(self): user1 = UserFactory(email="[email protected]") user2 = UserFactory(email="[email protected]") campaign = CampaignFactory(user=user1) TwibbonFactory(campaign=campaign, user=user2, caption="caption") response = self.client.get(reverse( 'twibbon-list-create', kwargs={'campaign_url': campaign.campaign_url}), secure=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['results'][0]['caption'], 'caption') self.assertEqual(response.data['results'][0]['user'], user2.id)
def test_user_list_view_authenticated_as_superuser(self): user1 = UserFactory.create(email='*****@*****.**') user2 = UserFactory.create_superuser(username='******', email='*****@*****.**', password='******') view = UserListCreateView.as_view() self.client.force_authenticate(user=user2) response = self.client.get(reverse('user-list-create'), secure=True) self.assertEqual(len(response.data['results']), 2)
def test_analyses_and_analysis_pillars_query(self): # Permission checks query = ''' query MyQuery ($projectId: ID!) { project(id: $projectId) { analyses { totalCount results { id title } } analysisPillars { totalCount results { id title } } } } ''' member_user = UserFactory.create() non_member_user = UserFactory.create() project = ProjectFactory.create() project.add_member(member_user, role=self.project_role_reader_non_confidential) analyses = AnalysisFactory.create_batch(2, project=project, team_lead=member_user, end_date=datetime.datetime.now()) for analysis in analyses: AnalysisPillarFactory.create_batch(5, analysis=analysis, assignee=member_user) def _query_check(**kwargs): return self.query_check(query, variables={'projectId': project.id}, **kwargs) # -- Without login _query_check(assert_for_error=True) # --- With login self.force_login(non_member_user) content = _query_check() self.assertEqual(content['data']['project']['analyses']['totalCount'], 0, content) self.assertEqual(len(content['data']['project']['analyses']['results']), 0, content) self.assertEqual(content['data']['project']['analysisPillars']['totalCount'], 0, content) self.assertEqual(len(content['data']['project']['analysisPillars']['results']), 0, content) self.force_login(member_user) content = _query_check() self.assertEqual(content['data']['project']['analyses']['totalCount'], 2, content) self.assertEqual(len(content['data']['project']['analyses']['results']), 2, content) self.assertEqual(content['data']['project']['analysisPillars']['totalCount'], 10, content) self.assertEqual(len(content['data']['project']['analysisPillars']['results']), 10, content)
def test_exports_query(self): query = ''' query MyQuery ($id: ID!) { project(id: $id) { exports { page pageSize totalCount results { id title } } } } ''' project = ProjectFactory.create() project2 = ProjectFactory.create() user = UserFactory.create() user2 = UserFactory.create() project.add_member(user, role=self.project_role_reader_non_confidential) project2.add_member(user2, role=self.project_role_reader_non_confidential) ExportFactory.create_batch(6, project=project, exported_by=user) ExportFactory.create_batch(8, project=project2, exported_by=user2) def _query_check(**kwargs): return self.query_check(query, variables={'id': project.id}, **kwargs) # --- Without login _query_check(assert_for_error=True) # --- With login self.force_login(user) content = _query_check() self.assertEqual(content['data']['project']['exports']['totalCount'], 6, content) self.assertEqual(len(content['data']['project']['exports']['results']), 6, content) # --- With login by user whose has not exported the export self.force_login(user2) content = _query_check() self.assertEqual(content['data']['project']['exports']['totalCount'], 0, content) self.assertEqual(len(content['data']['project']['exports']['results']), 0, content)
def test_export_query(self): """ Test export for project """ query = ''' query MyQuery ($projectId: ID! $exportId: ID!) { project(id: $projectId) { export (id: $exportId) { id title } } } ''' project = ProjectFactory.create() project2 = ProjectFactory.create() user = UserFactory.create() user2 = UserFactory.create() project.add_member(user, role=self.project_role_reader_non_confidential) project2.add_member(user2, role=self.project_role_reader_non_confidential) export = ExportFactory.create(project=project, exported_by=user) other_export = ExportFactory.create(project=project2, exported_by=user2) def _query_check(export, **kwargs): return self.query_check(query, variables={ 'projectId': project.id, 'exportId': export.id }, **kwargs) # -- Without login _query_check(export, assert_for_error=True) # --- With login self.force_login(user) content = _query_check(export) self.assertNotEqual(content['data']['project']['export'], None, content) self.assertEqual(content['data']['project']['export']['id'], str(export.id)) self.force_login(user) content = _query_check(other_export) self.assertEqual(content['data']['project']['export'], None, content)
def test_put_campaign_user_forbidden(self): user1 = UserFactory(email="*****@*****.**") user2 = UserFactory(email="*****@*****.**") campaign = CampaignFactory(name="campaign1", user=user1) self.client.force_authenticate(user=user2) response = self.client.put( reverse('campaign-retrieve-update-destroy', kwargs={'campaign_url': campaign.campaign_url}), { 'name': 'Nama', 'campaign_url': 'url', 'twibbon_img': open( get_sample_image_file_path('1x1.png'), 'rb') }, secure=True) self.assertEqual(response.status_code, 403)
def test_notification_query(self): query = ''' query MyQuery ($id: ID!) { notification(id: $id) { id status project { id title } notificationType timestamp notificationTypeDisplay statusDisplay data } } ''' project = ProjectFactory.create() user = UserFactory.create() another_user = UserFactory.create() notification_meta = dict( notification_type=Notification.Type.PROJECT_JOIN_REQUEST, status=Notification.Status.UNSEEN, ) our_notification = NotificationFactory.create(project=project, receiver=user, **notification_meta) other_notification = NotificationFactory.create(project=project, receiver=another_user, **notification_meta) def _query_check(notification, **kwargs): return self.query_check(query, variables={'id': notification.pk}, **kwargs) # -- Without login _query_check(our_notification, assert_for_error=True) # --- With login self.force_login(user) content = _query_check(our_notification) self.assertNotEqual(content['data']['notification'], None, content) content = _query_check(other_notification) self.assertEqual(content['data']['notification'], None, content)
def test_create_superuser_is_not_superuser(self): with self.assertRaises(ValueError): user = UserFactory.create_superuser(username='******', email='*****@*****.**', password='******', is_superuser=False) self.assertEqual(len(User.objects.all()), 0)
def test_user_update_invalid_data(self): view = UserRetrieveUpdateDestroyView.as_view() user = UserFactory.create_superuser(username='******', name='test', email='*****@*****.**', password='******') self.client.force_authenticate(user=user) response = self.client.put(reverse('user-retrieve-update-destroy', kwargs={"user_id": user.id}), { 'username': user.username, "id": user.id, "name": None, "birth_date": user.birth_date, "email": user.email, "password": user.password, }, format='json', secure=True) self.assertEqual(response.status_code, 400) user_new = User.objects.get(id=user.id) self.assertEqual(user_new.name, "test")
def test_project_allowed_permissions(self): query = ''' query MyQuery { projects { results { id allowedPermissions } } } ''' project1, project2 = ProjectFactory.create_batch(2) user = UserFactory.create() project1.add_member(user, badges=[]) project2.add_member(user, badges=[ProjectMembership.BadgeType.QA]) self.force_login(user) content_projects = self.query_check( query)['data']['projects']['results'] QA_PERMISSION = self.genum(PP.Permission.CAN_QUALITY_CONTROL) content_projects_permissions = { int(pdata['id']): pdata['allowedPermissions'] for pdata in content_projects } self.assertEqual(len(content_projects), 2, content_projects) self.assertNotIn(QA_PERMISSION, content_projects_permissions[project1.pk], content_projects) self.assertIn(QA_PERMISSION, content_projects_permissions[project2.pk], content_projects)
def test_project_query_has_assesment_af(self): query = ''' query MyQuery { projects(ordering: "id") { results { id hasAnalysisFramework hasAssessmentTemplate } } } ''' user = UserFactory.create() analysis_framework = AnalysisFrameworkFactory.create() assessment_template = AssessmentTemplateFactory.create() project1 = ProjectFactory.create( analysis_framework=analysis_framework, assessment_template=assessment_template) project2 = ProjectFactory.create( analysis_framework=analysis_framework, ) project3 = ProjectFactory.create( assessment_template=assessment_template) self.force_login(user) projects = self.query_check(query)['data']['projects']['results'] for index, (_id, has_af, has_ary_template) in enumerate([ (project1.pk, True, True), (project2.pk, True, False), (project3.pk, False, True), ]): self.assertIdEqual(projects[index]['id'], _id, projects) self.assertEqual(projects[index]['hasAnalysisFramework'], has_af, projects) self.assertEqual(projects[index]['hasAssessmentTemplate'], has_ary_template, projects)
def test_user_by_natural_key_not_found(self): email_user = '******' email_test = '*****@*****.**' user = UserFactory.create(email=email_user) with self.assertRaises(User.DoesNotExist): User.objects.get_by_natural_key(email_test)
def test_me_allowed_features(self): query = ''' query MyQuery { me { accessibleFeatures { title key featureType } } } ''' feature1 = FeatureFactory.create(key=Feature.FeatureKey.ANALYSIS) feature2 = FeatureFactory.create( key=Feature.FeatureKey.POLYGON_SUPPORT_GEO) FeatureFactory.create() user = UserFactory.create() # --- Login self.force_login(user) # --- Without any features content = self.query_check(query) self.assertEqual(len(content['data']['me']['accessibleFeatures']), 0, content) # --- With a project membership + But no lastActiveProject set in profile feature1.users.add(user) feature2.users.add(user) content = self.query_check(query) self.assertEqual(len(content['data']['me']['accessibleFeatures']), 2, content) self.assertEqual(content['data']['me']['accessibleFeatures'][0]['key'], self.genum(feature1.key), content) self.assertEqual(content['data']['me']['accessibleFeatures'][1]['key'], self.genum(feature2.key), content)
def test_password_change(self, send_password_changed_notification_mock): query = ''' mutation Mutation($input: PasswordChangeInputType!) { changePassword(data: $input) { ok errors } } ''' # input without email minput = dict(oldPassword='', newPassword='******') # Without authentication -- content = self.query_check(query, minput=minput, assert_for_error=True) # With authentication user = UserFactory.create() self.force_login(user) # With invalid old password -- content = self.query_check(query, minput=minput, okay=False) self.assertEqual(len(content['data']['changePassword']['errors']), 1, content) # With valid password -- minput['oldPassword'] = user.password_text with self.captureOnCommitCallbacks(execute=True): content = self.query_check(query, minput=minput, okay=True) # Make sure password reset message is send send_password_changed_notification_mock.assert_called_once() send_password_changed_notification_mock.assert_called_once_with( user_id=user.pk, client_ip='127.0.0.1', device_type=None, )
def setUp(self) -> None: self.user = UserFactory() self.keys = ['id', 'title', 'slug'] self.headers = { 'HTTP_AUTHORIZATION': 'Bearer ' + AccessTokenFactory(user=self.user).token, }
def test_organization_query(self): query = ''' query MyQuery { organizations(search: "Organization-", ordering: DESC_TITLE) { results { id title } totalCount } } ''' Organization.objects.all().delete() org1 = OrganizationFactory.create(title='org-1') org2 = OrganizationFactory.create(title='org-2') org3 = OrganizationFactory.create(title='org-3') user = UserFactory.create() # Without authentication ----- self.query_check(query, assert_for_error=True) self.force_login(user) content = self.query_check(query) self.assertEqual(len(content['data']['organizations']['results']), 3, content) self.assertEqual( [ item['title'] for item in content['data']['organizations']['results'] ], [org.title for org in [org3, org2, org1]], content, ) self.assertEqual(content['data']['organizations']['totalCount'], 3, content)
def test_get_user(self): user = UserFactory() response = self.client.get( reverse('user', args=[user.id]), HTTP_AUTHORIZATION=f"Bearer {user.access}", ) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_logout(self): query = ''' query Query { me { id email } } ''' logout_mutation = ''' mutation Mutation { logout { ok } } ''' user = UserFactory.create() # # Without Login session self.query_check(query, assert_for_error=True) # # Login self.force_login(user) # Query Me (Success) content = self.query_check(query) self.assertEqual(content['data']['me']['id'], str(user.id), content) self.assertEqual(content['data']['me']['email'], user.email, content) # # Logout self.query_check(logout_mutation, okay=True) # Query Me (with error again) self.query_check(query, assert_for_error=True)
def test_organization_type_query(self): query = ''' query OrganizationType { organizationTypes { results { id title description shortName } totalCount } } ''' OrganizationType.objects.all().delete() OrganizationTypeFactory.create_batch(3) user = UserFactory.create() # Without authentication ----- self.query_check(query, assert_for_error=True) self.force_login(user) content = self.query_check(query) self.assertEqual(len(content['data']['organizationTypes']['results']), 3, content) self.assertEqual(content['data']['organizationTypes']['totalCount'], 3, content)
def setUp(self) -> None: super().setUp() self.user = UserFactory.create() self.upload_mutation = """ mutation Mutation($data: AnalysisFrameworkInputType!) { analysisFrameworkCreate(data: $data) { ok errors result { id title previewImage { name url } } } } """ self.retrieve_af_query = """ query RetrieveAFQuery { analysisFramework(id: %s) { id previewImage { name url } } } """ self.variables = {"data": {"title": 'test', "previewImage": None}} self.force_login(self.user)