示例#1
0
    def test_only_category_filter(self):
        """
        unit test to only filter items with the category
        create 3 signals and only 2 signals with the category 'plastic_trash"
        """
        cat1 = ParentCategoryFactory.create(name='trash')
        plastic = CategoryFactory.create(parent=cat1,
                                         public_name='plastic_trash',
                                         is_public_accessible=True)
        compost = CategoryFactory.create(parent=cat1,
                                         public_name='compost_trash',
                                         is_public_accessible=True)

        SignalFactoryValidLocation.create(
            category_assignment__category=plastic)
        SignalFactoryValidLocation.create(
            category_assignment__category=plastic)

        SignalFactoryValidLocation.create(
            category_assignment__category=compost)

        response = self.client.get(
            f'{self.geography_endpoint}/?bbox=4.700000,52.200000,5.000000,52.500000&'
            f'category_slug={plastic.slug}')

        data = response.json()
        self.assertEqual(2, len(data['features']))
示例#2
0
    def setUp(self):
        user_model = get_user_model()
        self.superuser, _ = user_model.objects.get_or_create(
            email='*****@*****.**',
            is_superuser=True,
            defaults={
                'first_name': 'John',
                'last_name': 'Doe',
                'is_staff': True
            })

        self.department = DepartmentFactory.create()

        parent_category = ParentCategoryFactory.create()
        self.category_1 = CategoryFactory.create(parent=parent_category,
                                                 departments=[self.department])
        ServiceLevelObjectiveFactory.create(category=self.category_1,
                                            n_days=2,
                                            use_calendar_days=True)
        self.category_2 = CategoryFactory.create(parent=parent_category,
                                                 departments=[self.department])
        ServiceLevelObjectiveFactory.create(category=self.category_2,
                                            n_days=3,
                                            use_calendar_days=False)
        self.category_3 = CategoryFactory.create(parent=parent_category,
                                                 departments=[self.department])
        ServiceLevelObjectiveFactory.create(category=self.category_3,
                                            n_days=4,
                                            use_calendar_days=False)
示例#3
0
    def test_only_main_category_filter(self):
        """
        unit test to only filter items with the main category
        create 5 signals and only 3 under the main category 'trash' that should be returned
        """
        parent_cat = ParentCategoryFactory.create(name='trash')
        child_category = CategoryFactory.create(parent=parent_cat,
                                                public_name='',
                                                is_public_accessible=True)
        child_category_2 = CategoryFactory.create(parent=parent_cat,
                                                  public_name='',
                                                  is_public_accessible=True)

        SignalFactoryValidLocation.create(
            category_assignment__category=child_category)
        SignalFactoryValidLocation.create(
            category_assignment__category=child_category)
        SignalFactoryValidLocation.create(
            category_assignment__category=child_category_2)

        parent_cat_2 = ParentCategoryFactory.create(name='animal')
        child_animal = CategoryFactory.create(parent=parent_cat_2,
                                              public_name='',
                                              is_public_accessible=True)
        SignalFactoryValidLocation.create(
            category_assignment__category=child_animal)
        SignalFactoryValidLocation.create(
            category_assignment__category=child_animal)

        response = self.client.get(
            f'{self.geography_endpoint}/?bbox=4.700000,52.200000,5.000000,52.500000&'
            f'maincategory_slug={parent_cat.slug}')

        data = response.json()
        self.assertEqual(3, len(data['features']))
    def setUp(self):
        self.test_parentcategory_overig = Category.objects.get(
            slug='overig', parent__isnull=True)
        self.test_subcategory_overig = Category.objects.get(
            parent=self.test_parentcategory_overig,
            slug='overig',
            parent__isnull=False)
        self.link_test_subcategory_overig = f'{self.test_host}/signals/v1/public/terms/categories/' \
                                            f'{self.test_subcategory_overig.parent.slug}/sub_categories/' \
                                            f'{self.test_subcategory_overig.slug,}'

        self.test_subcategory = CategoryFactory.create()
        self.link_test_subcategory = f'{self.test_host}/signals/v1/public/terms/categories/' \
                                     f'{self.test_subcategory.parent.slug}/sub_categories/{self.test_subcategory.slug}'

        self.test_subcategory_translated = CategoryFactory.create(
            is_active=False)
        self.link_test_subcategory_translated = f'{self.test_host}/signals/v1/public/terms/categories/' \
                                                f'{self.test_subcategory_translated.parent.slug}/sub_categories/' \
                                                f'{self.test_subcategory_translated.slug}'

        self.link_test_subcategory_translation = CategoryTranslation.objects.create(
            old_category=self.test_subcategory_translated,
            new_category=self.test_subcategory,
            text='For testing purposes we translate this category',
            created_by='*****@*****.**',
        )
    def setUp(self):
        SourceFactory.create(name='online', is_active=True)
        SourceFactory.create(name='Telefoon – ASC', is_active=True)

        self.main_category = ParentCategoryFactory.create(name='main',
                                                          slug='main')
        self.link_main_category = '/signals/v1/public/terms/categories/main'

        self.sub_category_1 = CategoryFactory.create(name='sub1',
                                                     slug='sub1',
                                                     parent=self.main_category)
        self.link_sub_category_1 = f'{self.link_main_category}/sub_categories/sub1'

        self.sub_category_2 = CategoryFactory.create(name='sub2',
                                                     slug='sub2',
                                                     parent=self.main_category)
        self.link_sub_category_2 = f'{self.link_main_category}/sub_categories/sub2'

        self.sia_read_write_user.user_permissions.add(
            Permission.objects.get(codename='sia_can_view_all_categories'))
        self.client.force_authenticate(user=self.sia_read_write_user)

        self.initial_data_base = dict(
            text='Mensen in het cafe maken erg veel herrie',
            location=dict(geometrie=dict(
                type='point', coordinates=[4.90022563, 52.36768424])),
            category=dict(category_url=self.link_sub_category_1),
            reporter=dict(email='*****@*****.**'),
            incident_date_start=timezone.now().strftime('%Y-%m-%dT%H:%M'),
            source='Telefoon – ASC',
        )

        self.retrieve_signal_schema = self.load_json_schema(
            os.path.join(THIS_DIR, 'json_schema',
                         'get_signals_v1_private_signals_{pk}.json'))
