Exemplo n.º 1
0
    def test_lead_delete_validation(self):
        """
        This test checks create lead validations
        """
        query = '''
            mutation MyMutation ($projectId: ID! $leadId: ID!) {
              project(id: $projectId) {
                leadDelete(id: $leadId) {
                  ok
                  errors
                  result {
                    id
                    title
                    url
                  }
                }
              }
            }
        '''

        non_access_lead = LeadFactory.create()
        lead = LeadFactory.create(project=self.project)

        def _query_check(lead, will_delete=False, **kwargs):
            result = self.query_check(
                query,
                mnested=['project'],
                variables={
                    'projectId': self.project.id,
                    'leadId': lead.id
                },
                **kwargs,
            )
            if will_delete:
                with self.assertRaises(Lead.DoesNotExist):
                    lead.refresh_from_db()
            else:
                lead.refresh_from_db()
            return result

        # Error without login
        _query_check(non_access_lead, assert_for_error=True)

        # --- login
        self.force_login(self.member_user)
        # Error with login (if non-member project)
        _query_check(non_access_lead, okay=False)
        # ------- login as readonly_member
        self.force_login(self.readonly_member_user)
        # No Success with normal lead (with project membership)
        _query_check(lead, assert_for_error=True)
        # ------- login as normal member
        self.force_login(self.member_user)
        # Success with normal lead (with project membership)
        result = _query_check(
            lead, will_delete=True,
            okay=True)['data']['project']['leadDelete']['result']
        self.assertEqual(result['title'], lead.title, result)
Exemplo n.º 2
0
    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)
Exemplo n.º 3
0
    def test_lead_bulk(self):
        query = '''
        mutation MyMutation ($projectId: ID! $input: [BulkLeadInputType!]) {
          project(id: $projectId) {
            leadBulk(items: $input) {
              errors
              result {
                id
                title
                clientId
              }
            }
          }
        }
        '''
        project = ProjectFactory.create()
        # User with role
        user = UserFactory.create()
        project.add_member(user, role=self.project_role_member)
        lead1 = LeadFactory.create(project=project)
        lead2 = LeadFactory.create(project=project,
                                   source_type=Lead.SourceType.WEBSITE,
                                   url='https://example.com/path')

        lead_count = Lead.objects.count()
        minput = [
            dict(title='Lead title 1', clientId='new-lead-1'),
            dict(title='Lead title 2', clientId='new-lead-2'),
            dict(
                title='Lead title 4',
                sourceType=self.genum(Lead.SourceType.WEBSITE),
                url='https://example.com/path',
                clientId='new-lead-3',
            ),
            dict(id=str(lead1.pk), title='Lead title 3'),
            dict(id=str(lead2.pk), title='Lead title 4'),
        ]

        def _query_check(**kwargs):
            return self.query_check(query,
                                    minput=minput,
                                    variables={'projectId': project.pk},
                                    **kwargs)

        # --- without login
        _query_check(assert_for_error=True)

        # --- with login
        self.force_login(user)
        response = _query_check()['data']['project']['leadBulk']
        self.assertMatchSnapshot(response, 'success')
        self.assertEqual(lead_count + 2, Lead.objects.count())
Exemplo n.º 4
0
    def test_entry_dropped_excerpt_migrations(self):
        def _get_excerpt_snapshot():
            return list(Entry.objects.order_by('id').values_list('excerpt', 'dropped_excerpt', 'excerpt_modified'))

        migration_file = importlib.import_module('entry.migrations.0036_entry_excerpt_modified')

        af = AnalysisFrameworkFactory.create()
        project = ProjectFactory.create(analysis_framework=af)
        lead = LeadFactory.create(project=project)

        # Create entry before data migrate
        EntryFactory.create(lead=lead, excerpt='', dropped_excerpt='')
        EntryFactory.create(lead=lead, excerpt='sample-1', dropped_excerpt='')
        EntryFactory.create(lead=lead, excerpt='sample-2', dropped_excerpt='sample-2-updated')
        EntryFactory.create(lead=lead, excerpt='sample-3', dropped_excerpt='sample-3')
        old_excerpt_snaphost = _get_excerpt_snapshot()

        # Apply the migration logic
        migration_file._update_entry_excerpt(Entry)
        new_excerpt_snaphost = _get_excerpt_snapshot()

        assert Entry.objects.count() == 4
        assert Entry.objects.filter(dropped_excerpt='').count() == 1
        assert Entry.objects.filter(excerpt_modified=True).count() == 1
        assert Entry.objects.filter(dropped_excerpt=models.F('excerpt')).count() == 3
        assert Entry.objects.exclude(dropped_excerpt=models.F('excerpt')).count() == 1

        assert new_excerpt_snaphost != old_excerpt_snaphost
        assert new_excerpt_snaphost == [
            ('', '', False),
            ('sample-1', 'sample-1', False),
            ('sample-2', 'sample-2-updated', True),
            ('sample-3', 'sample-3', False),
        ]
Exemplo n.º 5
0
    def test_leads_status(self):
        query = '''
            query MyQuery ($id: ID!) {
              project(id: $id) {
                leads(ordering: ASC_ID) {
                  results {
                    id
                    title
                    status
                  }
                }
              }
            }
        '''
        user = UserFactory.create()
        project = ProjectFactory.create(
            analysis_framework=AnalysisFrameworkFactory.create())
        project.add_member(user)
        lead1, _ = LeadFactory.create_batch(2, project=project)

        def _query_check():
            return self.query_check(query, variables={'id': project.id})

        self.force_login(user)
        content = _query_check()['data']['project']['leads']['results']
        self.assertEqual(len(content), 2, content)
        self.assertEqual(
            set([lead['status'] for lead in content]),
            {self.genum(Lead.Status.NOT_TAGGED)},
            content,
        )
        # Add entry to lead1
        entry1 = EntryFactory.create(lead=lead1)
        content = _query_check()['data']['project']['leads']['results']
        self.assertEqual(len(content), 2, content)
        self.assertEqual(content[0]['status'],
                         self.genum(Lead.Status.IN_PROGRESS), content)
        self.assertEqual(content[1]['status'],
                         self.genum(Lead.Status.NOT_TAGGED), content)
        # Update lead1 status to TAGGED
        lead1.status = Lead.Status.TAGGED
        lead1.save(update_fields=['status'])
        content = _query_check()['data']['project']['leads']['results']
        self.assertEqual(len(content), 2, content)
        self.assertEqual(content[0]['status'], self.genum(Lead.Status.TAGGED),
                         content)
        self.assertEqual(content[1]['status'],
                         self.genum(Lead.Status.NOT_TAGGED), content)
        # Now update entry1
        entry1.save()
        content = _query_check()['data']['project']['leads']['results']
        self.assertEqual(len(content), 2, content)
        self.assertEqual(content[0]['status'],
                         self.genum(Lead.Status.IN_PROGRESS), content)
        self.assertEqual(content[1]['status'],
                         self.genum(Lead.Status.NOT_TAGGED), content)
Exemplo n.º 6
0
    def test_lead_entries_query(self):
        # Includes permissions checks
        query = '''
            query MyQuery ($projectId: ID! $leadId: ID!) {
              project(id: $projectId) {
                lead(id: $leadId) {
                  entries {
                    id
                    order
                    entryType
                    excerpt
                    attributes {
                      widgetType
                      widget
                      data
                      clientId
                      widgetVersion
                      id
                    }
                    clientId
                    droppedExcerpt
                    highlightHidden
                    informationDate
                    image {
                      id
                      metadata
                      mimeType
                      title
                      file {
                        url
                        name
                      }
                    }
                    controlled
                  }
                }
              }
            }
        '''

        lead = LeadFactory.create(project=self.project)
        entry = EntryFactory.create(project=self.project, analysis_framework=self.af, lead=lead)

        def _query_check(**kwargs):
            return self.query_check(query, variables={'projectId': self.project.pk, 'leadId': lead.id}, **kwargs)

        # Without login
        _query_check(assert_for_error=True)
        # With login
        self.force_login(self.user)
        content = _query_check()
        results = content['data']['project']['lead']['entries']
        self.assertEqual(len(content['data']['project']['lead']['entries']), 1, content)
        self.assertIdEqual(results[0]['id'], entry.pk, results)
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
 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])
Exemplo n.º 9
0
    def test_project_stat_recent(self):
        query = '''
              query MyQuery {
                recentProjects {
                  id
                  status
                  title
                  isPrivate
                  description
                  currentUserRole
                }
              }
          '''

        user = UserFactory.create()
        analysis_framework = AnalysisFrameworkFactory.create()
        public_project1, public_project2, public_project3, public_project4 = ProjectFactory.create_batch(
            4)
        public_project1.add_member(user)
        public_project2.add_member(user)
        public_project3.add_member(user)

        lead1 = LeadFactory.create(project=public_project1, created_by=user)
        LeadFactory.create(project=public_project2, created_by=user)
        EntryFactory.create(lead=lead1,
                            controlled=False,
                            created_by=user,
                            project=public_project1,
                            analysis_framework=analysis_framework)
        LeadFactory.create(project=public_project3, created_by=user)
        LeadFactory.create(project=public_project4, created_by=user)
        # -- Without login
        self.query_check(query, assert_for_error=True)

        # -- With login
        self.force_login(user)

        content = self.query_check(query)
        self.assertEqual(len(content['data']['recentProjects']), 3, content)
        self.assertEqual(content['data']['recentProjects'][0]['id'],
                         str(public_project3.pk), content)
        self.assertEqual(content['data']['recentProjects'][1]['id'],
                         str(public_project1.pk), content)
        self.assertEqual(content['data']['recentProjects'][2]['id'],
                         str(public_project2.pk), content)
Exemplo n.º 10
0
 def setUp(self):
     super().setUp()
     self.af = AnalysisFrameworkFactory.create()
     self.project = ProjectFactory.create(analysis_framework=self.af)
     # User with role
     self.non_member_user = UserFactory.create()
     self.readonly_member_user = UserFactory.create()
     self.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.lead = LeadFactory.create(project=self.project)
     self.widget1 = WidgetFactory.create(analysis_framework=self.af)
     self.widget2 = WidgetFactory.create(analysis_framework=self.af)
     self.widget3 = WidgetFactory.create(analysis_framework=self.af)
     # Files
     self.other_file = FileFactory.create()
     self.our_file = FileFactory.create(created_by=self.member_user)
     self.dummy_data = dict({})
