Ejemplo n.º 1
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.º 2
0
 def test_search_filter(self):
     ProjectFactory.create(title='one')
     p2 = ProjectFactory.create(title='two')
     p3 = ProjectFactory.create(title='twoo')
     obtained = self.filter_class(data=dict(search='tw')).qs
     expected = [p2, p3]
     self.assertQuerySetIdEqual(expected, obtained)
Ejemplo n.º 3
0
    def test_project_query_has_assesment_af(self):
        query = '''
            query MyQuery {
              projects(ordering: "id") {
                  results {
                    id
                    hasAnalysisFramework
                    hasAssessmentTemplate
                  }
              }
            }
        '''
        user = UserFactory.create()
        analysis_framework = AnalysisFrameworkFactory.create()
        assessment_template = AssessmentTemplateFactory.create()
        project1 = ProjectFactory.create(
            analysis_framework=analysis_framework,
            assessment_template=assessment_template)
        project2 = ProjectFactory.create(
            analysis_framework=analysis_framework, )
        project3 = ProjectFactory.create(
            assessment_template=assessment_template)
        self.force_login(user)

        projects = self.query_check(query)['data']['projects']['results']
        for index, (_id, has_af, has_ary_template) in enumerate([
            (project1.pk, True, True),
            (project2.pk, True, False),
            (project3.pk, False, True),
        ]):
            self.assertIdEqual(projects[index]['id'], _id, projects)
            self.assertEqual(projects[index]['hasAnalysisFramework'], has_af,
                             projects)
            self.assertEqual(projects[index]['hasAssessmentTemplate'],
                             has_ary_template, projects)
Ejemplo n.º 4
0
 def setUp(self):
     super().setUp()
     self.project = ProjectFactory.create()
     self.user = UserFactory.create()
     self.another_user = UserFactory.create()
     self.project.add_member(self.user)
     self.uc1, self.uc2 = UnifiedConnectorFactory.create_batch(
         2, project=self.project)
     self.fake_lead = ConnectorLeadFactory.create()
     # NOTE: Some other as noise, making sure they don't conflict with others
     another_project_with_access = ProjectFactory.create()
     another_project_without_access = ProjectFactory.create()
     uc_wc = UnifiedConnectorFactory.create(
         project=another_project_with_access)
     uc_wtc = UnifiedConnectorFactory.create(
         project=another_project_without_access)
     uc_wc_source = ConnectorSourceFactory.create(
         unified_connector=uc_wc, source=ConnectorSource.Source.RELIEF_WEB)
     uc_wtc_source = ConnectorSourceFactory.create(
         unified_connector=uc_wtc, source=ConnectorSource.Source.RELIEF_WEB)
     ConnectorSourceLeadFactory.create_batch(2,
                                             source=uc_wc_source,
                                             connector_lead=self.fake_lead)
     ConnectorSourceLeadFactory.create_batch(2,
                                             source=uc_wtc_source,
                                             connector_lead=self.fake_lead)
Ejemplo n.º 5
0
    def test_get_1_empty(self):
        """既に存在するプロジェクトIDでアクセスすると、そのデータが表示される"""
        project = ProjectFactory(name="Spam", description="Ham")
        project.save()

        response = self._callFUT(request(), str(project.id))
        assert response.status_code == 200
        assert project.name == "Spam"
        assert project.description == "Ham"
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
    def test_analysis_framework_filter(self):
        af1, af2, af3 = AnalysisFrameworkFactory.create_batch(3)
        p1 = ProjectFactory.create(analysis_framework=af1)
        p2 = ProjectFactory.create(analysis_framework=af2)
        ProjectFactory.create(analysis_framework=af3)

        obtained = self.filter_class(data=dict(
            analysis_frameworks=[af1.id, af2.id])).qs
        expected = [p2, p1]
        self.assertQuerySetIdEqual(expected, obtained)