示例#6
0
    def test_make_email_context_for_category_with_or_without_public_name(self):
        # Check categories with public names.
        main_cat_with_public_name = ParentCategoryFactory.create(
            parent=None, name='PRIVATE_MAIN_I', public_name='PUBLIC_MAIN_I')
        sub_cat_with_public_name = CategoryFactory.create(
            parent=main_cat_with_public_name,
            name='PRIVATE_SUB',
            public_name='PUBLIC_SUB_I')
        signal_with_public_name = SignalFactory.create(
            category_assignment__category=sub_cat_with_public_name)

        context_with = make_email_context(signal=signal_with_public_name)
        self.assertEqual(context_with['main_category_public_name'],
                         'PUBLIC_MAIN_I')
        self.assertEqual(context_with['sub_category_public_name'],
                         'PUBLIC_SUB_I')

        # Check categories without public names.
        main_cat_no_public_name = ParentCategoryFactory.create(
            parent=None, name='PRIVATE_MAIN_II', public_name=None)
        sub_cat_no_public_name = CategoryFactory.create(
            parent=main_cat_no_public_name,
            name='PRIVATE_SUB_II',
            public_name=None)
        signal_no_public_name = SignalFactory.create(
            category_assignment__category=sub_cat_no_public_name)

        context_without = make_email_context(signal=signal_no_public_name)
        self.assertEqual(context_without['main_category_public_name'],
                         'PRIVATE_MAIN_II')
        self.assertEqual(context_without['sub_category_public_name'],
                         'PRIVATE_SUB_II')