Exemplo n.º 11
0
    def test_assessment_delete_mutation(self):
        query = '''
            mutation MyMutation ($projectId: ID! $assessmentId: ID!) {
              project(id: $projectId) {
                assessmentDelete(id: $assessmentId) {
                  ok
                  errors
                  result {
                    id
                  }
                }
              }
            }
        '''
        project = ProjectFactory.create()
        member_user = UserFactory.create()
        non_member_user = UserFactory.create()
        project.add_member(member_user)

        lead1 = LeadFactory.create(project=project)
        ary = AssessmentFactory.create(project=project, lead=lead1)

        def _query_check(**kwargs):
            return self.query_check(
                query,
                variables={'projectId': project.id, 'assessmentId': ary.id},
                **kwargs
            )

        # -- Without login
        _query_check(assert_for_error=True)

        # --- member user
        self.force_login(member_user)
        content = _query_check(assert_for_error=False)
        self.assertEqual(content['data']['project']['assessmentDelete']['ok'], True)
        self.assertIdEqual(content['data']['project']['assessmentDelete']['result']['id'], ary.id)

        # --- non_member user
        self.force_login(non_member_user)
        _query_check(assert_for_error=True)
Exemplo n.º 12
0
    def set_project_viz_configuration(project):
        w_data = entry_stats_data.WIDGET_DATA
        a_data = entry_stats_data.ATTRIBUTE_DATA

        lead = LeadFactory.create(project=project)
        entry = EntryFactory.create(lead=lead)
        af = project.analysis_framework

        # Create widgets, attributes and configs
        invalid_stat_config = {}
        valid_stat_config = {}

        for index, (title, widget_identifier, data_identifier, config_kwargs) in enumerate([
            ('widget 1d', 'widget_1d', 'matrix1dWidget', {}),
            ('widget 2d', 'widget_2d', 'matrix2dWidget', {}),
            ('geo widget', 'geo_widget', 'geoWidget', {}),
            ('reliability widget', 'reliability_widget', 'scaleWidget', {}),
            ('affected groups widget', 'affected_groups_widget', 'multiselectWidget', {}),
            ('specific needs groups widget', 'specific_needs_groups_widget', 'multiselectWidget', {}),
        ]):
            widget = WidgetFactory.create(
                analysis_framework=af,
                section=None,
                title=title,
                widget_id=data_identifier,
                key=f'{data_identifier}-{index}',
                properties={'data': w_data[data_identifier]},
            )
            EntryAttributeFactory.create(entry=entry, widget=widget, data=a_data[data_identifier])
            valid_stat_config[widget_identifier] = {
                'pk': widget.pk,
                **config_kwargs,
            }
            invalid_stat_config[widget_identifier] = {'pk': 0}

        af.properties = {'stats_config': invalid_stat_config}
        af.save(update_fields=('properties',))

        project.is_visualization_enabled = True
        project.save(update_fields=('is_visualization_enabled',))
Exemplo n.º 13
0
    def test_test_entry_review_verify_control_migrations(self):
        migration_file = importlib.import_module('entry.migrations.0031_entry-migrate-verify-to-review-comment')

        # 3 normal users + Additional non-active user
        user1, user2, user3, _ = UserFactory.create_batch(4)

        af = AnalysisFrameworkFactory.create()
        project = ProjectFactory.create(analysis_framework=af)
        lead = LeadFactory.create(project=project)

        # Create entry before data migrate
        EntryFactory.create(lead=lead, controlled=True, controlled_changed_by=user1)
        EntryFactory.create(lead=lead, controlled=True, controlled_changed_by=user2)
        EntryFactory.create(lead=lead, controlled=False, controlled_changed_by=user3)
        EntryFactory.create(lead=lead, controlled=True, controlled_changed_by=None)
        EntryFactory.create(lead=lead, controlled=False, controlled_changed_by=None)

        # Apply the migration logic
        migration_file.migrate_entry_controlled_to_review_comment_(Entry, EntryReviewComment)

        assert Entry.objects.count() == 5
        # 2 verified review comment are created and 1 unverified review comment is created
        assert EntryReviewComment.objects.count() == 3
        # Related review comment are created by user last action on entry.
        assert set(EntryReviewComment.objects.values_list('created_by_id', flat=True)) == set([user1.pk, user2.pk, user3.pk])
        assert EntryReviewComment.objects.filter(comment_type=EntryReviewComment.CommentType.VERIFY).count() == 2
        assert EntryReviewComment.objects.filter(comment_type=EntryReviewComment.CommentType.UNVERIFY).count() == 1
        assert set(
            EntryReviewComment.objects.filter(
                comment_type=EntryReviewComment.CommentType.VERIFY,
            ).values_list('created_by_id', flat=True)
        ) == set([user1.pk, user2.pk])
        assert set(
            EntryReviewComment.objects.filter(
                comment_type=EntryReviewComment.CommentType.UNVERIFY,
            ).values_list('created_by_id', flat=True)
        ) == set([user3.pk])
        # All controlled, controlled_changed_by should be reset.
        assert Entry.objects.filter(controlled=True).count() == 0
        assert Entry.objects.filter(controlled_changed_by__isnull=False).count() == 0
Exemplo n.º 14
0
    def test_create_assignment_create_on_entry_review_comment(
            self, get_user_mocked_func):
        af = AnalysisFrameworkFactory.create()
        project = ProjectFactory.create(analysis_framework=af)
        user1, user2 = UserFactory.create_batch(2)
        get_user_mocked_func.return_value = user2
        entry = EntryFactory.create(lead=LeadFactory.create(project=project))

        old_assignment_count = Assignment.objects.count()
        entry_review_comment = EntryReviewCommentFactory.create(
            entry=entry, entry_comment=None, created_by=user1)
        new_assignment_count = Assignment.objects.count()

        self.assertEqual(old_assignment_count, new_assignment_count)

        entry_review_comment.mentioned_users.add(user1)
        new_assignment_count = Assignment.objects.count()
        self.assertEqual(old_assignment_count + 1, new_assignment_count)

        # try to change the assigne for the entry_review_comment and test for the change in assignment
        entry_review_comment.mentioned_users.remove(user1)
        entry_review_comment.mentioned_users.add(user2)
        self.assertEqual(old_assignment_count + 1, new_assignment_count)
        assignment = Assignment.objects.get(
            entry_review_comment__id=entry_review_comment.id)
        self.assertEqual(assignment.created_for,
                         user2)  # should represent the new user2

        # try to add another user and remove both from assignee
        entry_review_comment.mentioned_users.add(user1)
        new_assignment_count = Assignment.objects.count()
        self.assertEqual(old_assignment_count + 2, new_assignment_count)

        # try to get the assignment for user
        entry_review_comment.mentioned_users.add(user1, user2)
        assignment = Assignment.get_for(user1)
        assert assignment.count() == 1  # for only the user
        assert get_user_mocked_func.called
Exemplo n.º 15
0
    def test_entries_query(self):
        # Includes permissions checks
        query = '''
            query MyQuery ($projectId: ID!) {
              project(id: $projectId) {
                  entries (ordering: "-id") {
                      totalCount
                      results {
                        id
                        order
                        entryType
                        excerpt
                        attributes {
                          widgetType
                          widget
                          data
                          clientId
                          widgetVersion
                          id
                        }
                        clientId
                        droppedExcerpt
                        highlightHidden
                        informationDate
                        image {
                          id
                          metadata
                          mimeType
                          title
                          file {
                            url
                            name
                          }
                        }
                        controlled
                }
              }
            }
        }
        '''

        user = UserFactory.create()
        lead = LeadFactory.create(project=self.project)
        conf_lead = LeadFactory.create(project=self.project, confidentiality=Lead.Confidentiality.CONFIDENTIAL)
        entry = EntryFactory.create(project=self.project, analysis_framework=self.af, lead=lead)
        conf_entry = EntryFactory.create(project=self.project, analysis_framework=self.af, lead=conf_lead)

        def _query_check(**kwargs):
            return self.query_check(query, variables={'projectId': self.project.pk}, **kwargs)

        # Without login
        _query_check(assert_for_error=True)
        # With login
        self.force_login(user)
        # -- Without membership
        content = _query_check()
        results = content['data']['project']['entries']['results']
        self.assertEqual(content['data']['project']['entries']['totalCount'], 0, content)
        self.assertEqual(len(results), 0, results)
        # -- Without membership (confidential only)
        current_membership = self.project.add_member(user, role=self.project_role_reader_non_confidential)
        content = _query_check()
        results = content['data']['project']['entries']['results']
        self.assertEqual(content['data']['project']['entries']['totalCount'], 1, content)
        self.assertIdEqual(results[0]['id'], entry.pk, results)
        # -- With membership (non-confidential only)
        current_membership.delete()
        self.project.add_member(user, role=self.project_role_reader)
        content = _query_check()
        results = content['data']['project']['entries']['results']
        self.assertEqual(content['data']['project']['entries']['totalCount'], 2, content)
        self.assertIdEqual(results[0]['id'], conf_entry.pk, results)
        self.assertIdEqual(results[1]['id'], entry.pk, results)
Exemplo n.º 16
0
    def test_assessment_query(self):
        query = '''
              query MyQuery ($id: ID!) {
                project(id: $id) {
                  assessments(ordering: "id") {
                    results {
                      id
                      score
                      metadata
                      summary
                      leadGroup {
                          id
                      }
                      lead {
                          id
                      }
                      questionnaire
                      project {
                        id
                      }
                    }
                    totalCount
                  }
                }
              }
        '''
        project1 = ProjectFactory.create()
        project2 = ProjectFactory.create()
        member_user = UserFactory.create()
        member_user = UserFactory.create()
        non_confidential_member_user = UserFactory.create()
        project1.add_member(non_confidential_member_user,
                            role=self.project_role_reader_non_confidential)
        non_member_user = UserFactory.create()
        project1.add_member(member_user)
        project2.add_member(member_user)

        lead1 = LeadFactory.create(
            project=project1,
            confidentiality=Lead.Confidentiality.CONFIDENTIAL)
        lead2 = LeadFactory.create(project=project1)
        lead3 = LeadFactory.create(project=project2)
        ary1 = AssessmentFactory.create(project=project1, lead=lead1)
        ary2 = AssessmentFactory.create(project=project1, lead=lead2)
        ary3 = AssessmentFactory.create(project=project2, lead=lead3)

        # -- non member user (Project 1)
        self.force_login(non_member_user)
        content = self.query_check(query, variables={'id': project1.id})
        self.assertEqual(
            content['data']['project']['assessments']['totalCount'], 0)
        self.assertListIds(
            content['data']['project']['assessments']['results'], [], content)

        # -- non confidential member user (Project 1)
        self.force_login(non_confidential_member_user)
        content = self.query_check(query, variables={'id': project1.id})
        self.assertEqual(
            content['data']['project']['assessments']['totalCount'], 1)
        self.assertListIds(
            content['data']['project']['assessments']['results'], [ary2],
            content)

        # -- member user (Project 1)
        self.force_login(member_user)
        content = self.query_check(query, variables={'id': project1.id})
        self.assertEqual(
            content['data']['project']['assessments']['totalCount'], 2)
        self.assertListIds(
            content['data']['project']['assessments']['results'], [ary1, ary2],
            content)

        # -- member user (Project 2)
        content = self.query_check(query, variables={'id': project2.id})
        self.assertEqual(
            content['data']['project']['assessments']['totalCount'], 1)
        self.assertEqual(
            content['data']['project']['assessments']['results'][0]['id'],
            str(ary3.id))