Ejemplo n.º 8
0
    def test_public_projects_by_region(self):
        query = '''
            query MyQuery ($projectFilter: RegionProjectFilterData) {
              publicProjectsByRegion (projectFilter: $projectFilter) {
               totalCount
               results {
                 id
                 projectsId
                 centroid
               }
              }
            }
        '''
        fake_centroid = Point(1, 2)
        region1 = RegionFactory.create(public=False, centroid=fake_centroid)
        region2 = RegionFactory.create(centroid=fake_centroid)
        region3 = RegionFactory.create(centroid=fake_centroid)
        region4 = RegionFactory.create(public=False, centroid=fake_centroid)
        RegionFactory.create()  # No Centroid ( This will not show)
        project1 = ProjectFactory.create(is_private=False,
                                         regions=[region1, region2],
                                         title='Test Nepal')
        ProjectFactory.create(is_private=False,
                              regions=[region3],
                              title='Test Canada')
        project2 = ProjectFactory.create(is_private=True,
                                         regions=[region4],
                                         title='Test Brazil')

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

        content = self.query_check(query)
        self.assertEqual(
            content['data']['publicProjectsByRegion']['totalCount'], 3,
            content)

        # test for project filter
        content = _query_check({'ids': [project1.pk]
                                })['data']['publicProjectsByRegion']
        self.assertEqual(content['totalCount'], 2, content)

        content = _query_check({'ids': [project1.pk, project2.pk]
                                })['data']['publicProjectsByRegion']
        self.assertEqual(content['totalCount'], 2, content)

        content = _query_check({'search':
                                'Canada'})['data']['publicProjectsByRegion']
        self.assertEqual(content['totalCount'], 1, content)

        content = _query_check({'search':
                                'Brazil'})['data']['publicProjectsByRegion']
        self.assertEqual(content['totalCount'], 0,
                         content)  # Private projects are not shown
Ejemplo n.º 9
0
 def test_status_filter(self):
     p1, p2 = ProjectFactory.create_batch(2, status=Project.Status.ACTIVE)
     p3 = ProjectFactory.create(status=Project.Status.INACTIVE)
     obtained = self.filter_class(data=dict(
         status=Project.Status.ACTIVE.value)).qs
     expected = [p1, p2]
     self.assertQuerySetIdEqual(expected, obtained)
     obtained = self.filter_class(data=dict(
         status=Project.Status.INACTIVE.value)).qs
     expected = [p3]
     self.assertQuerySetIdEqual(expected, obtained)
Ejemplo n.º 10
0
    def test_exports_query(self):
        query = '''
            query MyQuery ($id: ID!) {
              project(id: $id) {
                exports {
                  page
                  pageSize
                  totalCount
                  results {
                    id
                    title
                  }
                }
              }
            }
        '''
        project = ProjectFactory.create()
        project2 = ProjectFactory.create()
        user = UserFactory.create()
        user2 = UserFactory.create()
        project.add_member(user,
                           role=self.project_role_reader_non_confidential)
        project2.add_member(user2,
                            role=self.project_role_reader_non_confidential)
        ExportFactory.create_batch(6, project=project, exported_by=user)
        ExportFactory.create_batch(8, project=project2, exported_by=user2)

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

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

        # --- With login
        self.force_login(user)
        content = _query_check()
        self.assertEqual(content['data']['project']['exports']['totalCount'],
                         6, content)
        self.assertEqual(len(content['data']['project']['exports']['results']),
                         6, content)

        # --- With login by user whose has not exported the export
        self.force_login(user2)
        content = _query_check()
        self.assertEqual(content['data']['project']['exports']['totalCount'],
                         0, content)
        self.assertEqual(len(content['data']['project']['exports']['results']),
                         0, content)
