Ejemplo n.º 1
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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
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))
Ejemplo n.º 4
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)
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
    def test(self):
        entry1_1 = EntryFactory.create(**self.entry_create_kwargs, lead=self.lead1)
        entry2_1 = EntryFactory.create(**self.entry_create_kwargs, lead=self.lead2)
        entry3_1 = EntryFactory.create(**self.entry_create_kwargs, lead=self.lead3)
        entry3_2 = EntryFactory.create(**self.entry_create_kwargs, lead=self.lead3)

        # Create attributes for multiselect (LIST Filter)
        EntryAttributeFactory.create(entry=entry1_1, widget=self.widget_multiselect, data={'value': ['key-101', 'key-102']})
        EntryAttributeFactory.create(entry=entry2_1, widget=self.widget_multiselect, data={'value': ['key-102', 'key-103']})
        # Create attributes for time (NUMBER Filter)
        EntryAttributeFactory.create(entry=entry1_1, widget=self.widget_number, data={'value': 10001})
        EntryAttributeFactory.create(entry=entry3_1, widget=self.widget_number, data={'value': 10002})
        # Create attributes for date range (INTERSECTS Filter)
        EntryAttributeFactory.create(
            entry=entry2_1,
            widget=self.widget_date_range,
            data={'value': {'startDate': '2020-01-10', 'endDate': '2020-01-20'}},
        )
        EntryAttributeFactory.create(
            entry=entry3_1,
            widget=self.widget_date_range,
            data={'value': {'startDate': '2020-01-10', 'endDate': '2020-02-20'}},
        )
        EntryAttributeFactory.create(
            entry=entry3_2,
            widget=self.widget_date_range,
            data={'value': {'startDate': '2020-01-15', 'endDate': '2020-01-25'}},
        )
        # Create attributes for text (TEXT Filter)
        EntryAttributeFactory.create(entry=entry1_1, widget=self.widget_text, data={'value': 'This is a test 1'})
        EntryAttributeFactory.create(entry=entry3_1, widget=self.widget_text, data={'value': 'This is a test 2'})
        # Create attributes for GEO (LIST Filter)
        EntryAttributeFactory.create(
            entry=entry1_1, widget=self.widget_geo,
            data={'value': [self.geo_area_3_2.pk]}  # Leaf tagged
        )
        EntryAttributeFactory.create(
            entry=entry2_1, widget=self.widget_geo,
            data={'value': [self.geo_area_1.pk]}  # Root tagged
        )
        EntryAttributeFactory.create(
            entry=entry3_1, widget=self.widget_geo,
            data={'value': [self.geo_area_2_1.pk]}  # Middle child tagged
        )
        EntryAttributeFactory.create(
            entry=entry3_2, widget=self.widget_geo,
            data={'value': [self.geo_area_1.pk, self.geo_area_3_2.pk]}  # Middle child tagged + leaf node
        )

        # Some entries with different AF
        other_entry = EntryFactory.create(lead=self.lead1, analysis_framework=AnalysisFrameworkFactory.create(title='Other'))
        EntryAttributeFactory.create(
            entry=other_entry, widget=self.widget_multiselect, data={'value': ['key-101', 'key-102']})
        EntryAttributeFactory.create(entry=other_entry, widget=self.widget_number, data={'value': 10002})
        EntryAttributeFactory.create(
            entry=other_entry, widget=self.widget_geo,
            data={'value': [self.geo_area_3_2.pk]}  # Leaf tagged
        )

        # Some leads/entries in other projects
        other_leads = LeadFactory.create_batch(3, project=ProjectFactory.create(analysis_framework=self.af))
        [EntryFactory.create_batch(3, lead=lead) for lead in other_leads]

        # -- With login
        self.force_login(self.user)

        for filter_name, filter_data, expected_entries in [
            # NUMBER Filter Cases
            (
                'number-filter-1',
                [
                    {
                        'filterKey': self.widget_number.key,
                        'value': '10001',
                        'valueGte': '10002',  # This is ignored when value is provided
                        'valueLte': '10005',  # This is ignored when value is provided
                    },
                ],
                [entry1_1],
            ),
            (
                'number-filter-2',
                [
                    {
                        'filterKey': self.widget_number.key,
                        'valueGte': '10001',
                        'valueLte': '10005',
                    },
                ],
                [entry1_1, entry3_1],
            ),
            (
                'number-filter-3',
                [
                    {
                        'filterKey': self.widget_number.key,
                        'valueLte': '10001',
                    },
                ],
                [entry1_1],
            ),
            (
                'number-filter-4',
                [
                    {
                        'filterKey': self.widget_number.key,
                        'valueGte': '10002',
                    },
                ],
                [entry3_1],
            ),

            # TEXT Filter Cases
            (
                'text-filter-1',
                [
                    {
                        'filterKey': self.widget_text.key,
                        'value': 'This is a test',
                        'valueGte': '10002',  # This is ignored
                    },
                ],
                [entry1_1, entry3_1],
            ),
            (
                'text-filter-2',
                [
                    {
                        'filterKey': self.widget_text.key,
                        'value': 'This is a test 1',
                        'valueLte': '10002',  # This is ignored
                    },
                ],
                [entry1_1],
            ),

            # INTERSECTS TODO: May need more test cases
            (
                'intersect-filter-1',
                [
                    {
                        'filterKey': self.widget_date_range.key,
                        'value': '2020-01-10',
                        # 'valueLte': '2020-01-01',  # TODO:
                        # 'valueGte': '2020-01-30',  # TODO:
                    },
                ],
                [entry2_1, entry3_1],
            ),
            (
                'intersect-filter-2',
                [
                    {
                        'filterKey': self.widget_date_range.key,
                        'valueGte': '2020-01-01',
                        'valueLte': '2020-01-30',
                    },
                ],
                [entry2_1, entry3_1, entry3_2],
            ),
            (
                'intersect-filter-3',
                [
                    {
                        'filterKey': self.widget_date_range.key,
                        'valueGte': '2020-01-30',  # Only one is ignored
                    },
                ],
                [entry1_1, entry2_1, entry3_1, entry3_2],
            ),

            # LIST Filter
            (
                'list-filter-1',
                [
                    {
                        'filterKey': self.widget_multiselect.key,
                        'value': '13',  # This is ignored
                    },
                ],
                [entry1_1, entry2_1, entry3_1, entry3_2],
            ),
            (
                'list-filter-2',
                [
                    {
                        'filterKey': self.widget_multiselect.key,
                        'valueList': ['key-101', 'key-102'],
                    },
                ],
                [entry1_1, entry2_1],
            ),
            (
                'list-filter-3',
                [
                    {
                        'filterKey': self.widget_multiselect.key,
                        'valueList': ['key-101', 'key-102'],
                        'useAndOperator': True,
                    },
                ],
                [entry1_1],
            ),
            (
                'list-filter-4',
                [
                    {
                        'filterKey': self.widget_multiselect.key,
                        'valueList': ['key-101', 'key-102'],
                        'useAndOperator': True,
                        'useExclude': True,
                    },
                ],
                [entry2_1, entry3_1, entry3_2],
            ),
            (
                'list-filter-5',
                [
                    {
                        'filterKey': self.widget_multiselect.key,
                        'valueList': ['key-101', 'key-102'],
                        'useExclude': True,
                    },
                ],
                [entry3_1, entry3_2],
            ),

            # GEO (LIST) Filter
            (
                'geo-filter-1',
                [
                    {
                        'filterKey': self.widget_geo.key,
                        'valueList': [self.geo_area_1.pk],
                    },
                ],
                [entry2_1, entry3_2],
            ),
            (
                'geo-filter-2',
                [
                    {
                        'filterKey': self.widget_geo.key,
                        'valueList': [self.geo_area_1.pk],
                        'includeSubRegions': True,
                    },
                ],
                [entry1_1, entry2_1, entry3_1, entry3_2],
            ),
            (
                'geo-filter-3',
                [
                    {
                        'filterKey': self.widget_geo.key,
                        'valueList': [self.geo_area_1.pk],
                        'includeSubRegions': True,
                        'useExclude': True,
                    },
                ],
                [],
            ),
            (
                'geo-filter-4',
                [
                    {
                        'filterKey': self.widget_geo.key,
                        'valueList': [self.geo_area_2_2.pk],
                        'includeSubRegions': True,
                    },
                ],
                [entry1_1, entry3_2],
            ),
            (
                'geo-filter-5',
                [
                    {
                        'filterKey': self.widget_geo.key,
                        'valueList': [self.geo_area_2_2.pk],
                        'includeSubRegions': True,
                        'useExclude': True,
                    },
                ],
                [entry2_1, entry3_1],
            )
        ]:
            # Lead filter test
            content = self.query_check(
                self.entries_query,
                variables={'projectId': self.project.id, 'filterableData': filter_data},
            )
            self.assertListIds(
                content['data']['project']['entries']['results'], expected_entries,
                {'response': content, 'filter': filter_data, 'filter_name': filter_name}
            )
            # Lead filter test
            expected_leads = set([entry.lead for entry in expected_entries])
            content = self.query_check(
                TestLeadQuerySchema.lead_filter_query,
                variables={
                    'projectId': self.project.id,
                    'hasEntries': True,
                    'entriesFilterData': {
                        'filterableData': filter_data,
                    }
                }
            )
            self.assertListIds(
                content['data']['project']['leads']['results'], expected_leads,
                {'response': content, 'filter': filter_data, 'filter_name': filter_name}
            )
