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 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_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 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_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_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_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 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_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_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 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)
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_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_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 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_analysis_and_analysis_pillar_query(self): # Permission checks query = ''' query MyQuery ($projectId: ID!, $analysisId: ID!, $analysisPillarId: ID!) { project(id: $projectId) { analysis (id: $analysisId) { id title } analysisPillar (id: $analysisPillarId) { 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) analysis = AnalysisFactory.create(project=project, team_lead=member_user, end_date=datetime.datetime.now()) analysis_pillar = AnalysisPillarFactory.create(analysis=analysis, assignee=member_user) def _query_check(**kwargs): return self.query_check( query, variables={ 'projectId': project.id, 'analysisId': analysis.id, 'analysisPillarId': analysis_pillar.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']['analysis'], None, content) self.assertEqual(content['data']['project']['analysisPillar'], None, content) self.force_login(member_user) content = _query_check() self.assertNotEqual(content['data']['project']['analysis'], None, content) self.assertNotEqual(content['data']['project']['analysisPillar'], None, content)
def setUp(self): super().setUp() self.project = ProjectFactory.create() # User with role self.non_member_user = UserFactory.create() self.readonly_member_user = UserFactory.create() self.member_user = UserFactory.create() self.another_member_user = UserFactory.create() self.project.add_member(self.readonly_member_user, role=self.project_role_reader_non_confidential) self.project.add_member(self.member_user, role=self.project_role_member) self.project.add_member(self.another_member_user, role=self.project_role_member) self.common_export_attrs = dict( project=self.project, format=Export.Format.DOCX, type=Export.DataType.ENTRIES, export_type=Export.ExportType.REPORT, )
def test_join_private_project(self): user = UserFactory.create() project = ProjectFactory.create(is_private=True) reason = fuzzy.FuzzyText(length=50).fuzz() minput = dict(project=project.id, reason=reason) self.force_login(user) content = self.query_check(self.project_join_mutation, minput=minput, okay=False) self.assertEqual(len(content['data']['joinProject']['errors']), 1, content)
def test_project_join_request_accept(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.ACCEPTED), role='normal') # without login self.query_check( self.projet_accept_reject_mutation, minput=minput, variables={'projectId': project.id, 'joinRequestId': join_request.id}, assert_for_error=True ) notification_qs = Notification.objects.filter( receiver=user, notification_type=Notification.Type.PROJECT_JOIN_RESPONSE ) old_count = notification_qs.count() # 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']['requestedBy']['id'], str(user2.id), content ) self.assertEqual( content['data']['project']['acceptRejectProject']['result']['respondedBy']['id'], str(user.id), content ) self.assertEqual( content['data']['project']['acceptRejectProject']['result']['status'], self.genum(ProjectJoinRequest.Status.ACCEPTED), content ) # make sure memberships is created self.assertIn(user2.id, ProjectMembership.objects.filter(project=project).values_list('member', flat=True)) assert notification_qs.count() > old_count
def test_user_destroy_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.delete(reverse('user-retrieve-update-destroy', kwargs={"user_id": user2.id}), secure=True) self.assertEqual(response.status_code, 404) try: user2_new = User.objects.get(id=user2.id) except User.DoesNotExist: self.fail("DoesNotExist raised")
def test_analysis_framework_list(self): query = ''' query MyQuery { analysisFrameworks (ordering: "id") { page pageSize totalCount results { id title description isPrivate } } } ''' user = UserFactory.create() private_af = AnalysisFrameworkFactory.create(is_private=True) normal_af = AnalysisFrameworkFactory.create() member_af = AnalysisFrameworkFactory.create() member_af.add_member(user) # Without login self.query_check(query, assert_for_error=True) # With login self.force_login(user) content = self.query_check(query) results = content['data']['analysisFrameworks']['results'] self.assertEqual(content['data']['analysisFrameworks']['totalCount'], 2) self.assertIdEqual(results[0]['id'], normal_af.id) self.assertIdEqual(results[1]['id'], member_af.id) self.assertNotIn(str(private_af.id), [d['id'] for d in results]) # Can't see private project. project = ProjectFactory.create(analysis_framework=private_af) # It shouldn't list private AF after adding to a project. content = self.query_check(query) results = content['data']['analysisFrameworks']['results'] self.assertEqual(content['data']['analysisFrameworks']['totalCount'], 2) self.assertNotIn(str(private_af.id), [d['id'] for d in results]) # Can't see private project. project.add_member(user) # It should list private AF after user is member of the project. content = self.query_check(query) results = content['data']['analysisFrameworks']['results'] self.assertEqual(content['data']['analysisFrameworks']['totalCount'], 3) self.assertIn(str(private_af.id), [d['id'] for d in results]) # Can see private project now.
def test_export_path_generation(self): MOCK_TIME_STR = '20211205' MOCK_RANDOM_STRING = 'random-string' user = UserFactory.create() project = ProjectFactory.create() common_args = { 'type': Export.DataType.ENTRIES, 'exported_by': user, 'project': project, } with \ patch('export.tasks.get_random_string') as get_random_string_mock, \ patch('export.models.timezone') as timezone_mock: get_random_string_mock.return_value = MOCK_RANDOM_STRING timezone_mock.now.return_value.strftime.return_value = MOCK_TIME_STR for export, expected_title, expected_filename, _type in [ ( ExportFactory( title='', format=Export.Format.DOCX, export_type=Export.ExportType.REPORT, **common_args ), f'{MOCK_TIME_STR} DEEP Entries General Export', f'{MOCK_TIME_STR} DEEP Entries General Export.docx', 'without-title', ), ( ExportFactory( title='test 123', format=Export.Format.PDF, export_type=Export.ExportType.REPORT, **common_args, ), 'test 123', 'test 123.pdf', 'with-title-01', ), ( ExportFactory( title='test 321', format=Export.Format.JSON, export_type=Export.ExportType.JSON, is_preview=True, **common_args, ), 'test 321', '(Preview) test 321.json', 'with-title-02', ), ]: export.save() # generated_title = Export.generate_title(export.type, export.format) # export.title = export.title or generated_title # This is automatically done on export save (mocking here) generated_filename = get_export_filename(export) self.assertEqual(export.title, expected_title, _type) self.assertEqual(generated_filename, f'{MOCK_RANDOM_STRING}/{expected_filename}', _type)
def setUp(self): super().setUp() self.qa_member_user = UserFactory.create() self.member_user = UserFactory.create() self.readonly_member_user = UserFactory.create() self.non_member_user = UserFactory.create() self.af = AnalysisFrameworkFactory.create() self.project = ProjectFactory.create(analysis_framework=self.af) self.lead = LeadFactory.create(project=self.project) self.entry = EntryFactory.create(lead=self.lead) # Add member to project self.project.add_member(self.readonly_member_user, role=self.project_role_reader_non_confidential) self.project.add_member(self.member_user, role=self.project_role_member) self.project.add_member(self.qa_member_user, role=self.project_role_member, badges=[ProjectMembership.BadgeType.QA])