Exemplo n.º 17
0
    def test_leads_fields_query(self):
        """
        Test leads field value
        """
        query = '''
            query MyQuery ($id: ID!) {
              project(id: $id) {
                analysisFramework {
                    id
                }
                leads(ordering: ASC_ID) {
                  page
                  pageSize
                  totalCount
                  results {
                    id
                    status
                    createdAt
                    title
                    publishedOn
                    priority
                    entriesCount {
                      total
                      controlled
                    }
                    authors {
                      id
                      mergedAs {
                        id
                        title
                        logo {
                          id
                          file {
                            name
                            url
                          }
                        }
                      }
                    }
                    source {
                      id
                      logo {
                        id
                        file {
                          name
                          url
                        }
                      }
                      mergedAs {
                        id
                        title
                      }
                    }
                  }
                }
              }
            }
        '''

        af, af_new = AnalysisFrameworkFactory.create_batch(2)
        project = ProjectFactory.create(analysis_framework=af)
        org_type = OrganizationTypeFactory.create()
        org1 = OrganizationFactory.create(organization_type=org_type)
        org2 = OrganizationFactory.create(organization_type=org_type,
                                          parent=org1)
        org3 = OrganizationFactory.create(organization_type=org_type)
        # User with role
        user = UserFactory.create()
        project.add_member(user)
        # Create lead
        lead1 = LeadFactory.create(project=project, source=org1)
        lead2 = LeadFactory.create(project=project,
                                   source=org2,
                                   authors=[org1, org3])
        lead3 = LeadFactory.create(project=project)

        # Some entries for entriesCount
        EntryFactory.create_batch(2, lead=lead1, controlled=True)
        EntryFactory.create_batch(5, lead=lead1)
        EntryFactory.create_batch(10, lead=lead2)

        # -- With login
        self.force_login(user)

        # --- member user (only unprotected leads)
        self.force_login(user)
        content = self.query_check(query, variables={'id': project.id})
        self.assertIdEqual(
            content['data']['project']['analysisFramework']['id'], af.pk)
        results = content['data']['project']['leads']['results']
        # Count check
        self.assertEqual(content['data']['project']['leads']['totalCount'], 3,
                         content)
        self.assertListIds(results, [lead1, lead2, lead3], content)
        self.assertEqual(len(results[0]['authors']), 0, content)
        # Source check
        self.assertIdEqual(results[0]['source']['id'], org1.id, content)
        self.assertEqual(results[0]['source']['logo']['file']['name'],
                         str(org1.logo.file.name), content)
        self.assertEqual(results[0]['source']['logo']['file']['url'],
                         self.get_media_url(org1.logo.file.name), content)
        # Authors check
        self.assertListIds(results[1]['authors'], [org1, org3], content)
        self.assertIdEqual(results[1]['source']['mergedAs']['id'], org1.id,
                           content)
        # Entries Count check
        for index, (total_count, controlled_count) in enumerate([
            [7, 2],
            [10, 0],
            [0, 0],
        ]):
            self.assertEqual(results[index]['entriesCount']['total'],
                             total_count, content)
            self.assertEqual(results[index]['entriesCount']['controlled'],
                             controlled_count, content)

        # Change AF, this will now not show old entries
        content = self.query_check(query, variables={'id': project.id})
        project.analysis_framework = af_new
        project.save(update_fields=('analysis_framework', ))
        EntryFactory.create_batch(2, lead=lead1, controlled=True)
        EntryFactory.create_batch(1, lead=lead2, controlled=False)
        content = self.query_check(query, variables={'id': project.id})
        self.assertIdEqual(
            content['data']['project']['analysisFramework']['id'], af_new.pk)
        results = content['data']['project']['leads']['results']
        # Entries Count check (After AF change)
        for index, (total_count, controlled_count) in enumerate([
            [2, 2],
            [1, 0],
            [0, 0],
        ]):
            self.assertEqual(results[index]['entriesCount']['total'],
                             total_count, content)
            self.assertEqual(results[index]['entriesCount']['controlled'],
                             controlled_count, content)
Exemplo n.º 18
0
    def test_project_query(self):
        """
        Test private + non-private project behaviour
        """
        query = '''
            query MyQuery ($id: ID!) {
              project(id: $id) {
                id
                title
                currentUserRole
                startDate
                status
                isVisualizationEnabled
                isPrivate
                endDate
                description
                data
                stats {
                  entriesActivity {
                    count
                    date
                  }
                  numberOfLeads
                  numberOfLeadsNotTagged
                  numberOfLeadsInProgress
                  numberOfLeadsTagged
                  numberOfEntries
                  numberOfEntriesVerified
                  numberOfEntriesControlled
                  numberOfUsers
                  leadsActivity {
                    count
                    date
                  }
                }
                membershipPending
                isRejected
                regions {
                  id
                  title
                }
              }
            }
        '''

        user = UserFactory.create()
        analysis_framework = AnalysisFrameworkFactory.create()
        public_project, public_project2, public_project3, public_project4 = ProjectFactory.create_batch(
            4, analysis_framework=analysis_framework)
        now = timezone.now()
        lead1_1 = self.update_obj(LeadFactory.create(project=public_project),
                                  created_at=now + relativedelta(months=-1))
        lead1_2 = self.update_obj(LeadFactory.create(project=public_project),
                                  created_at=now + relativedelta(months=-2))
        lead1_3 = self.update_obj(LeadFactory.create(project=public_project),
                                  created_at=now + relativedelta(months=-2))
        lead1_4 = self.update_obj(LeadFactory.create(project=public_project),
                                  created_at=now + relativedelta(months=-1))
        self.update_obj(LeadFactory.create(project=public_project),
                        created_at=now + relativedelta(months=-1))

        data = [
            {
                "lead": lead1_1,
                "controlled": False,
                "months": -1,
            },
            {
                "lead": lead1_1,
                "controlled": False,
                "months": -3,
            },
            {
                "lead": lead1_2,
                "controlled": True,
                "months": -3,
            },
            {
                "lead": lead1_2,
                "controlled": False,
                "months": -2,
            },
            {
                "lead": lead1_2,
                "controlled": True,
                "months": -2,
            },
            {
                "lead": lead1_3,
                "controlled": True,
                "months": -3,
            },
            {
                "lead": lead1_3,
                "controlled": True,
                "months": -3,
            },
        ]
        now = timezone.now()
        for item in data:
            self.update_obj(
                EntryFactory.create(lead=item['lead'],
                                    controlled=item['controlled'],
                                    project=public_project,
                                    analysis_framework=analysis_framework),
                created_at=now + relativedelta(months=item['months']))
        EntryFactory.create(lead=lead1_3,
                            project=public_project,
                            controlled=True,
                            analysis_framework=analysis_framework)
        EntryFactory.create(lead=lead1_4,
                            project=public_project,
                            controlled=True,
                            analysis_framework=analysis_framework)

        lead2 = LeadFactory.create(project=public_project2)
        lead3 = LeadFactory.create(project=public_project3)
        EntryFactory.create(lead=lead2,
                            project=public_project2,
                            controlled=False,
                            analysis_framework=analysis_framework)
        EntryFactory.create(lead=lead3,
                            project=public_project3,
                            controlled=False,
                            analysis_framework=analysis_framework)

        user2, user3, request_user, non_member_user = UserFactory.create_batch(
            4)
        public_project = ProjectFactory.create(
            analysis_framework=analysis_framework)
        private_project = ProjectFactory.create(
            is_private=True, analysis_framework=analysis_framework)
        ProjectJoinRequestFactory.create(project=public_project,
                                         requested_by=request_user,
                                         status='pending',
                                         role=self.project_role_admin)
        # create projectJoinRequest(status='rejected')
        ProjectJoinRequestFactory.create(project=public_project4,
                                         requested_by=request_user,
                                         status='rejected',
                                         role=self.project_role_admin)
        # add some project member
        public_project.add_member(user)
        public_project.add_member(user2)
        public_project.add_member(user3)

        # add some lead for the project
        lead = LeadFactory.create(project=public_project)
        lead2 = LeadFactory.create(project=public_project)
        LeadFactory.create_batch(3, project=public_project)
        LeadFactory.create(project=private_project)

        # add some entry for the project
        EntryFactory.create_batch(4,
                                  project=public_project,
                                  analysis_framework=analysis_framework,
                                  lead=lead)
        entry2_1 = EntryFactory.create(project=public_project,
                                       analysis_framework=analysis_framework,
                                       lead=lead2,
                                       controlled=True)
        entry2_2 = EntryFactory.create(project=public_project,
                                       analysis_framework=analysis_framework,
                                       lead=lead2)
        EntryFactory.create(project=private_project,
                            analysis_framework=analysis_framework,
                            lead=lead)

        # Verify entries
        entry2_1.verified_by.add(user)
        entry2_1.verified_by.add(user3)
        entry2_2.verified_by.add(user)

        # NOTE: Right noe only IN_PROGRESS status is set automatically
        # Control one lead
        lead2.status = Lead.Status.TAGGED
        lead2.save(update_fields=('status', ))

        # lets add some regions to project
        region1, region2, region3 = RegionFactory.create_batch(3)
        public_project.regions.add(region1)
        public_project.regions.add(region2)
        private_project.regions.add(region3)

        # Generate project cache
        _generate_project_stats_cache()

        # -- Without login
        self.query_check(query,
                         assert_for_error=True,
                         variables={'id': public_project.id})
        self.query_check(query,
                         assert_for_error=True,
                         variables={'id': private_project.id})

        # -- With login
        self.force_login(user)

        # --- non-member user
        content = self.query_check(query, variables={'id': public_project.id})
        self.assertNotEqual(content['data']['project'], None, content)
        content = self.query_check(query, variables={'id': private_project.id})
        self.assertEqual(content['data']['project'], None, content)

        # login with non_member
        self.force_login(non_member_user)
        content = self.query_check(query, variables={'id': public_project.id})
        self.assertNotEqual(content['data']['project'], None, content)
        self.assertEqual(content['data']['project']['membershipPending'],
                         False)

        # login with request_user
        self.force_login(request_user)
        content = self.query_check(query, variables={'id': public_project4.id})
        self.assertNotEqual(content['data']['project'], None, content)
        self.assertEqual(content['data']['project']['isRejected'], True)

        # --- member user
        # ---- (public-project)
        self.force_login(user)
        content = self.query_check(query, variables={'id': public_project.id})
        self.assertNotEqual(content['data']['project'], None, content)
        self.assertEqual(content['data']['project']['stats']['numberOfLeads'],
                         5, content)
        self.assertEqual(
            content['data']['project']['stats']['numberOfLeadsNotTagged'], 3,
            content)
        self.assertEqual(
            content['data']['project']['stats']['numberOfLeadsInProgress'], 1,
            content)
        self.assertEqual(
            content['data']['project']['stats']['numberOfLeadsTagged'], 1,
            content)
        self.assertEqual(
            content['data']['project']['stats']['numberOfEntries'], 6, content)
        self.assertEqual(
            content['data']['project']['stats']['numberOfEntriesVerified'], 2,
            content)
        self.assertEqual(
            content['data']['project']['stats']['numberOfEntriesControlled'],
            1, content)
        self.assertEqual(content['data']['project']['stats']['numberOfUsers'],
                         3, content)
        self.assertEqual(
            len(content['data']['project']['stats']['leadsActivity']), 1,
            content)
        self.assertEqual(
            len(content['data']['project']['stats']['entriesActivity']), 1,
            content)
        self.assertEqual(len(content['data']['project']['regions']), 2,
                         content)
        self.assertListIds(content['data']['project']['regions'],
                           [region1, region2], content)

        # login with request user
        self.force_login(request_user)
        content = self.query_check(query, variables={'id': public_project.id})
        self.assertNotEqual(content['data']['project'], None, content)
        self.assertEqual(content['data']['project']['membershipPending'], True)

        # ---- (private-project)
        self.force_login(user)
        private_project.add_member(user)
        content = self.query_check(query, variables={'id': private_project.id})
        self.assertNotEqual(content['data']['project'], None, content)
        self.assertEqual(len(content['data']['project']['regions']), 1,
                         content)
        self.assertListIds(content['data']['project']['regions'], [region3],
                           content)