Ejemplo n.º 7
0
    def test_entry_query_filter(self):
        query = '''
            query MyQuery (
                $projectId: ID!
                $leadAuthoringOrganizationTypes: [ID!]
                $commentStatus: EntryFilterCommentStatusEnum
                $controlled: Boolean
                $createdAt: DateTime
                $createdAtGte: DateTime
                $createdAtLte: DateTime
                $createdBy: [ID!]
                $entriesId: [ID!]
                $entryTypes: [EntryTagTypeEnum!]
                $excerpt: String
                $filterableData: [EntryFilterDataType!]
                $geoCustomShape: String
                $leadAssignees: [ID!]
                $leadConfidentialities: [LeadConfidentialityEnum!]
                $leadGroupLabel: String
                $leadPriorities: [LeadPriorityEnum!]
                $leadPublishedOn: Date
                $leadPublishedOnGte: Date
                $leadPublishedOnLte: Date
                $leads: [ID!]
                $leadStatuses: [LeadStatusEnum!]
                $leadTitle: String
                $modifiedAt: DateTime
                $modifiedBy: [ID!]
                $projectEntryLabels: [ID!]
            ) {
              project(id: $projectId) {
                entries (
                    commentStatus: $commentStatus
                    controlled: $controlled
                    createdAt: $createdAt
                    createdAtGte: $createdAtGte
                    createdAtLte: $createdAtLte
                    createdBy: $createdBy
                    entriesId: $entriesId
                    entryTypes: $entryTypes
                    excerpt: $excerpt
                    filterableData: $filterableData
                    geoCustomShape: $geoCustomShape
                    modifiedAt: $modifiedAt
                    modifiedBy: $modifiedBy
                    projectEntryLabels: $projectEntryLabels
                    # Lead filters
                    leadAuthoringOrganizationTypes: $leadAuthoringOrganizationTypes
                    leadAssignees: $leadAssignees
                    leadConfidentialities: $leadConfidentialities
                    leadGroupLabel: $leadGroupLabel
                    leadPriorities: $leadPriorities
                    leadPublishedOn: $leadPublishedOn
                    leadPublishedOnGte: $leadPublishedOnGte
                    leadPublishedOnLte: $leadPublishedOnLte
                    leads: $leads
                    leadStatuses: $leadStatuses
                    leadTitle: $leadTitle
                ) {
                  results {
                    id
                  }
                }
              }
            }
        '''

        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)
        # 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,
            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,
            authors=[org1, org3],
            priority=Lead.Priority.LOW,
        )
        lead4 = LeadFactory.create(
            project=project,
            title='Sample 2',
            authors=[org1],
            priority=Lead.Priority.MEDIUM,
        )

        other_project = ProjectFactory.create(analysis_framework=af)
        other_lead = LeadFactory.create(project=other_project)
        outside_entry = EntryFactory.create(project=other_project, analysis_framework=af, lead=other_lead)
        entry1_1 = EntryFactory.create(
            project=project, analysis_framework=af, lead=lead1, entry_type=Entry.TagType.EXCERPT, controlled=False)
        entry2_1 = EntryFactory.create(
            project=project, analysis_framework=af, lead=lead2, entry_type=Entry.TagType.IMAGE, controlled=True)
        entry3_1 = EntryFactory.create(
            project=project, analysis_framework=af, lead=lead3, entry_type=Entry.TagType.EXCERPT, controlled=False)
        entry4_1 = EntryFactory.create(
            project=project, analysis_framework=af, lead=lead4, entry_type=Entry.TagType.EXCERPT, controlled=False)
        # Change lead1 status to TAGGED
        lead1.status = Lead.Status.TAGGED
        lead1.save(update_fields=['status'])

        # Some leads/entries in other projects
        other_leads = LeadFactory.create_batch(3, project=ProjectFactory.create(analysis_framework=af))
        [EntryFactory.create_batch(3, lead=lead) for lead in other_leads]

        # -- With login
        self.force_login(user)

        # TODO: Add direct test for filter_set as well (is used within export)
        for filter_data, expected_entries in [
            ({'controlled': True}, [entry2_1]),
            ({'controlled': False}, [entry1_1, entry3_1, entry4_1]),
            ({'entriesId': [entry1_1.id, entry2_1.id, outside_entry.id]}, [entry1_1, entry2_1]),
            ({'entryTypes': [self.genum(Entry.TagType.EXCERPT)]}, [entry1_1, entry3_1, entry4_1]),
            (
                {'entryTypes': [self.genum(Entry.TagType.EXCERPT), self.genum(Entry.TagType.IMAGE)]},
                [entry1_1, entry2_1, entry3_1, entry4_1],
            ),
            # TODO: ({'projectEntryLabels': []}, []),
            # TODO: ({'geoCustomShape': []}, []),
            # TODO: After adding comment({'commentStatus': self.genum(EntryFilterMixin.CommentStatus.RESOLVED)}, []),
            # Lead filters
            ({'leadAuthoringOrganizationTypes': [org_type2.pk]}, [entry1_1, entry2_1, entry3_1]),
            ({'leadAuthoringOrganizationTypes': [org_type1.pk, org_type2.pk]}, [entry1_1, entry2_1, entry3_1, entry4_1]),
            ({'leads': [lead1.pk, lead2.pk]}, [entry1_1, entry2_1]),
            ({'leadTitle': 'test'}, [entry1_1, entry2_1]),
            ({'leadAssignees': [member2.pk]}, [entry2_1]),
            ({'leadAssignees': [member1.pk, member2.pk]}, [entry1_1, entry2_1]),
            ({'leadConfidentialities': self.genum(Lead.Confidentiality.CONFIDENTIAL)}, [entry1_1, entry3_1]),
            ({'leadPriorities': [self.genum(Lead.Priority.HIGH)]}, [entry1_1, entry2_1]),
            (
                {'leadPriorities': [self.genum(Lead.Priority.LOW), self.genum(Lead.Priority.HIGH)]},
                [entry1_1, entry2_1, entry3_1]
            ),
            ({'leadStatuses': [self.genum(Lead.Status.NOT_TAGGED)]}, []),
            ({'leadStatuses': [self.genum(Lead.Status.IN_PROGRESS)]}, [entry2_1, entry3_1, entry4_1]),
            ({'leadStatuses': [self.genum(Lead.Status.TAGGED)]}, [entry1_1]),
            (
                {'leadStatuses': [self.genum(Lead.Status.IN_PROGRESS), self.genum(Lead.Status.TAGGED)]},
                [entry1_1, entry2_1, entry3_1, entry4_1]
            ),
            # TODO: Common filters
            # ({'excerpt': []}, []),
            # ({'modifiedAt': []}, []),
            # ({'modifiedBy': []}, []),
            # ({'createdAt': []}, []),
            # ({'createdAtGte': []}, []),
            # ({'createdAtLte': []}, []),
            # ({'createdBy': []}, []),
            # ({'leadGroupLabel': []}, []),
            # ({'leadPublishedOn': []}, []),
            # ({'leadPublishedOnGte': []}, []),
            # ({'leadPublishedOnLte': []}, []),
        ]:
            # Entry filter test
            content = self.query_check(query, variables={'projectId': project.id, **filter_data})
            self.assertListIds(
                content['data']['project']['entries']['results'], expected_entries,
                {'response': content, 'filter': filter_data}
            )
            # Lead filter test
            expected_leads = set([entry.lead for entry in expected_entries])
            content = self.query_check(
                TestLeadQuerySchema.lead_filter_query,
                variables={
                    'projectId': project.id,
                    'hasEntries': True,
                    'entriesFilterData': filter_data,
                }
            )
            self.assertListIds(
                content['data']['project']['leads']['results'], expected_leads,
                {'response': content, 'filter': filter_data},
            )