Ejemplo n.º 11
0
    def test_export_query(self):
        """
        Test export for project
        """
        query = '''
            query MyQuery ($projectId: ID! $exportId: ID!) {
              project(id: $projectId) {
                export (id: $exportId) {
                  id
                  title
                }
              }
            }
        '''

        project = ProjectFactory.create()
        project2 = ProjectFactory.create()
        user = UserFactory.create()
        user2 = UserFactory.create()
        project.add_member(user,
                           role=self.project_role_reader_non_confidential)
        project2.add_member(user2,
                            role=self.project_role_reader_non_confidential)
        export = ExportFactory.create(project=project, exported_by=user)
        other_export = ExportFactory.create(project=project2,
                                            exported_by=user2)

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

        # -- Without login
        _query_check(export, assert_for_error=True)

        # --- With login
        self.force_login(user)
        content = _query_check(export)
        self.assertNotEqual(content['data']['project']['export'], None,
                            content)
        self.assertEqual(content['data']['project']['export']['id'],
                         str(export.id))

        self.force_login(user)
        content = _query_check(other_export)
        self.assertEqual(content['data']['project']['export'], None, content)
Ejemplo n.º 12
0
    def test_project_query_filter(self):
        query = '''
            query MyQuery ($isCurrentUserMember: Boolean!) {
              projects(isCurrentUserMember: $isCurrentUserMember) {
                page
                pageSize
                totalCount
                results {
                  id
                  title
                  isPrivate
                  currentUserRole
                }
              }
            }
        '''

        user = UserFactory.create()
        project1 = ProjectFactory.create()
        project2 = ProjectFactory.create(is_private=True)
        project3 = ProjectFactory.create()
        ProjectFactory.create(is_private=True)

        # Add user to project1 only (one normal + one private)
        project1.add_member(user)
        project2.add_member(user)

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

        # -- With login
        self.force_login(user)

        # project without membership
        content = self.query_check(query,
                                   variables={'isCurrentUserMember': True})
        self.assertEqual(content['data']['projects']['totalCount'], 2, content)
        self.assertListIds(content['data']['projects']['results'],
                           [project1, project2], content)
        # project with membership
        content = self.query_check(query,
                                   variables={'isCurrentUserMember': False})
        self.assertEqual(content['data']['projects']['totalCount'], 1,
                         content)  # Private will not show here
        self.assertListIds(content['data']['projects']['results'], [project3],
                           content)
Ejemplo n.º 13
0
    def test_project_allowed_permissions(self):
        query = '''
              query MyQuery {
                projects {
                  results {
                   id
                   allowedPermissions
                  }
                }
              }
        '''
        project1, project2 = ProjectFactory.create_batch(2)
        user = UserFactory.create()
        project1.add_member(user, badges=[])
        project2.add_member(user, badges=[ProjectMembership.BadgeType.QA])

        self.force_login(user)
        content_projects = self.query_check(
            query)['data']['projects']['results']
        QA_PERMISSION = self.genum(PP.Permission.CAN_QUALITY_CONTROL)
        content_projects_permissions = {
            int(pdata['id']): pdata['allowedPermissions']
            for pdata in content_projects
        }
        self.assertEqual(len(content_projects), 2, content_projects)
        self.assertNotIn(QA_PERMISSION,
                         content_projects_permissions[project1.pk],
                         content_projects)
        self.assertIn(QA_PERMISSION, content_projects_permissions[project2.pk],
                      content_projects)
Ejemplo n.º 14
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),
        ]
Ejemplo n.º 15
0
    def test_project_join_request_reject(self):
        user = UserFactory.create()
        user2 = UserFactory.create()
        project = ProjectFactory.create()
        project.add_member(user, role=self.project_role_admin)
        join_request = ProjectJoinRequestFactory.create(requested_by=user2,
                                                        project=project,
                                                        role=ProjectRole.get_default_role(),
                                                        status=ProjectJoinRequest.Status.PENDING)
        minput = dict(status=self.genum(ProjectJoinRequest.Status.REJECTED))
        # without login
        self.query_check(
            self.projet_accept_reject_mutation,
            minput=minput,
            variables={'projectId': project.id, 'joinRequestId': join_request.id},
            assert_for_error=True
        )

        # with login
        self.force_login(user)
        content = self.query_check(self.projet_accept_reject_mutation, minput=minput,
                                   variables={'projectId': project.id, 'joinRequestId': join_request.id})
        self.assertEqual(
            content['data']['project']['acceptRejectProject']['result']['status'],
            self.genum(ProjectJoinRequest.Status.REJECTED),
            content
        )