示例#7
0
    def test_command_with_parameters(self):
        CategoryFactory.create()

        db_cnt = Signal.objects.count()

        out = StringIO()
        err = StringIO()

        call_command('dummy_signals', to_create=5, stdout=out, stderr=err)
        self.assertEqual(Signal.objects.count(), db_cnt + 5)
    def setUp(self):
        email = '*****@*****.**'

        self.department_yes = DepartmentFactory.create(name='department_yes')
        self.department_no = DepartmentFactory.create(name='department_no')
        self.category_yes = CategoryFactory.create(departments=[self.department_yes])
        self.category_no = CategoryFactory.create(departments=[self.department_no])
        self.signal_yes = SignalFactory.create(category_assignment__category=self.category_yes, reporter__email=email)
        self.signal_no = SignalFactory.create(category_assignment__category=self.category_no, reporter__email=email)

        self.sia_read_write_user.profile.departments.add(self.department_yes)
    def test_handling_message_in_history_is_constant(self):
        # SIG-3555 because history is not tracked for the Category model and its
        # handling_message. Changing the handling_message will also change the
        # history of every Signal that has that Category associated with.
        # This test demonstrates the problem.
        message_1 = 'MESSAGE 1'
        message_2 = 'MESSAGE 2'

        cat1 = CategoryFactory.create(name='cat1', handling_message=message_1)
        cat2 = CategoryFactory.create(name='cat2')
        signal = SignalFactoryValidLocation(category_assignment__category=cat1)

        self.sia_read_write_user.user_permissions.add(
            Permission.objects.get(codename='sia_can_view_all_categories'))
        self.client.force_authenticate(user=self.sia_read_write_user)

        # Retrieve signal history before changing the Category handling message.
        response = self.client.get(
            f'/signals/v1/private/signals/{signal.id}/history' +
            '?what=UPDATE_SLA')
        self.assertEqual(response.status_code, 200)

        response_json = response.json()
        self.assertEqual(len(response_json), 1)
        self.assertEqual(response_json[0]['description'], message_1)

        # Change handling message on category
        cat1.handling_message = message_2
        cat1.save()
        cat1.refresh_from_db()

        # Assign different category and then the same again, check handling messages.
        Signal.actions.update_category_assignment({'category': cat2}, signal)
        signal.refresh_from_db()
        Signal.actions.update_category_assignment({'category': cat1}, signal)
        response = self.client.get(
            f'/signals/v1/private/signals/{signal.id}/history' +
            '?what=UPDATE_SLA')
        self.assertEqual(response.status_code, 200)

        response_json = response.json()
        self.assertEqual(len(response_json), 1)
        self.assertEqual(response_json[0]['description'], message_1)

        # check that the correct handling messages are stored:
        category_assignments = list(
            CategoryAssignment.objects.filter(
                _signal_id=signal.id).order_by('id'))
        self.assertEqual(category_assignments[0].stored_handling_message,
                         message_1)
        self.assertEqual(category_assignments[2].stored_handling_message,
                         message_2)
    def setUp(self):
        # We use a category without no deadlines to create signals/complaints that
        # will have deadline set to None.
        test_cat = CategoryFactory.create(name='testcategory')

        with freeze_time(self.NOW - datetime.timedelta(days=4 * 7)):
            self.signal_late_open = SignalFactory.create(
                status__state=workflow.GEMELD,
                category_assignment__category=test_cat)
            self.signal_late_closed = SignalFactory.create(
                status__state=workflow.AFGEHANDELD,
                category_assignment__category=test_cat)

        # We now set a Service Level Objective for the category, so that we can
        # create some signals/complaints with a deadline set to some value other
        # than None.
        ServiceLevelObjectiveFactory.create(
            category=test_cat,
            n_days=5,
            use_calendar_days=False,
        )

        with freeze_time(self.NOW - datetime.timedelta(hours=1)):
            self.signal_punctual_open = SignalFactory.create(
                status__state=workflow.GEMELD,
                category_assignment__category=test_cat)
            self.signal_punctual_closed = SignalFactory.create(
                status__state=workflow.AFGEHANDELD,
                category_assignment__category=test_cat)
示例#11
0
    def test_public_name_isset(self):
        """
        An empty public_name (None) must fallback to the name
        """
        parent_category = ParentCategoryFactory.create()
        child_category = CategoryFactory.create(parent=parent_category,
                                                public_name='test',
                                                is_public_accessible=True)
        SignalFactoryValidLocation.create(
            category_assignment__category=child_category)

        response = self.client.get(
            f'{self.geography_endpoint}/?maincategory_slug={parent_category.slug}'
            f'&category_slug={child_category.slug}&bbox=4.700000,52.200000,5.000000,52.500000'
        )
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, int(response.headers['X-Total-Count']))

        data = response.json()
        self.assertEqual(1, len(data['features']))
        self.assertEqual(child_category.public_name,
                         data['features'][0]['properties']['category']['name'])
        self.assertNotEqual(
            child_category.name,
            data['features'][0]['properties']['category']['name'])