Exemplo n.º 19
0
    def test_snapshot(self):
        query = '''
            query MyQuery {
              projectExploreStats {
                totalProjects
                totalUsers
                leadsAddedWeekly
                dailyAverageLeadsTaggedPerProject
                generatedExportsMonthly
                topActiveProjects {
                  projectId
                  projectTitle
                  analysisFrameworkId
                  analysisFrameworkTitle
                }
                calculatedAt
              }
            }
        '''

        def _cache_clear():
            cache.delete(
                CacheKey.PROJECT_EXPLORE_STATS_LOADER_KEY)  # Delete cache

        user = UserFactory.create()

        # -- With login
        self.force_login(user)

        _cache_clear()

        previous_content = content = self.query_check(query)
        self.assertMatchSnapshot(content, 'no-data')

        UserFactory.create_batch(3, is_active=False)  # Some Inactive users
        analysis_framework = AnalysisFrameworkFactory.create()
        projects = ProjectFactory.create_batch(3)
        projects_with_af = ProjectFactory.create_batch(
            3, analysis_framework=analysis_framework)
        # This shouldn't show in top projects but leads/entries count should
        private_project = ProjectFactory.create(
            title='Private Project',
            is_private=True,
            analysis_framework=analysis_framework)
        now = timezone.now()

        # Generate project cache
        _generate_project_stats_cache()

        content = self.query_check(query)
        self.assertEqual(content, previous_content)  # Test for cache
        _cache_clear()
        previous_content = content = self.query_check(
            query)  # Pull latest data
        self.assertMatchSnapshot(content, 'only-project')

        self.update_obj(LeadFactory.create(project=projects[0]),
                        created_at=now + relativedelta(weeks=-1))
        self.update_obj(LeadFactory.create(project=projects[0]),
                        created_at=now + relativedelta(weeks=-1))
        self.update_obj(LeadFactory.create(project=projects[1]),
                        created_at=now + relativedelta(weeks=-2))
        self.update_obj(LeadFactory.create(project=projects[1]),
                        created_at=now + relativedelta(weeks=-1))
        self.update_obj(LeadFactory.create(project=projects[1]),
                        created_at=now + relativedelta(weeks=-1))
        self.update_obj(LeadFactory.create(project=projects[2]),
                        created_at=now + relativedelta(weeks=-2))

        lead0_1 = self.update_obj(
            LeadFactory.create(project=projects_with_af[0]),
            created_at=now + relativedelta(weeks=-1))
        lead1_1 = self.update_obj(
            LeadFactory.create(project=projects_with_af[1]),
            created_at=now + relativedelta(weeks=-2))
        lead1_2 = self.update_obj(
            LeadFactory.create(project=projects_with_af[1]),
            created_at=now + relativedelta(weeks=-1))
        plead1_1 = self.update_obj(LeadFactory.create(project=private_project),
                                   created_at=now + relativedelta(weeks=-2))
        plead1_2 = self.update_obj(LeadFactory.create(project=private_project),
                                   created_at=now + relativedelta(weeks=-1))
        self.update_obj(LeadFactory.create(project=projects_with_af[1]),
                        created_at=now + relativedelta(weeks=-1))
        self.update_obj(LeadFactory.create(project=projects_with_af[2]),
                        created_at=now + relativedelta(weeks=-3))

        self.update_obj(EntryFactory.create(lead=lead0_1),
                        created_at=now + relativedelta(weeks=-1))
        self.update_obj(EntryFactory.create(lead=lead1_1),
                        created_at=now + relativedelta(weeks=-1))
        self.update_obj(EntryFactory.create(lead=lead1_2),
                        created_at=now + relativedelta(weeks=-1))
        self.update_obj(EntryFactory.create(lead=plead1_1),
                        created_at=now + relativedelta(weeks=-1))
        self.update_obj(EntryFactory.create(lead=plead1_2),
                        created_at=now + relativedelta(weeks=-1))

        # Generate project cache
        _generate_project_stats_cache()

        self.update_obj(ExportFactory.create(project=projects_with_af[0],
                                             exported_by=user),
                        exported_at=now + relativedelta(months=-1))
        self.update_obj(ExportFactory.create(project=projects_with_af[0],
                                             exported_by=user),
                        exported_at=now + relativedelta(months=-1))
        self.update_obj(ExportFactory.create(project=projects_with_af[0],
                                             exported_by=user),
                        exported_at=now + relativedelta(months=-2))
        self.update_obj(ExportFactory.create(project=projects_with_af[1],
                                             exported_by=user),
                        exported_at=now + relativedelta(months=-2))
        self.update_obj(ExportFactory.create(project=projects_with_af[2],
                                             exported_by=user),
                        exported_at=now + relativedelta(months=-3))
        self.update_obj(ExportFactory.create(project=private_project,
                                             exported_by=user),
                        exported_at=now + relativedelta(months=-1))

        content = self.query_check(query)
        self.assertEqual(content, previous_content)  # Test for cache
        _cache_clear()
        previous_content = content = self.query_check(
            query)  # Pull latest data
        self.assertMatchSnapshot(content, 'with-data')
Exemplo n.º 20
0
    def test_lead_options_query(self):
        """
        Test leads field value
        """
        query = '''
            query MyQuery ($id: ID!) {
              project(id: $id) {
                leadGroups {
                  results {
                    id
                    title
                  }
                  totalCount
                }
                emmEntities {
                  results {
                    id
                    name
                  }
                  totalCount
                }
                leadEmmTriggers {
                  results {
                    count
                    emmKeyword
                    emmRiskFactor
                    id
                  }
                  totalCount
                }
              }
            }
        '''
        project = ProjectFactory.create()
        project2 = ProjectFactory.create()
        member_user = UserFactory.create()
        confidential_member_user = UserFactory.create()
        project.add_member(member_user, role=self.project_role_owner)
        project.add_member(confidential_member_user,
                           role=self.project_role_reader)

        lead_group1 = LeadGroupFactory.create(project=project)
        lead_group2 = LeadGroupFactory.create(project=project)
        LeadGroupFactory.create(project=project2)

        emm_entity_1 = EmmEntityFactory.create()
        emm_entity_2 = EmmEntityFactory.create()
        emm_entity_3 = EmmEntityFactory.create()

        lead1 = LeadFactory.create(
            project=project,
            emm_entities=[emm_entity_1, emm_entity_2],
            confidentiality=Lead.Confidentiality.CONFIDENTIAL)
        lead2 = LeadFactory.create(project=project,
                                   emm_entities=[emm_entity_1])
        lead3 = LeadFactory.create(project=project,
                                   emm_entities=[emm_entity_3])
        lead4 = LeadFactory.create(project=project2,
                                   emm_entities=[emm_entity_3])

        LeadEMMTriggerFactory.create(lead=lead1)
        LeadEMMTriggerFactory.create(lead=lead2)
        LeadEMMTriggerFactory.create(lead=lead3)
        LeadEMMTriggerFactory.create(lead=lead4)

        self.force_login(member_user)
        # test for lead group
        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)]))

        # with different project
        content = self.query_check(query, variables={'id': project2.id})
        self.assertEqual(
            content['data']['project']['leadGroups']['totalCount'], 0)

        # test for emm_entities
        # login with member_user
        content = self.query_check(query, variables={'id': project.id})
        self.assertEqual(
            content['data']['project']['emmEntities']['totalCount'], 3)

        # login with confidential_member_user
        self.force_login(confidential_member_user)
        content = self.query_check(query, variables={'id': project.id})
        self.assertEqual(
            content['data']['project']['emmEntities']['totalCount'], 3)

        # test for lead_emm_trigger
        # login with confidential_member_user
        content = self.query_check(query, variables={'id': project.id})
        self.assertEqual(
            content['data']['project']['leadEmmTriggers']['totalCount'], 3)

        # test for project that user is not member
        content = self.query_check(query, variables={'id': project2.id})
        self.assertEqual(
            content['data']['project']['leadEmmTriggers']['totalCount'], 0)