Ejemplo n.º 16
0
    def test_projects_query(self):
        """
        Test private + non-private project list behaviour
        """
        query = '''
            query MyQuery {
              projects (ordering: "id") {
                page
                pageSize
                totalCount
                results {
                  id
                  status
                  title
                  isPrivate
                  description
                  currentUserRole
                }
              }
            }
        '''

        user = UserFactory.create()
        public_project = ProjectFactory.create()
        private_project = ProjectFactory.create(is_private=True)

        # -- Without login
        self.query_check(query, assert_for_error=True)

        # -- With login
        self.force_login(user)

        # --- non-member user (only public project is listed)
        content = self.query_check(query)
        self.assertEqual(content['data']['projects']['totalCount'], 1, content)
        self.assertEqual(content['data']['projects']['results'][0]['id'],
                         str(public_project.pk), content)

        # --- member user (all public project is listed)
        public_project.add_member(user)
        private_project.add_member(user)
        content = self.query_check(query)
        self.assertEqual(content['data']['projects']['totalCount'], 2, content)
        self.assertEqual(content['data']['projects']['results'][0]['id'],
                         str(public_project.pk), content)
        self.assertEqual(content['data']['projects']['results'][1]['id'],
                         str(private_project.pk), content)
Ejemplo n.º 17
0
 def test_search_filter(self):
     project = ProjectFactory.create()
     LeadGroupFactory.create(title='one', project=project)
     lg2 = LeadGroupFactory.create(title='two', project=project)
     lg3 = LeadGroupFactory.create(title='twoo', project=project)
     obtained = self.filter_class(data=dict(search='tw')).qs
     expected = [lg2, lg3]
     self.assertQuerySetIdEqual(expected, obtained)
Ejemplo n.º 18
0
 def test_join_private_project(self):
     user = UserFactory.create()
     project = ProjectFactory.create(is_private=True)
     reason = fuzzy.FuzzyText(length=50).fuzz()
     minput = dict(project=project.id, reason=reason)
     self.force_login(user)
     content = self.query_check(self.project_join_mutation, minput=minput, okay=False)
     self.assertEqual(len(content['data']['joinProject']['errors']), 1, content)
Ejemplo n.º 19
0
    def test_analysis_framework_list(self):
        query = '''
            query MyQuery {
              analysisFrameworks (ordering: "id") {
                page
                pageSize
                totalCount
                results {
                  id
                  title
                  description
                  isPrivate
                }
              }
            }
        '''

        user = UserFactory.create()
        private_af = AnalysisFrameworkFactory.create(is_private=True)
        normal_af = AnalysisFrameworkFactory.create()
        member_af = AnalysisFrameworkFactory.create()
        member_af.add_member(user)

        # Without login
        self.query_check(query, assert_for_error=True)

        # With login
        self.force_login(user)

        content = self.query_check(query)
        results = content['data']['analysisFrameworks']['results']
        self.assertEqual(content['data']['analysisFrameworks']['totalCount'],
                         2)
        self.assertIdEqual(results[0]['id'], normal_af.id)
        self.assertIdEqual(results[1]['id'], member_af.id)
        self.assertNotIn(str(private_af.id),
                         [d['id']
                          for d in results])  # Can't see private project.

        project = ProjectFactory.create(analysis_framework=private_af)
        # It shouldn't list private AF after adding to a project.
        content = self.query_check(query)
        results = content['data']['analysisFrameworks']['results']
        self.assertEqual(content['data']['analysisFrameworks']['totalCount'],
                         2)
        self.assertNotIn(str(private_af.id),
                         [d['id']
                          for d in results])  # Can't see private project.

        project.add_member(user)
        # It should list private AF after user is member of the project.
        content = self.query_check(query)
        results = content['data']['analysisFrameworks']['results']
        self.assertEqual(content['data']['analysisFrameworks']['totalCount'],
                         3)
        self.assertIn(str(private_af.id),
                      [d['id']
                       for d in results])  # Can see private project now.