示例#12
0
    def test_lon_lat_parameters(self):
        """
        Return the GEOJson containing all signals in the child category
        """
        parent_category = ParentCategoryFactory.create()
        child_category = CategoryFactory.create(
            parent=parent_category,
            public_name='Public category for testing',
            is_public_accessible=True)

        signal = SignalFactoryValidLocation.create(
            category_assignment__category=child_category)
        lon = signal.location.geometrie.x
        lat = signal.location.geometrie.y

        response = self.client.get(
            f'{self.geography_endpoint}/?maincategory_slug={parent_category.slug}'
            f'&category_slug={child_category.slug}&lon={lon}&lat={lat}')

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, int(response.headers['X-Total-Count']))

        data = response.json()
        self.assertEqual(1, len(data['features']))

        for feature in data['features']:
            self.assertEqual(feature['properties']['category']['name'],
                             child_category.public_name)
示例#13
0
    def test_get_geojson(self):
        """
        Return the GEOJson containing all signals in the child category
        """
        parent_category = ParentCategoryFactory.create()
        child_category = CategoryFactory.create(
            parent=parent_category,
            public_name='Public category for testing',
            is_public_accessible=True)

        now = timezone.now()
        for x in range(5):
            with (freeze_time(now - timedelta(days=x))):
                SignalFactoryValidLocation.create(
                    category_assignment__category=child_category)

        response = self.client.get(
            f'{self.geography_endpoint}/?maincategory_slug={parent_category.slug}'
            f'&category_slug={child_category.slug}&bbox=4.700000,52.200000,5.000000,52.500000'
        )
        self.assertEqual(200, response.status_code)
        self.assertEqual(5, int(response.headers['X-Total-Count']))

        data = response.json()
        self.assertEqual(5, len(data['features']))

        for feature in data['features']:
            self.assertEqual(feature['properties']['category']['name'],
                             child_category.public_name)
示例#14
0
    def setUp(self):
        with open(self.fixture_file, 'r') as f:
            self.create_initial_data = json.load(f)

        self.subcategory = CategoryFactory.create()

        self.link_test_cat_sub = '/signals/v1/public/terms/categories/{}/sub_categories/{}'.format(
            self.subcategory.parent.slug, self.subcategory.slug
        )

        self.create_initial_data['category'] = {'sub_category': self.link_test_cat_sub}

        self.retrieve_schema = self.load_json_schema(
            os.path.join(
                THIS_DIR,
                'json_schema',
                'get_signals_v1_public_signals_{uuid}.json'
            )
        )
        self.create_schema = self.load_json_schema(
            os.path.join(
                THIS_DIR,
                'json_schema',
                'post_signals_v1_public_signals.json'
            )
        )
        self.create_attachment_schema = self.load_json_schema(
            os.path.join(
                THIS_DIR,
                'json_schema',
                'post_signals_v1_public_signals_attachment.json'
            )
        )
示例#15
0
    def test_get_group_by(self):
        """
        Return the GEOJson containing the first created_at in a BBOX grouped by a category
        """
        parent_category = ParentCategoryFactory.create()
        child_category = CategoryFactory.create(
            parent=parent_category,
            public_name='Public category for testing',
            is_public_accessible=True)

        now = timezone.now()
        for x in range(5):
            with (freeze_time(now - timedelta(days=x))):
                # Should appear in the response
                SignalFactory.create(
                    location__geometrie=Point(STADHUIS['lon'],
                                              STADHUIS['lat']),
                    location__buurt_code=STADHUIS['buurt_code'],
                    category_assignment__category=child_category)

        response = self.client.get(
            f'{self.geography_endpoint}/?maincategory_slug={parent_category.slug}'
            f'&category_slug={child_category.slug}&bbox=4.875759,52.360656,4.921221,52.37942'
            '&group_by=category')
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, int(response.headers['X-Total-Count']))

        data = response.json()
        self.assertEqual(1, len(data['features']))
        self.assertEqual(data['features'][0]['properties']['category']['name'],
                         child_category.public_name)