Exemplo n.º 21
0
    def test_review_comments_project_scope_query(self):
        """
        Include permission check
        """
        query = '''
            query MyQuery ($projectId: ID! $reviewId: ID!) {
                project(id: $projectId) {
                    reviewComment(id: $reviewId) {
                        commentType
                        createdAt
                        createdBy {
                            id
                            firstName
                        }
                        id
                        mentionedUsers {
                            displayName
                            displayPictureUrl
                        }
                        textHistory {
                            createdAt
                            id
                            text
                        }
                    }
                }
            }
        '''

        user = UserFactory.create()
        analysis_framework = AnalysisFrameworkFactory.create()
        project = ProjectFactory.create(analysis_framework=analysis_framework)
        lead = LeadFactory.create(project=project)
        conf_lead = LeadFactory.create(
            project=project, confidentiality=Lead.Confidentiality.CONFIDENTIAL)
        entry = EntryFactory.create(project=project,
                                    analysis_framework=analysis_framework,
                                    lead=lead)
        conf_entry = EntryFactory.create(project=project,
                                         analysis_framework=analysis_framework,
                                         lead=conf_lead)

        review_comment = EntryReviewCommentFactory.create(entry=entry,
                                                          created_by=user)
        conf_review_comment = EntryReviewCommentFactory.create(
            entry=conf_entry, created_by=user)
        review_text1, review_text2 = EntryReviewCommentTextFactory.create_batch(
            2, comment=review_comment)
        review_text_conf1, review_text_conf2 = EntryReviewCommentTextFactory.create_batch(
            2, comment=conf_review_comment)

        def _query_check(review_comment, **kwargs):
            return self.query_check(query,
                                    variables={
                                        'projectId': project.id,
                                        'reviewId': review_comment.id
                                    },
                                    **kwargs)

        # Without login
        _query_check(review_comment, assert_for_error=True)
        _query_check(conf_review_comment, assert_for_error=True)
        # With login
        self.force_login(user)
        # -- Without membership
        content = _query_check(review_comment)
        self.assertEqual(content['data']['project']['reviewComment'], None,
                         content)
        # -- Without membership (confidential only)
        current_membership = project.add_member(
            user, role=self.project_role_reader_non_confidential)
        content = _query_check(review_comment)
        self.assertNotEqual(content['data']['project']['reviewComment'], None,
                            content)
        self.assertEqual(
            len(content['data']['project']['reviewComment']['textHistory']), 2,
            content)
        self.assertListIds(
            content['data']['project']['reviewComment']['textHistory'],
            [review_text1, review_text2], content)
        content = _query_check(conf_review_comment)
        self.assertEqual(content['data']['project']['reviewComment'], None,
                         content)
        # -- With membership (non-confidential only)
        current_membership.delete()
        project.add_member(user, role=self.project_role_reader)
        content = _query_check(review_comment)
        self.assertNotEqual(content['data']['project']['reviewComment'], None,
                            content)
        content = _query_check(conf_review_comment)
        self.assertNotEqual(content['data']['project']['reviewComment'], None,
                            content)
        self.assertEqual(
            len(content['data']['project']['reviewComment']['textHistory']), 2,
            content)
        self.assertListIds(
            content['data']['project']['reviewComment']['textHistory'],
            [review_text_conf1, review_text_conf2], content)
Exemplo n.º 22
0
    def test_lead_query(self):
        """
        Test private + non-private project behaviour
        """
        query = '''
            query MyQuery ($projectId: ID! $leadId: ID!) {
              project(id: $projectId) {
                lead (id: $leadId) {
                  id
                  title
                  text
                }
              }
            }
        '''

        project = ProjectFactory.create()
        # User with role
        non_member_user = UserFactory.create()
        member_user = UserFactory.create()
        confidential_member_user = UserFactory.create()
        project.add_member(member_user,
                           role=self.project_role_reader_non_confidential)
        project.add_member(confidential_member_user,
                           role=self.project_role_reader)
        normal_lead = LeadFactory.create(
            project=project)  # It's UNPROTECTED by default
        confidential_lead = LeadFactory.create(
            project=project, confidentiality=Lead.Confidentiality.CONFIDENTIAL)

        def _query_check(lead, **kwargs):
            return self.query_check(query,
                                    variables={
                                        'projectId': project.id,
                                        'leadId': lead.id
                                    },
                                    **kwargs)

        # -- Without login
        _query_check(confidential_lead, assert_for_error=True)
        _query_check(normal_lead, assert_for_error=True)

        # -- With login
        self.force_login(non_member_user)

        # --- non-member user
        content = _query_check(normal_lead)
        self.assertEqual(content['data']['project']['lead'], None, content)
        content = _query_check(confidential_lead)
        self.assertEqual(content['data']['project']['lead'], None, content)

        # --- member user
        self.force_login(member_user)
        content = _query_check(normal_lead)
        self.assertNotEqual(content['data']['project']['lead'], None, content)
        content = _query_check(confidential_lead)
        self.assertEqual(content['data']['project']['lead'], None, content)

        # --- confidential member user
        self.force_login(confidential_member_user)
        content = _query_check(normal_lead)
        self.assertNotEqual(content['data']['project']['lead'], None, content)
        content = _query_check(confidential_lead)
        self.assertNotEqual(content['data']['project']['lead'], None, content)
Exemplo n.º 23
0
    def test_public_lead_query(self):
        query = '''
            query MyQuery ($uuid: UUID!) {
              publicLead(uuid: $uuid) {
                project {
                  id
                  isRejected
                  membershipPending
                }
                lead {
                  uuid
                  projectTitle
                  url
                  text
                  sourceTypeDisplay
                  sourceType
                  sourceTitle
                  publishedOn
                  createdByDisplayName
                  attachment {
                    title
                    file {
                      url
                      name
                    }
                  }
                }
              }
            }
          '''

        project = ProjectFactory.create()
        # User with role
        non_member_user = UserFactory.create(email='[email protected]')
        member_user = UserFactory.create(email='[email protected]')
        confidential_member_user = UserFactory.create(
            email='[email protected]')
        project.add_member(member_user,
                           role=self.project_role_reader_non_confidential)
        project.add_member(confidential_member_user,
                           role=self.project_role_reader)
        # Public project
        unprotected_lead = LeadFactory.create(
            project=project,
            confidentiality=Lead.Confidentiality.UNPROTECTED,
            title='unprotected_lead',
        )
        restricted_lead = LeadFactory.create(
            project=project,
            confidentiality=Lead.Confidentiality.RESTRICTED,
            title='restricted_lead',
        )
        confidential_lead = LeadFactory.create(
            project=project,
            confidentiality=Lead.Confidentiality.CONFIDENTIAL,
            title='confidential_lead',
        )

        def _query_check(lead):
            return self.query_check(query, variables={'uuid': str(lead.uuid)})

        cases = [
            # Public Project
            (
                False,
                False,
                [  # Project view public leads
                    (
                        # Without login [Lead, show_project, show_lead]
                        None,
                        [
                            [unprotected_lead, False, False, None],
                            [restricted_lead, False, False, None],
                            [confidential_lead, False, False, None],
                        ],
                    ),
                    (
                        # Non member user
                        non_member_user,
                        [
                            [unprotected_lead, True, False, None],
                            [restricted_lead, True, False, None],
                            [confidential_lead, True, False, None],
                        ]),
                    (
                        # Member user with non-confidential access
                        member_user,
                        [
                            [unprotected_lead, True, True, True],
                            [restricted_lead, True, True, True],
                            [confidential_lead, True, False, None],
                        ]),
                    (
                        # Member user with confidential access
                        confidential_member_user,
                        [
                            [unprotected_lead, True, True, True],
                            [restricted_lead, True, True, True],
                            [confidential_lead, True, True, True],
                        ]),
                ]),
            (
                False,
                True,
                [  # Project view public leads
                    (
                        # Without login
                        None,
                        [
                            [unprotected_lead, False, True, True],
                            [restricted_lead, False, False, None],
                            [confidential_lead, False, False, None],
                        ],
                    ),
                    (
                        # Non member user
                        non_member_user,
                        [
                            [unprotected_lead, True, True, True],
                            [restricted_lead, True, False, None],
                            [confidential_lead, True, False, None],
                        ]),
                    (
                        # Member user with non-confidential access
                        member_user,
                        [
                            [unprotected_lead, True, True, True],
                            [restricted_lead, True, True, True],
                            [confidential_lead, True, False, None],
                        ]),
                    (
                        # Member user with confidential access
                        confidential_member_user,
                        [
                            [unprotected_lead, True, True, True],
                            [restricted_lead, True, True, True],
                            [confidential_lead, True, True, True],
                        ]),
                ]),
            # Private Project
            (
                True,
                False,
                [  # Project view public leads
                    (
                        # Without login
                        None,
                        [
                            [unprotected_lead, False, False, None],
                            [restricted_lead, False, False, None],
                            [confidential_lead, False, False, None],
                        ],
                    ),
                    (
                        # Non member user
                        non_member_user,
                        [
                            [unprotected_lead, False, False, None],
                            [restricted_lead, False, False, None],
                            [confidential_lead, False, False, None],
                        ]),
                    (
                        # Member user with non-confidential access
                        member_user,
                        [
                            [unprotected_lead, True, True, True],
                            [restricted_lead, True, True, True],
                            [confidential_lead, True, False, None],
                        ]),
                    (
                        # Member user with confidential access
                        confidential_member_user,
                        [
                            [unprotected_lead, True, True, True],
                            [restricted_lead, True, True, True],
                            [confidential_lead, True, True, True],
                        ]),
                ]),
            (
                True,
                True,
                [  # Project view public leads
                    (
                        # Without login
                        None,
                        [
                            [unprotected_lead, False, True, False],
                            [restricted_lead, False, False, None],
                            [confidential_lead, False, False, None],
                        ],
                    ),
                    (
                        # Non member user
                        non_member_user,
                        [
                            [unprotected_lead, False, True, False],
                            [restricted_lead, False, False, None],
                            [confidential_lead, False, False, None],
                        ]),
                    (
                        # Member user with non-confidential access
                        member_user,
                        [
                            [unprotected_lead, True, True, True],
                            [restricted_lead, True, True, True],
                            [confidential_lead, True, False, None],
                        ]),
                    (
                        # Member user with confidential access
                        confidential_member_user,
                        [
                            [unprotected_lead, True, True, True],
                            [restricted_lead, True, True, True],
                            [confidential_lead, True, True, True],
                        ]),
                ]),
        ]
        for is_private, project_show_public_leads, user_and_conditions in cases:
            project.is_private = is_private
            project.has_publicly_viewable_leads = project_show_public_leads
            project.save(update_fields=(
                'is_private',
                'has_publicly_viewable_leads',
            ))
            for user, conditions in user_and_conditions:
                if user:
                    self.force_login(user)
                else:
                    self.logout()
                for used_lead, expect_project_membership_data, expect_lead, show_project_title in conditions:
                    content = _query_check(used_lead)['data']['publicLead']
                    check_meta = (is_private, project_show_public_leads, user,
                                  used_lead)
                    # Excepted Lead
                    if expect_lead:
                        self.assertIsNotNone(content['lead'], check_meta)
                        self.assertEqual(content['lead']['uuid'],
                                         str(used_lead.uuid))
                        # Show project title in Lead data.
                        if show_project_title:
                            self.assertIsNotNone(
                                content['lead']['projectTitle'], check_meta)
                        else:
                            self.assertIsNone(content['lead']['projectTitle'],
                                              check_meta)
                    else:
                        self.assertIsNone(content['lead'], check_meta)
                    # Show project with membership data
                    if expect_project_membership_data:
                        self.assertIsNotNone(content['project'], check_meta)
                        self.assertEqual(content['project']['id'],
                                         str(used_lead.project_id))
                    else:
                        self.assertIsNone(content['project'], check_meta)