Ejemplo n.º 20
0
 def setUp(self):
     super().setUp()
     self.project = ProjectFactory.create()
     self.member_user = UserFactory.create()
     self.non_member_user = UserFactory.create()
     self.readonly_member_user = UserFactory.create()
     self.project.add_member(self.member_user)
     self.project.add_member(self.readonly_member_user,
                             role=self.project_role_reader_non_confidential)
Ejemplo n.º 21
0
 def test_export_path_generation(self):
     MOCK_TIME_STR = '20211205'
     MOCK_RANDOM_STRING = 'random-string'
     user = UserFactory.create()
     project = ProjectFactory.create()
     common_args = {
         'type': Export.DataType.ENTRIES,
         'exported_by': user,
         'project': project,
     }
     with \
             patch('export.tasks.get_random_string') as get_random_string_mock, \
             patch('export.models.timezone') as timezone_mock:
         get_random_string_mock.return_value = MOCK_RANDOM_STRING
         timezone_mock.now.return_value.strftime.return_value = MOCK_TIME_STR
         for export, expected_title, expected_filename, _type in [
             (
                 ExportFactory(
                     title='',
                     format=Export.Format.DOCX,
                     export_type=Export.ExportType.REPORT,
                     **common_args
                 ),
                 f'{MOCK_TIME_STR} DEEP Entries General Export',
                 f'{MOCK_TIME_STR} DEEP Entries General Export.docx',
                 'without-title',
             ),
             (
                 ExportFactory(
                     title='test 123',
                     format=Export.Format.PDF,
                     export_type=Export.ExportType.REPORT,
                     **common_args,
                 ),
                 'test 123',
                 'test 123.pdf',
                 'with-title-01',
             ),
             (
                 ExportFactory(
                     title='test 321',
                     format=Export.Format.JSON,
                     export_type=Export.ExportType.JSON,
                     is_preview=True,
                     **common_args,
                 ),
                 'test 321',
                 '(Preview) test 321.json',
                 'with-title-02',
             ),
         ]:
             export.save()
             # generated_title = Export.generate_title(export.type, export.format)
             # export.title = export.title or generated_title  # This is automatically done on export save (mocking here)
             generated_filename = get_export_filename(export)
             self.assertEqual(export.title, expected_title, _type)
             self.assertEqual(generated_filename, f'{MOCK_RANDOM_STRING}/{expected_filename}', _type)
Ejemplo n.º 22
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.º 23
0
    def test_analysis_framework(self):
        query = '''
            query MyQuery ($id: ID!) {
              analysisFramework(id: $id) {
                id
                currentUserRole
                description
                isPrivate
                title
              }
            }
        '''

        user = UserFactory.create()
        private_af = AnalysisFrameworkFactory.create(is_private=True)
        normal_af = AnalysisFrameworkFactory.create()
        member_af = AnalysisFrameworkFactory.create()
        member_af.add_member(user)
        # Without login
        self.query_check(query,
                         assert_for_error=True,
                         variables={'id': normal_af.pk})

        # With login
        self.force_login(user)

        # Should work for normal AF
        response = self.query_check(query,
                                    variables={'id': normal_af.pk
                                               })['data']['analysisFramework']
        self.assertIdEqual(response['id'], normal_af.id, response)
        self.assertEqual(response['isPrivate'], False, response)
        # Should work for member AF
        response = self.query_check(query,
                                    variables={'id': member_af.pk
                                               })['data']['analysisFramework']
        self.assertIdEqual(response['id'], member_af.id, response)
        self.assertEqual(response['isPrivate'], False, response)
        # Shouldn't work for non-member private AF
        response = self.query_check(query,
                                    variables={'id': private_af.pk
                                               })['data']['analysisFramework']
        self.assertEqual(response, None, response)
        # Shouldn't work for non-member private AF even if there is a project attached
        project = ProjectFactory.create(analysis_framework=private_af)
        response = self.query_check(query,
                                    variables={'id': private_af.pk
                                               })['data']['analysisFramework']
        self.assertEqual(response, None, response)
        # Should work for member private AF
        project.add_member(user)
        response = self.query_check(query,
                                    variables={'id': private_af.pk
                                               })['data']['analysisFramework']
        self.assertIdEqual(response['id'], private_af.id, response)
        self.assertEqual(response['isPrivate'], True, response)