示例#16
0
    def setUp(self):
        self.parent_category = ParentCategoryFactory.create(
            name='PARENT-CATEGORY')
        self.child_category = CategoryFactory.create(
            name='CHILD-CATEGORY', parent=self.parent_category)

        self.signal = SignalFactoryWithImage.create(
            text='BLAH BLAH BLAH',
            incident_date_start=timezone.now(),
            category_assignment__category=self.child_category,
            reporter__email='*****@*****.**',
            reporter__phone='0612345678')
        StatusFactory.create(_signal=self.signal,
                             state=workflow.AFWACHTING,
                             text='waiting')
        StatusFactory.create(_signal=self.signal,
                             state=workflow.ON_HOLD,
                             text='please hold')
        status = StatusFactory.create(_signal=self.signal,
                                      state=workflow.AFGEHANDELD,
                                      text='Consider it done')
        self.signal.status = status
        self.signal.save()

        self.user = SuperUserFactory.create()
    def setUp(self):
        self.test_parentcategory_overig = Category.objects.get(slug='overig', parent__isnull=True)
        self.test_subcategory_overig = Category.objects.get(parent=self.test_parentcategory_overig, slug='overig',
                                                            parent__isnull=False)
        self.link_test_subcategory_overig = f'{self.test_host}/signals/v1/public/terms/categories/' \
                                            f'{self.test_subcategory_overig.parent.slug}/sub_categories/' \
                                            f'{self.test_subcategory_overig.slug,}'

        self.test_subcategory = CategoryFactory.create()
        self.link_test_subcategory = f'{self.test_host}/signals/v1/public/terms/categories/' \
                                     f'{self.test_subcategory.parent.slug}/sub_categories/{self.test_subcategory.slug}'
示例#18
0
    def setUp(self):
        self.department_read = Permission.objects.get(
            codename='sia_department_read')
        self.department_write = Permission.objects.get(
            codename='sia_department_write')
        self.sia_read_write_user.user_permissions.add(self.department_read)
        self.sia_read_write_user.user_permissions.add(self.department_write)

        self.department = DepartmentFactory.create()

        self.maincategory = ParentCategoryFactory.create()
        self.subcategory = CategoryFactory.create(parent=self.maincategory)
    def setUp(self):
        statusmessagetemplate_write_permission = Permission.objects.get(
            codename='sia_statusmessagetemplate_write')
        self.sia_read_write_user.user_permissions.add(
            statusmessagetemplate_write_permission)
        self.sia_read_write_user.save()
        self.client.force_authenticate(user=self.sia_read_write_user)

        self.subcategory = CategoryFactory.create()
        self.link_cat_sub_templates = '/signals/v1/private/terms/categories/{}/sub_categories/{}/status-message-templates'.format(  # noqa
            self.subcategory.parent.slug, self.subcategory.slug)

        self.link_cat_parent_templates = '/signals/v1/private/terms/categories/{}/status-message-templates'.format(  # noqa
            self.subcategory.parent.slug)
示例#20
0
    def test_missing_bbox_and_lonlat(self):
        """
        Validate that when neither bbox or lon/lat is filled in to return a non_field_error
        """
        parent_category = ParentCategoryFactory.create()
        child_category = CategoryFactory.create(parent=parent_category,
                                                is_public_accessible=False)
        response = self.client.get(
            f'{self.geography_endpoint}/?maincategory_slug={parent_category.slug}'
            f'&category_slug={child_category.slug}')

        data = response.json()
        self.assertEqual(400, response.status_code)
        self.assertIn('non_field_errors', data.keys())
        self.assertEqual(1, len(data['non_field_errors']))
        self.assertEqual('Either bbox or lon/lat must be filled in',
                         data['non_field_errors'][0])
示例#21
0
    def test_missing_lon(self):
        """
        Validate that both lat /lon parameters have to be filled in if lons parameter is missing
        """
        parent_category = ParentCategoryFactory.create()
        child_category = CategoryFactory.create(parent=parent_category,
                                                is_public_accessible=False)
        response = self.client.get(
            f'{self.geography_endpoint}/?maincategory_slug={parent_category.slug}'
            f'&category_slug={child_category.slug}&lat=5')

        data = response.json()
        self.assertEqual(400, response.status_code)
        self.assertIn('non_field_errors', data.keys())
        self.assertEqual(1, len(data['non_field_errors']))
        self.assertEqual('Either bbox or lon/lat must be filled in',
                         data['non_field_errors'][0])
示例#22
0
    def test_sub_category_detail_questionnaire(self):
        questionnaire = QuestionnaireFactory.create()
        parent_category = ParentCategoryFactory.create()
        sub_category = CategoryFactory.create(parent=parent_category,
                                              questionnaire=questionnaire)

        url = f'/signals/v1/public/terms/categories/{sub_category.parent.slug}/sub_categories/{sub_category.slug}'
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        data = response.json()

        # JSONSchema validation
        self.assertJsonSchema(self.retrieve_sub_category_schema, data)
        self.assertIsNotNone(data['_links']['sia:questionnaire'])
        self.assertEqual(data['questionnaire'],
                         str(sub_category.questionnaire.uuid))