Exemplo n.º 24
0
    def test_leads_query(self):
        """
        Test private + non-private project behaviour
        """
        query = '''
            query MyQuery ($id: ID!) {
              project(id: $id) {
                leads {
                  page
                  pageSize
                  totalCount
                  results {
                    id
                    title
                    text
                  }
                }
              }
            }
        '''

        project = ProjectFactory.create()
        # User with role
        non_member_user = UserFactory.create()
        member_user = UserFactory.create()
        confidential_member_user = UserFactory.create()
        project.add_member(member_user,
                           role=self.project_role_reader_non_confidential)
        project.add_member(confidential_member_user,
                           role=self.project_role_reader)
        # Create 10 (5 confidential, 5 non-protected) dummy leads
        normal_leads = LeadFactory.create_batch(
            5, project=project)  # It's UNPROTECTED by default
        confidential_leads = LeadFactory.create_batch(
            6,
            project=project,
            confidentiality=Lead.Confidentiality.CONFIDENTIAL)

        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(non_member_user)

        # --- non-member user (zero leads)
        content = _query_check()
        self.assertEqual(content['data']['project']['leads']['totalCount'], 0,
                         content)
        self.assertEqual(len(content['data']['project']['leads']['results']),
                         0, content)

        # --- member user (only unprotected leads)
        self.force_login(member_user)
        content = _query_check()
        self.assertEqual(content['data']['project']['leads']['totalCount'], 5,
                         content)
        self.assertListIds(content['data']['project']['leads']['results'],
                           normal_leads, content)

        # --- confidential member user (all leads)
        self.force_login(confidential_member_user)
        content = _query_check()
        self.assertEqual(content['data']['project']['leads']['totalCount'], 11,
                         content)
        self.assertListIds(content['data']['project']['leads']['results'],
                           confidential_leads + normal_leads, content)
Exemplo n.º 25
0
    def test_lead_update_validation(self):
        query = '''
            mutation MyMutation ($projectId: ID! $leadId: ID! $input: LeadInputType!) {
              project(id: $projectId) {
                leadUpdate(id: $leadId data: $input) {
                  ok
                  errors
                  result {
                    id
                    title
                    sourceType
                    text
                    url
                    attachment {
                        id
                    }
                    assignee {
                        id
                    }
                    emmEntities {
                        name
                    }
                    emmTriggers {
                        emmKeyword
                        emmRiskFactor
                        count
                    }
                  }
                }
              }
            }
        '''

        lead = LeadFactory.create(project=self.project)
        non_access_lead = LeadFactory.create()
        user_file = FileFactory.create(created_by=self.member_user)

        minput = dict(title='New Lead')

        def _query_check(_lead, **kwargs):
            return self.query_check(
                query,
                minput=minput,
                mnested=['project'],
                variables={
                    'projectId': self.project.id,
                    'leadId': _lead.id
                },
                **kwargs,
            )

        # --- without login
        _query_check(lead, assert_for_error=True)

        # --- login
        self.force_login(self.member_user)
        # ------- Non access lead
        _query_check(non_access_lead, okay=False)
        # ------- Access lead
        result = _query_check(
            lead, okay=True)['data']['project']['leadUpdate']['result']
        self.assertEqual(result['title'], minput['title'], result)
        # -------- Duplicate leads validations
        # ------------ Text (Using duplicate text)
        new_lead = LeadFactory.create(project=self.project)
        minput['sourceType'] = self.genum(Lead.SourceType.TEXT)
        minput['text'] = new_lead.text
        result = _query_check(
            lead, okay=False)['data']['project']['leadUpdate']['result']
        self.assertEqual(result, None, result)
        new_lead.delete()  # Can save after deleting the conflicting lead.
        result = _query_check(
            lead, okay=True)['data']['project']['leadUpdate']['result']
        self.assertEqual(result['title'], minput['title'], result)
        # ------------ Website (Using duplicate website)
        new_lead = LeadFactory.create(project=self.project,
                                      source_type=Lead.SourceType.WEBSITE,
                                      url='https://example.com/random-path')
        minput['sourceType'] = self.genum(Lead.SourceType.WEBSITE)
        minput['url'] = new_lead.url
        result = _query_check(
            lead, okay=False)['data']['project']['leadUpdate']['result']
        self.assertEqual(result, None, result)
        new_lead.delete()  # Can save after deleting the conflicting lead.
        result = _query_check(
            lead, okay=True)['data']['project']['leadUpdate']['result']
        self.assertEqual(result['url'], minput['url'], result)
        # ------------ Attachment (Using duplicate file)
        new_lead = LeadFactory.create(project=self.project,
                                      source_type=Lead.SourceType.DISK,
                                      attachment=user_file)
        minput['sourceType'] = self.genum(Lead.SourceType.DISK)
        minput['attachment'] = new_lead.attachment.pk
        result = _query_check(
            lead, okay=False)['data']['project']['leadUpdate']['result']
        self.assertEqual(result, None, result)
        new_lead.delete()  # Can save after deleting the conflicting lead.
        result = _query_check(
            lead, okay=True)['data']['project']['leadUpdate']['result']
        self.assertIdEqual(result['attachment']['id'], minput['attachment'],
                           result)