Ejemplo n.º 24
0
    def test_organization_filter(self):
        org1, org2, org3 = OrganizationFactory.create_batch(3)
        p1, p2, p3 = ProjectFactory.create_batch(3)
        p1.organizations.set([org2, org1])
        p2.organizations.set([org2, org3])
        p3.organizations.add(org1)

        obtained = self.filter_class(data=dict(
            organizations=[org3.pk, org2.pk])).qs
        expected = [p2, p1]
        self.assertQuerySetIdEqual(expected, obtained)
Ejemplo n.º 25
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())
Ejemplo n.º 26
0
    def test_me_last_active_project(self):
        query = '''
            query Query {
              me {
                lastActiveProject {
                    id
                    title
                }
              }
            }
        '''

        user = UserFactory.create()
        project1 = ProjectFactory.create()
        project2 = ProjectFactory.create()
        project3 = ProjectFactory.create()

        # --- Login
        self.force_login(user)
        # --- Without any project membership
        content = self.query_check(query)
        self.assertEqual(content['data']['me']['lastActiveProject'], None,
                         content)
        # --- With a project membership + But no lastActiveProject set in profile
        project1.add_member(user)
        content = self.query_check(query)
        self.assertIdEqual(content['data']['me']['lastActiveProject']['id'],
                           project1.pk, content)
        # --- With a project membership + lastActiveProject is set in profile
        project2.add_member(user)
        user.last_active_project = project2
        content = self.query_check(query)
        self.assertIdEqual(content['data']['me']['lastActiveProject']['id'],
                           project2.pk, content)
        # --- With a project membership + (non-member) lastActiveProject is set in profile
        user.last_active_project = project3
        content = self.query_check(query)
        self.assertIdEqual(content['data']['me']['lastActiveProject']['id'],
                           project2.pk, content)
Ejemplo n.º 27
0
    def test_analyses_and_analysis_pillars_query(self):
        # Permission checks
        query = '''
            query MyQuery ($projectId: ID!) {
              project(id: $projectId) {
                analyses {
                  totalCount
                  results {
                      id
                      title
                  }
                }
                analysisPillars {
                  totalCount
                  results {
                      id
                      title
                    }
                }
              }
            }
        '''

        member_user = UserFactory.create()
        non_member_user = UserFactory.create()
        project = ProjectFactory.create()
        project.add_member(member_user, role=self.project_role_reader_non_confidential)
        analyses = AnalysisFactory.create_batch(2, project=project, team_lead=member_user, end_date=datetime.datetime.now())
        for analysis in analyses:
            AnalysisPillarFactory.create_batch(5, analysis=analysis, assignee=member_user)

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

        # -- Without login
        _query_check(assert_for_error=True)

        # --- With login
        self.force_login(non_member_user)
        content = _query_check()
        self.assertEqual(content['data']['project']['analyses']['totalCount'], 0, content)
        self.assertEqual(len(content['data']['project']['analyses']['results']), 0, content)
        self.assertEqual(content['data']['project']['analysisPillars']['totalCount'], 0, content)
        self.assertEqual(len(content['data']['project']['analysisPillars']['results']), 0, content)

        self.force_login(member_user)
        content = _query_check()
        self.assertEqual(content['data']['project']['analyses']['totalCount'], 2, content)
        self.assertEqual(len(content['data']['project']['analyses']['results']), 2, content)
        self.assertEqual(content['data']['project']['analysisPillars']['totalCount'], 10, content)
        self.assertEqual(len(content['data']['project']['analysisPillars']['results']), 10, content)