示例#23
0
    def test_filter_maincategory_and_category_slugs_not_a_unique_slug(self):
        parent_category = ParentCategoryFactory.create(name='not_unique')
        category = CategoryFactory.create(name='not_unique',
                                          parent=parent_category)

        SignalFactory.create(category_assignment__category=category)

        params = {
            'maincategory_slug': [
                parent_category.slug,
            ],
            'category_slug': [
                category.slug,
            ]
        }

        result_ids = self._request_filter_signals(params)
        self.assertEqual(1, len(result_ids))
示例#24
0
    def test_get_geojson_no_signals(self):
        """
        Return an empty FeatureCollection because there are no signals at all
        """
        parent_category = ParentCategoryFactory.create()
        child_category = CategoryFactory.create(
            parent=parent_category,
            public_name='Public category for testing',
            is_public_accessible=True)

        response = self.client.get(
            f'{self.geography_endpoint}/?maincategory_slug={parent_category.slug}'
            f'&category_slug={child_category.slug}&bbox=4.700000,52.200000,5.000000,52.500000'
        )
        self.assertEqual(200, response.status_code)
        self.assertEqual(0, int(response.headers['X-Total-Count']))

        data = response.json()
        self.assertIsNone(data['features'])
示例#25
0
    def setUp(self):
        self.department = DepartmentFactory.create()
        self.category = CategoryFactory.create(departments=[self.department])
        self.signal = SignalFactory.create(
            category_assignment__category=self.category)
        self.attachment = ImageAttachmentFactory.create(
            _signal=self.signal, created_by='*****@*****.**')

        # Various Attachment delete permissions
        self.permission_delete_other = Permission.objects.get(
            codename='sia_delete_attachment_of_other_user')
        self.permission_delete_anonymous_user = Permission.objects.get(
            codename='sia_delete_attachment_of_anonymous_user')
        self.permission_delete_normal = Permission.objects.get(
            codename='sia_delete_attachment_of_normal_signal')
        self.permission_delete_parent = Permission.objects.get(
            codename='sia_delete_attachment_of_parent_signal')
        self.permission_delete_child = Permission.objects.get(
            codename='sia_delete_attachment_of_child_signal')
示例#26
0
    def test_child_category_public_name_and_is_public_accessible_true(self):
        """
        Parent category has a public name and is_public_accessible set to False
        Child category has a public name and is_public_accessible set to True

        The is_public_accessible of the parent category should be True because there is at least one child category that
        has the is_public_accessible set to True. The is_public_accessible of the child category should be True in the
        response.
        """
        parent_category = ParentCategoryFactory.create(
            public_name='Publieke naam hoofdcategorie',
            is_public_accessible=False)
        sub_category = CategoryFactory.create(
            parent=parent_category,
            public_name='Publieke naam kindcategorie',
            is_public_accessible=True)

        url = f'/signals/v1/public/terms/categories/{parent_category.slug}'
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        data = response.json()

        # JSONSchema validation
        self.assertJsonSchema(self.retrieve_category_schema, data)
        self.assertEqual(data['public_name'], parent_category.public_name)
        self.assertTrue(data['is_public_accessible'])

        self.assertEqual(data['sub_categories'][0]['public_name'],
                         sub_category.public_name)
        self.assertTrue(data['sub_categories'][0]['is_public_accessible'])

        url = f'/signals/v1/public/terms/categories/{parent_category.slug}/sub_categories/{sub_category.slug}'
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        data = response.json()

        # JSONSchema validation
        self.assertJsonSchema(self.retrieve_sub_category_schema, data)
        self.assertEqual(data['public_name'], sub_category.public_name)
        self.assertTrue(data['is_public_accessible'])
示例#27
0
    def test_null_stored_handling_message(self):
        # SIG-3555 old complaints/Signals will have no stored handling messages on their associated CategoryAssignments.
        # This test fakes that by setting one category's handling message to null and checks that the correct
        # placeholder is returned.
        message_1 = None

        cat1 = CategoryFactory.create(name='cat1', handling_message=message_1)
        signal = SignalFactoryValidLocation(category_assignment__category=cat1)

        self.sia_read_write_user.user_permissions.add(
            Permission.objects.get(codename='sia_can_view_all_categories'))
        self.client.force_authenticate(user=self.sia_read_write_user)

        response = self.client.get(
            f'/signals/v1/private/signals/{signal.id}/history' +
            '?what=UPDATE_SLA')
        self.assertEqual(response.status_code, 200)
        response_json = response.json()
        self.assertEqual(response_json[0]['description'],
                         EMPTY_HANDLING_MESSAGE_PLACEHOLDER_MESSAGE)