Exemplo n.º 26
0
    def test_lead_query_filter(self):
        af = AnalysisFrameworkFactory.create()
        project = ProjectFactory.create(analysis_framework=af)
        org_type1, org_type2 = OrganizationTypeFactory.create_batch(2)
        org1 = OrganizationFactory.create(organization_type=org_type1)
        org2 = OrganizationFactory.create(organization_type=org_type2)
        org3 = OrganizationFactory.create(organization_type=org_type2)
        org1_child = OrganizationFactory.create(organization_type=org_type2,
                                                parent=org1)
        # User with role
        user = UserFactory.create()
        member1 = UserFactory.create()
        member2 = UserFactory.create()
        project.add_member(user, role=self.project_role_reader)
        project.add_member(member1, role=self.project_role_reader)
        project.add_member(member2, role=self.project_role_reader)
        lead1 = LeadFactory.create(
            project=project,
            title='Test 1',
            source_type=Lead.SourceType.TEXT,
            confidentiality=Lead.Confidentiality.CONFIDENTIAL,
            source=org1_child,
            authors=[org1, org2],
            assignee=[member1],
            priority=Lead.Priority.HIGH,
            status=Lead.Status.IN_PROGRESS,
        )
        lead2 = LeadFactory.create(
            project=project,
            source_type=Lead.SourceType.TEXT,
            title='Test 2',
            assignee=[member2],
            authors=[org2, org3],
            priority=Lead.Priority.HIGH,
        )
        lead3 = LeadFactory.create(
            project=project,
            source_type=Lead.SourceType.WEBSITE,
            url='https://wwwexample.com/sample-1',
            title='Sample 1',
            confidentiality=Lead.Confidentiality.CONFIDENTIAL,
            source=org2,
            authors=[org1, org3],
            priority=Lead.Priority.LOW,
        )
        lead4 = LeadFactory.create(
            project=project,
            title='Sample 2',
            source=org3,
            authors=[org1],
            priority=Lead.Priority.MEDIUM,
        )
        lead5 = LeadFactory.create(
            project=project,
            title='Sample 3',
            status=Lead.Status.TAGGED,
            assignee=[member2],
            source=org3,
        )

        EntryFactory.create(project=project,
                            analysis_framework=af,
                            lead=lead4,
                            controlled=False)
        EntryFactory.create(project=project,
                            analysis_framework=af,
                            lead=lead4,
                            controlled=False)
        EntryFactory.create(project=project,
                            analysis_framework=af,
                            lead=lead5,
                            controlled=True)
        AssessmentFactory.create(project=project, lead=lead1)
        AssessmentFactory.create(project=project, lead=lead2)

        # -- With login
        self.force_login(user)

        # TODO: Add direct test for filter_set as well (is used within export)
        for filter_data, expected_leads in [
            ({
                'search': 'test'
            }, [lead1, lead2]),
            ({
                'confidentiality':
                self.genum(Lead.Confidentiality.CONFIDENTIAL)
            }, [lead1, lead3]),
            ({
                'assignees': [member2.pk]
            }, [lead2, lead5]),
            ({
                'assignees': [member1.pk, member2.pk]
            }, [lead1, lead2, lead5]),
            ({
                'authoringOrganizationTypes': [org_type2.pk]
            }, [lead1, lead2, lead3]),
            ({
                'authoringOrganizationTypes': [org_type1.pk, org_type2.pk]
            }, [lead1, lead2, lead3, lead4]),
            ({
                'authorOrganizations': [org1.pk, org2.pk]
            }, [lead1, lead2, lead3, lead4]),
            ({
                'authorOrganizations': [org3.pk]
            }, [lead2, lead3]),
            ({
                'sourceOrganizations': [org1.pk, org2.pk]
            }, [lead1, lead3]),
            ({
                'sourceOrganizations': [org3.pk]
            }, [lead4, lead5]),
            ({
                'priorities': [self.genum(Lead.Priority.HIGH)]
            }, [lead1, lead2]),
            ({
                'priorities': [
                    self.genum(Lead.Priority.LOW),
                    self.genum(Lead.Priority.HIGH)
                ]
            }, [lead1, lead2, lead3, lead5]),
            ({
                'sourceTypes': [self.genum(Lead.SourceType.WEBSITE)]
            }, [lead3]),
            ({
                'sourceTypes': [
                    self.genum(Lead.SourceType.TEXT),
                    self.genum(Lead.SourceType.WEBSITE)
                ]
            }, [lead1, lead2, lead3]),
            ({
                'statuses': [self.genum(Lead.Status.NOT_TAGGED)]
            }, [lead2, lead3]),
            ({
                'statuses': [
                    self.genum(Lead.Status.IN_PROGRESS),
                    self.genum(Lead.Status.TAGGED)
                ]
            }, [lead1, lead4, lead5]),
            ({
                'hasEntries': True
            }, [lead4, lead5]),
            ({
                'hasEntries': False
            }, [lead1, lead2, lead3]),
            ({
                'hasEntries':
                True,
                'ordering': [
                    self.genum(LeadOrderingEnum.DESC_ENTRIES_COUNT),
                    self.genum(LeadOrderingEnum.ASC_ID)
                ],
            }, [lead5, lead4]),
            ({
                'hasEntries':
                True,
                'entriesFilterData': {},
                'ordering': [
                    self.genum(LeadOrderingEnum.DESC_ENTRIES_COUNT),
                    self.genum(LeadOrderingEnum.ASC_ID)
                ],
            }, [lead5, lead4]),
            ({
                'entriesFilterData': {
                    'controlled': True
                },
                'ordering': [
                    self.genum(LeadOrderingEnum.DESC_ENTRIES_COUNT),
                    self.genum(LeadOrderingEnum.ASC_ID)
                ],
            }, [lead5]),
            ({
                'hasAssessment': True
            }, [lead1, lead2]),
            ({
                'hasAssessment': False
            }, [lead3, lead4, lead5]),
                # TODO:
                # ({'emmEntities': []}, []),
                # ({'emmKeywords': []}, []),
                # ({'emmRiskFactors': []}, []),
                # TODO: Common filters
                # ({'publishedOn': []}, []),
                # ({'publishedOnGte': []}, []),
                # ({'publishedOnLte': []}, []),
                # ({'text': []}, []),
                # ({'url': []}, []),
                # ({'createdAt': []}, []),
                # ({'createdAtGte': []}, []),
                # ({'createdAtLte': []}, []),
        ]:
            content = self.query_check(self.lead_filter_query,
                                       variables={
                                           'projectId': project.id,
                                           **filter_data
                                       })
            self.assertListIds(content['data']['project']['leads']['results'],
                               expected_leads, {
                                   'response': content,
                                   'filter': filter_data
                               })
Exemplo n.º 27
0
    def test_review_comments_query(self):
        query = '''
            query MyQuery ($projectId: ID! $entryId: ID!) {
                project(id: $projectId) {
                    entry (id: $entryId) {
                        id
                        verifiedBy {
                            displayName
                            id
                        }
                        controlled
                        controlledChangedBy {
                            id
                            displayName
                        }
                        reviewCommentsCount
                    }
                    reviewComments (entry: $entryId, ordering: DESC_ID) {
                        totalCount
                        results {
                            id
                            text
                            commentType
                            createdAt
                            mentionedUsers {
                                displayName
                                id
                            }
                        }
                    }
                }
            }
        '''

        user = UserFactory.create()
        user2, user3 = UserFactory.create_batch(2)
        analysis_framework = AnalysisFrameworkFactory.create()
        project = ProjectFactory.create(analysis_framework=analysis_framework)
        lead = LeadFactory.create(project=project)
        entry = EntryFactory.create(project=project,
                                    analysis_framework=analysis_framework,
                                    lead=lead,
                                    controlled=True,
                                    controlled_changed_by=user2,
                                    verified_by=[user2, user3])
        entry1 = EntryFactory.create(
            project=project,
            analysis_framework=analysis_framework,
            lead=lead,
        )

        review_comment1, review_comment2 = EntryReviewCommentFactory.create_batch(
            2, entry=entry, created_by=user)
        EntryReviewCommentFactory.create(entry=entry1, created_by=user)
        review_text1 = EntryReviewCommentTextFactory.create(
            comment=review_comment1)

        # -- Without login
        self.query_check(query,
                         assert_for_error=True,
                         variables={
                             'projectId': project.id,
                             'entryId': entry.id
                         })

        # -- With login
        self.force_login(user)

        # --- non-member user
        content = self.query_check(query,
                                   variables={
                                       'projectId': project.id,
                                       'entryId': entry.id
                                   })
        self.assertEqual(content['data']['project']['entry'], None, content)

        # --- add-member in project
        project.add_member(user)
        content = self.query_check(query,
                                   variables={
                                       'projectId': project.id,
                                       'entryId': entry.id
                                   })
        self.assertEqual(
            content['data']['project']['entry']['reviewCommentsCount'], 2,
            content)
        self.assertEqual(
            content['data']['project']['reviewComments']['totalCount'], 2,
            content)
        self.assertListIds(
            content['data']['project']['reviewComments']['results'],
            [review_comment1, review_comment2], content)
        self.assertEqual(
            content['data']['project']['reviewComments']['results'][1]['text'],
            review_text1.text, content)

        # add another review_text for same review_comment
        review_text2 = EntryReviewCommentTextFactory.create(
            comment=review_comment1)
        content = self.query_check(query,
                                   variables={
                                       'projectId': project.id,
                                       'entryId': entry.id
                                   })
        self.assertEqual(
            content['data']['project']['entry']['reviewCommentsCount'], 2,
            content)
        self.assertEqual(
            content['data']['project']['reviewComments']['results'][1]['text'],
            review_text2.text,  # here latest text should be present
            content)

        # lets check for the contolled in entry
        self.assertEqual(content['data']['project']['entry']['controlled'],
                         True, content)
        self.assertEqual(
            content['data']['project']['entry']['controlledChangedBy']['id'],
            str(user2.id), content)
        self.assertEqual(
            len(content['data']['project']['entry']['verifiedBy']), 2, content)

        # lets query for another entry
        content = self.query_check(query,
                                   variables={
                                       'projectId': project.id,
                                       'entryId': entry1.id
                                   })
        self.assertEqual(
            content['data']['project']['entry']['reviewCommentsCount'], 1,
            content)
        self.assertEqual(
            content['data']['project']['reviewComments']['totalCount'], 1,
            content)