Ejemplo n.º 28
0
    def test_exports_type_filter(self):
        query = '''
            query MyQuery ($id: ID!, $type: [ExportDataTypeEnum!]) {
              project(id: $id) {
                exports(type: $type){
                  page
                  pageSize
                  totalCount
                  results {
                    id
                    title
                  }
                }
              }
            }
        '''
        project = ProjectFactory.create()
        user = UserFactory.create()
        project.add_member(user,
                           role=self.project_role_reader_non_confidential)
        ExportFactory.create_batch(6,
                                   project=project,
                                   exported_by=user,
                                   type=Export.DataType.ENTRIES)
        ExportFactory.create_batch(2,
                                   project=project,
                                   exported_by=user,
                                   type=Export.DataType.ASSESSMENTS)

        def _query_check(**kwargs):
            return self.query_check(query,
                                    variables={
                                        'id':
                                        project.id,
                                        'type':
                                        [self.genum(Export.DataType.ENTRIES)]
                                    },
                                    **kwargs)

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

        # --- With login
        self.force_login(user)
        content = _query_check()
        self.assertEqual(content['data']['project']['exports']['totalCount'],
                         6, content)
        self.assertEqual(len(content['data']['project']['exports']['results']),
                         6, content)
Ejemplo n.º 29
0
 def test_already_request_sent_for_project(self):
     user = UserFactory.create()
     project = ProjectFactory.create()
     # lets create a join request for the project
     ProjectJoinRequestFactory.create(
         requested_by=user,
         project=project,
         role=ProjectRole.get_default_role(),
         status=ProjectJoinRequest.Status.PENDING,
     )
     reason = fuzzy.FuzzyText(length=50).fuzz()
     minput = dict(project=project.id, reason=reason)
     self.force_login(user)
     content = self.query_check(self.project_join_mutation, minput=minput, okay=False)
     self.assertEqual(len(content['data']['joinProject']['errors']), 1, content)
Ejemplo n.º 30
0
    def test_delete_project_join_request(self):
        user = UserFactory.create()
        project = ProjectFactory.create()
        ProjectJoinRequestFactory.create(
            requested_by=user,
            project=project,
            role=ProjectRole.get_default_role(),
            status=ProjectJoinRequest.Status.PENDING,
        )
        join_request_qs = ProjectJoinRequest.objects.filter(requested_by=user, project=project)
        old_join_request_count = join_request_qs.count()

        self.force_login(user)
        self.query_check(self.project_join_request_delete_mutation, variables={'projectId': project.id}, okay=True)
        self.assertEqual(join_request_qs.count(), old_join_request_count - 1)
Ejemplo n.º 31
0
    def test_notification_query(self):
        query = '''
            query MyQuery ($id: ID!) {
              notification(id: $id) {
                  id
                  status
                  project {
                    id
                    title
                  }
                  notificationType
                  timestamp
                  notificationTypeDisplay
                  statusDisplay
                  data
              }
            }
        '''

        project = ProjectFactory.create()
        user = UserFactory.create()
        another_user = UserFactory.create()
        notification_meta = dict(
            notification_type=Notification.Type.PROJECT_JOIN_REQUEST,
            status=Notification.Status.UNSEEN,
        )
        our_notification = NotificationFactory.create(project=project,
                                                      receiver=user,
                                                      **notification_meta)
        other_notification = NotificationFactory.create(project=project,
                                                        receiver=another_user,
                                                        **notification_meta)

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

        # -- Without login
        _query_check(our_notification, assert_for_error=True)

        # --- With login
        self.force_login(user)
        content = _query_check(our_notification)
        self.assertNotEqual(content['data']['notification'], None, content)

        content = _query_check(other_notification)
        self.assertEqual(content['data']['notification'], None, content)