示例#28
0
    def test_category_assignment_model(self):
        """
        CategoryAssignmentFactory.save() calls the deadline calculations, check that mechanism here.
        """
        tzinfo = get_default_timezone()
        start = datetime(2021, 2, 19, 12, 0, 0, tzinfo=tzinfo)
        true_deadline = datetime(2021, 2, 22, 12, 0, 0, tzinfo=tzinfo)
        true_deadline_factor_3 = datetime(2021, 2, 24, 12, 0, 0, tzinfo=tzinfo)

        cat = CategoryFactory.create()
        ServiceLevelObjectiveFactory.create(n_days=1,
                                            use_calendar_days=False,
                                            category=cat)

        with freeze_time(start):
            cas = CategoryAssignmentFactory(category=cat)

        self.assertEqual(cas._signal.created_at, start)
        self.assertEqual(cas.deadline, true_deadline)
        self.assertEqual(cas.deadline_factor_3, true_deadline_factor_3)
        self.assertTrue(is_aware(cas.deadline))
        self.assertTrue(is_aware(cas.deadline_factor_3))
示例#29
0
    def _create_signals(cls):
        """
        Creates SIGNALS_DISTRIBUTE_DAYS_CNT signals. One per day backwards starting from yesterday
        current time.
        Creates SIGNALS_DISTRIBUTE_HOURS_CNT signals every hour backwards from now

        If today is Friday 16:00, and SIGNALS_DISTRIBUTE_DAYS_CNT and SIGNALS_DISTRIBUTE_HOURS_CNT
        are both set to 3, we will generate the following signals:
        - Per day: Thursday (yesterday) 16:00, Wednesday (day before yesterday) 16:00, Tuesday 16:00
        - Per hour: Friday 16:00 (now), Friday 15:00 (now minus 1 hour), Friday 14:00 (now minus 2h)
        """
        now = timezone.now()

        # Generate created/updated times for new signals.
        times = [now - timedelta(days=idx + 1)
                 for idx in range(cls.SIGNALS_DISTRIBUTE_DAYS_CNT)] + \
                [now - timedelta(hours=idx)
                 for idx in range(cls.SIGNALS_DISTRIBUTE_HOURS_CNT)]

        cls.states = 3 * [BEHANDELING
                          ] + 2 * [ON_HOLD] + (len(times) - 3 - 2) * [GEMELD]
        shuffle(cls.states)

        cls.sub_categories = [
            CategoryFactory.create() for _ in range(cls.SUBCATEGORY_CNT)
        ]

        for idx, time in enumerate(times):
            with freeze_time(time):
                signal = SignalFactory.create()
                StatusFactory(_signal=signal, state=cls.states[idx])
                category_assignment = CategoryAssignmentFactory(
                    _signal=signal,
                    category=cls.sub_categories[idx % len(cls.sub_categories)])
                signal.category_assignment = category_assignment
                signal.save()

                cls.signals.append(signal)
示例#30
0
    def test_from_signal_and_category(self):
        """
        Call into the deadline calculation service using Django ORM objects.
        """
        tzinfo = get_default_timezone()
        start = datetime(2021, 2, 19, 12, 0, 0, tzinfo=tzinfo)
        true_deadline = datetime(2021, 2, 22, 12, 0, 0, tzinfo=tzinfo)
        true_deadline_factor_3 = datetime(2021, 2, 24, 12, 0, 0, tzinfo=tzinfo)

        cat = CategoryFactory.create()
        ServiceLevelObjectiveFactory.create(n_days=1,
                                            use_calendar_days=False,
                                            category=cat)

        with freeze_time(start):
            signal = SignalFactory(category_assignment__category=cat)

        deadline, deadline_factor_3 = DeadlineCalculationService.from_signal_and_category(
            signal, cat)
        self.assertEqual(deadline, true_deadline)
        self.assertEqual(deadline_factor_3, true_deadline_factor_3)
        self.assertTrue(is_aware(deadline))
        self.assertTrue(is_aware(deadline_factor_3))