Exemplo n.º 28
0
    def test_lead_copy_mutation(self):
        query = '''
            mutation MyMutation ($projectId: ID! $input: LeadCopyInputType!) {
              project(id: $projectId) {
                leadCopy(data: $input) {
                  ok
                  errors
                  result {
                    id
                    title
                    project
                    status
                    createdAt
                    createdBy {
                        id
                    }
                    modifiedBy {
                        id
                    }
                  }
                }
              }
            }
        '''
        member_user = UserFactory.create()
        member_user_only_protected = UserFactory.create()
        non_member_user = UserFactory.create()
        created_by_user = UserFactory.create()

        # Source Projects
        wa_source_project = ProjectFactory.create(
            title='With access Source Project')  # With access
        woa_source_project = ProjectFactory.create(
            title='Without access Source Project')  # Without access
        # Destination Projects
        wa_destination_project = ProjectFactory.create(
            title='With access Destination Project')  # With access
        woa_destination_project = ProjectFactory.create(
            title='Without access Destination Project')  # Without access
        # Assign access
        wa_source_project.add_member(member_user)
        wa_source_project.add_member(
            member_user_only_protected,
            role=self.project_role_reader_non_confidential)
        wa_destination_project.add_member(member_user)
        wa_destination_project.add_member(member_user_only_protected)
        woa_source_project.add_member(
            member_user,
            role=self.project_base_access)  # With no lead read access
        woa_source_project.add_member(
            member_user_only_protected,
            role=self.project_base_access)  # With no lead read access

        # Lead1 Info (Will be used later for testing)
        author1 = OrganizationFactory.create(title='author1')
        author2 = OrganizationFactory.create(title='author2')
        emm_entity = EmmEntityFactory.create(name='emm_entity_11')

        # Generate some leads in source projects.
        wa_lead_confidential = LeadFactory.create(
            title='Confidential Lead (with-access)',
            project=wa_source_project,
            source_type=Lead.SourceType.WEBSITE,
            url='http://confidential-lead.example.com',
            confidentiality=Lead.Confidentiality.CONFIDENTIAL,
        )
        wa_lead1 = LeadFactory.create(title='Lead 1 (with-access)',
                                      project=wa_source_project,
                                      source_type=Lead.SourceType.WEBSITE,
                                      url='http://example.com',
                                      created_by=created_by_user,
                                      status=Lead.Status.TAGGED)
        wa_lead2 = LeadFactory.create(title='Lead 2 (with-access)',
                                      project=wa_source_project,
                                      source_type=Lead.SourceType.WEBSITE,
                                      url='http://another.example.com')
        woa_lead3 = LeadFactory.create(title='Lead 3 (without-access)',
                                       project=woa_source_project,
                                       source_type=Lead.SourceType.WEBSITE,
                                       url='http://another-2.example.com')
        # Assign authors
        wa_lead1.authors.set([author1, author2])
        wa_lead2.authors.set([author1])
        woa_lead3.authors.set([author2])

        # Generating Foreign elements for wa_lead1
        wa_lead1_preview = LeadPreviewFactory.create(
            lead=wa_lead1, text_extract='This is a random text extarct')
        wa_lead1_image_preview = LeadPreviewImageFactory.create(
            lead=wa_lead1, file='test-file-123')
        LeadEMMTriggerFactory.create(
            lead=wa_lead1,
            emm_keyword='emm1',
            emm_risk_factor='risk1',
            count=22,
        )
        wa_lead1.emm_entities.set([emm_entity])

        # Generate some leads in destinations projects as well.
        LeadFactory.create(
            project=wa_destination_project,
            title=wa_lead2.title,
            source_type=wa_lead2.source_type,
            url=wa_lead2.url,
        )

        # test for single lead copy
        minput = {
            'projects': [
                wa_destination_project.id,  # Lead will be added here
                woa_destination_project.id,  # No Lead are added here
            ],
            'leads':
            [wa_lead_confidential.id, wa_lead1.id, wa_lead2.id, woa_lead3.id]
        }

        def _query_check(source_project, **kwargs):
            return self.query_check(query,
                                    minput=minput,
                                    variables={'projectId': source_project.pk},
                                    **kwargs)

        # without login
        _query_check(wa_source_project, assert_for_error=True)

        # with non_member user[destination_project]
        self.force_login(non_member_user)
        _query_check(wa_source_project, assert_for_error=True)

        # with member user (With non-confidential access)
        self.force_login(member_user_only_protected)

        woa_current_leads_count = woa_destination_project.lead_set.count()
        woa_current_leads_count = woa_destination_project.lead_set.count()
        # Call endpoint using no lead read access (no changes here)
        _query_check(woa_source_project, okay=False)
        woa_new_leads_count = woa_destination_project.lead_set.count()
        self.assertEqual(woa_current_leads_count, woa_new_leads_count)
        self.assertEqual(woa_current_leads_count, woa_new_leads_count)

        wa_current_leads_count = wa_destination_project.lead_set.count()
        woa_current_leads_count = woa_destination_project.lead_set.count()
        # Call endpoint
        new_leads = _query_check(
            wa_source_project)['data']['project']['leadCopy']['result']
        # lets make sure lead is copied to the destination project
        wa_new_count = wa_destination_project.lead_set.count()
        woa_new_leads_count = woa_destination_project.lead_set.count()
        # Only 1 since there is already another lead for wa_lead2 in wa_destination_project
        # confidential can't be copied for member_user_only_protected user.
        self.assertEqual(len(new_leads), 1, new_leads)
        self.assertEqual(wa_new_count, wa_current_leads_count + 1)
        self.assertEqual(woa_current_leads_count, woa_new_leads_count)

        wa_current_leads_count = wa_destination_project.lead_set.count()
        woa_current_leads_count = woa_destination_project.lead_set.count()
        # Call endpoint (again)
        _query_check(wa_source_project)
        wa_new_count = wa_destination_project.lead_set.count()
        woa_new_leads_count = woa_destination_project.lead_set.count()
        # No changes now since leads are already copied
        self.assertEqual(wa_new_count, wa_current_leads_count)
        self.assertEqual(woa_current_leads_count, woa_new_leads_count)

        self.force_login(member_user)  # With confidential access
        wa_current_leads_count = wa_destination_project.lead_set.count()
        woa_current_leads_count = woa_destination_project.lead_set.count()
        # Call endpoint
        _query_check(wa_source_project)
        # lets make sure lead is copied to the destination project
        wa_new_count = wa_destination_project.lead_set.count()
        woa_new_leads_count = woa_destination_project.lead_set.count()
        self.assertEqual(wa_new_count,
                         wa_current_leads_count + 1)  # 1 new confidential lead
        self.assertEqual(woa_current_leads_count, woa_new_leads_count)

        # Now check if copied leads are done correctly
        # make sure same lead is created for destination project
        copied_lead1 = wa_destination_project.lead_set.get(
            title=wa_lead1.title)
        self.assertEqual(copied_lead1.source_type, wa_lead1.source_type)
        self.assertEqual(copied_lead1.url, wa_lead1.url)
        self.assertEqual(copied_lead1.confidentiality,
                         wa_lead1.confidentiality)
        # lets check for the foreign key field copy
        self.assertEqual(copied_lead1.leadpreview.text_extract,
                         wa_lead1_preview.text_extract)
        self.assertEqual(
            list(copied_lead1.images.values_list('file', flat=True)),
            [wa_lead1_image_preview.file.name])
        self.assertEqual(
            list(
                copied_lead1.emm_triggers.values('emm_keyword',
                                                 'emm_risk_factor', 'count')),
            list(
                wa_lead1.emm_triggers.values('emm_keyword', 'emm_risk_factor',
                                             'count')),
        )
        self.assertEqual(
            list(copied_lead1.emm_entities.all()),
            [emm_entity],
        )
        # lets check for the updated fields after copy
        self.assertEqual(copied_lead1.created_by.id,
                         member_user_only_protected.id)
        self.assertEqual(copied_lead1.modified_by.id,
                         member_user_only_protected.id)
        self.assertEqual(copied_lead1.status, Lead.Status.NOT_TAGGED)
Exemplo n.º 29
0
    def test_recent_analysis_framework(self):
        # NOTE: This test includes the recent_analysis_framework based on project and source
        query = '''
                query MyQuery {
                  projectExploreStats {
                    topActiveFrameworks {
                      analysisFrameworkId
                      analysisFrameworkTitle
                      projectCount
                      sourceCount
                    }
                  }
                }
            '''

        # lets create some analysis_framework
        analysis_framework1 = AnalysisFrameworkFactory.create()
        analysis_framework2 = AnalysisFrameworkFactory.create()
        analysis_framework3 = AnalysisFrameworkFactory.create()
        analysis_framework4 = AnalysisFrameworkFactory.create()
        analysis_framework5 = AnalysisFrameworkFactory.create()
        analysis_framework6 = AnalysisFrameworkFactory.create()

        project1 = ProjectFactory.create(
            analysis_framework=analysis_framework1)
        project2 = ProjectFactory.create(
            analysis_framework=analysis_framework2)
        project3 = ProjectFactory.create(
            analysis_framework=analysis_framework1)
        project4 = ProjectFactory.create(
            analysis_framework=analysis_framework3)
        project5 = ProjectFactory.create(
            analysis_framework=analysis_framework4)
        project6 = ProjectFactory.create(
            analysis_framework=analysis_framework3)
        project7 = ProjectFactory.create(
            analysis_framework=analysis_framework1)
        project8 = ProjectFactory.create(
            analysis_framework=analysis_framework5)
        project9 = ProjectFactory.create(
            analysis_framework=analysis_framework6)

        # some lead for the project
        LeadFactory.create_batch(15, project=project1)
        LeadFactory.create_batch(13, project=project2)
        LeadFactory.create_batch(20, project=project3)
        LeadFactory.create_batch(20, project=project4)
        LeadFactory.create_batch(20, project=project5)
        LeadFactory.create_batch(30, project=project6)
        LeadFactory.create_batch(30, project=project7)
        LeadFactory.create_batch(30, project=project8)
        LeadFactory.create_batch(30, project=project9)

        content = self.query_check(query)

        self.assertEqual(
            len(content['data']['projectExploreStats']['topActiveFrameworks']),
            5, content)
        self.assertEqual(
            content['data']['projectExploreStats']['topActiveFrameworks'][0]
            ['analysisFrameworkId'], str(analysis_framework1.id))
        self.assertEqual(
            content['data']['projectExploreStats']['topActiveFrameworks'][0]
            ['projectCount'], 3)
        self.assertEqual(
            content['data']['projectExploreStats']['topActiveFrameworks'][0]
            ['sourceCount'], 65)
        self.assertEqual(
            content['data']['projectExploreStats']['topActiveFrameworks'][1]
            ['analysisFrameworkId'], str(analysis_framework3.id))
        self.assertEqual(
            content['data']['projectExploreStats']['topActiveFrameworks'][1]
            ['projectCount'], 2)
        self.assertEqual(
            content['data']['projectExploreStats']['topActiveFrameworks'][2]
            ['analysisFrameworkId'], str(analysis_framework5.id))
        self.assertEqual(
            content['data']['projectExploreStats']['topActiveFrameworks'][3]
            ['analysisFrameworkId'], str(analysis_framework6.id))
        self.assertEqual(
            content['data']['projectExploreStats']['topActiveFrameworks'][4]
            ['analysisFrameworkId'], str(analysis_framework4.id))
Exemplo n.º 30
0
    def test_leads_entries_query(self):
        query = '''
            query MyQuery ($id: ID!, $leadId: ID!) {
              project(id: $id) {
                analysisFramework {
                    id
                }
                lead(id: $leadId) {
                    id
                    entriesCount {
                      total
                      controlled
                    }
                    entries {
                        id
                    }
                  }
                }
              }
        '''
        af, af_new = AnalysisFrameworkFactory.create_batch(2)
        user = UserFactory.create()
        project = ProjectFactory.create(analysis_framework=af)
        project.add_member(user, role=self.project_role_member)
        lead = LeadFactory.create(project=project)

        controlled_entries = EntryFactory.create_batch(2,
                                                       lead=lead,
                                                       controlled=True)
        not_controlled_entries = EntryFactory.create_batch(3,
                                                           lead=lead,
                                                           controlled=False)

        def _query_check():
            return self.query_check(query,
                                    variables={
                                        'id': project.id,
                                        'leadId': lead.id
                                    })

        # -- With login
        self.force_login(user)
        response = _query_check()
        self.assertIdEqual(
            response['data']['project']['analysisFramework']['id'], af.pk)
        content = response['data']['project']['lead']
        self.assertIdEqual(content['id'], lead.pk, content)
        self.assertEqual(content['entriesCount']['total'], 5, content)
        self.assertEqual(content['entriesCount']['controlled'], 2, content)
        self.assertListIds(content['entries'],
                           [*controlled_entries, *not_controlled_entries],
                           content)

        # Now change AF
        project.analysis_framework = af_new
        project.save(update_fields=('analysis_framework', ))

        new_controlled_entries = EntryFactory.create_batch(4,
                                                           lead=lead,
                                                           controlled=True)
        new_not_controlled_entries = EntryFactory.create_batch(
            2, lead=lead, controlled=False)

        response = _query_check()
        self.assertIdEqual(
            response['data']['project']['analysisFramework']['id'], af_new.pk)
        content = response['data']['project']['lead']
        self.assertIdEqual(content['id'], lead.pk, content)
        self.assertEqual(content['entriesCount']['total'], 6, content)
        self.assertEqual(content['entriesCount']['controlled'], 4, content)
        self.assertListIds(
            content['entries'],
            [*new_controlled_entries, *new_not_controlled_entries], content)