Ejemplo n.º 1
0
class ZaakInformatieobjectTypePaginationTestCase(APITestCase):
    maxDiff = None
    list_url = reverse_lazy(ZaakInformatieobjectType)

    def test_pagination_default(self):
        ZaakInformatieobjectTypeFactory.create_batch(
            2, zaaktype__concept=False, informatieobjecttype__concept=False)

        response = self.client.get(self.list_url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = response.json()
        self.assertEqual(response_data['count'], 2)
        self.assertIsNone(response_data['previous'])
        self.assertIsNone(response_data['next'])

    def test_pagination_page_param(self):
        ZaakInformatieobjectTypeFactory.create_batch(
            2, zaaktype__concept=False, informatieobjecttype__concept=False)

        response = self.client.get(self.list_url, {'page': 1})

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = response.json()
        self.assertEqual(response_data['count'], 2)
        self.assertIsNone(response_data['previous'])
        self.assertIsNone(response_data['next'])
Ejemplo n.º 2
0
class EnkelvoudigInformatieObjectPaginationAPITests(JWTAuthMixin, APITestCase):
    list_url = reverse_lazy(EnkelvoudigInformatieObject)
    heeft_alle_autorisaties = True

    def test_pagination_default(self):
        """
        Deleting a Besluit causes all related objects to be deleted as well.
        """
        EnkelvoudigInformatieObjectFactory.create_batch(2)

        response = self.client.get(self.list_url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = response.json()
        self.assertEqual(response_data["count"], 2)
        self.assertIsNone(response_data["previous"])
        self.assertIsNone(response_data["next"])

    def test_pagination_page_param(self):
        EnkelvoudigInformatieObjectFactory.create_batch(2)

        response = self.client.get(self.list_url, {"page": 1})

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = response.json()
        self.assertEqual(response_data["count"], 2)
        self.assertIsNone(response_data["previous"])
        self.assertIsNone(response_data["next"])
Ejemplo n.º 3
0
class LocalRelevanteAndereZakenTests(JWTAuthMixin, APITestCase):

    heeft_alle_autorisaties = True
    list_url = reverse_lazy(Zaak)

    def test_create_local_relevante_andere_zaak(self):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = f"http://testserver.com{reverse(zaaktype)}"
        zaak = ZaakFactory.create(zaaktype=zaaktype)
        zaak_url = f"http://testserver.com{reverse(zaak)}"

        response = self.client.post(
            self.list_url,
            {
                "zaaktype": zaaktype_url,
                "bronorganisatie": "517439943",
                "verantwoordelijkeOrganisatie": "517439943",
                "registratiedatum": "2018-12-24",
                "startdatum": "2018-12-24",
                "vertrouwelijkheidaanduiding": VertrouwelijkheidsAanduiding.openbaar,
                "relevanteAndereZaken": [
                    {"url": zaak_url, "aardRelatie": AardZaakRelatie.vervolg,}
                ],
            },
            **ZAAK_WRITE_KWARGS,
            HTTP_HOST="testserver.com",
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data)
        self.assertEqual(
            response.data["relevante_andere_zaken"],
            [{"url": zaak_url, "aardRelatie": AardZaakRelatie.vervolg}],
        )

    def test_read_local_relevante_andere_zaak(self):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaak = ZaakFactory.create(zaaktype=zaaktype)
        zaak_url = f"http://testserver.com{reverse(zaak)}"

        relevante_zaak = ZaakFactory.create(zaaktype=zaaktype)
        relevante_zaak_url = f"http://testserver.com{reverse(relevante_zaak)}"

        RelevanteZaakRelatieFactory.create(
            url=relevante_zaak, zaak=zaak, aard_relatie=AardZaakRelatie.vervolg
        )

        response = self.client.get(
            zaak_url, **ZAAK_READ_KWARGS, HTTP_HOST="testserver.com"
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
        self.assertEqual(
            response.data["relevante_andere_zaken"],
            [{"url": relevante_zaak_url, "aardRelatie": AardZaakRelatie.vervolg}],
        )
Ejemplo n.º 4
0
class WebhookTests(JWTScopesMixin, APITestCase):

    scopes = [SCOPE_NOTIFICATIES_STUREN]
    url = reverse_lazy('notificaties-webhook')

    def test_auth_required(self):
        self.client.credentials()  # clear any credentials

        response = self.client.post(self.url)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_receive_nofication(self):
        data = {
            "kanaal":
            "zaken",
            "hoofdObject":
            "https://ref.tst.vng.cloud/zrc/api/v1/zaken/d7a22",
            "resource":
            "status",
            "resourceUrl":
            "https://ref.tst.vng.cloud/zrc/api/v1/statussen/d7a22/721c9",
            "actie":
            "create",
            "aanmaakdatum":
            "2018-01-01T17:00:00Z",
            "kenmerken": [{
                "bron": "082096752011"
            }, {
                "zaaktype":
                "https://example.com/api/v1/zaaktypen/5aa5c"
            }, {
                "vertrouwelijkeidaanduiding": "openbaar"
            }]
        }

        response = self.client.post(self.url, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
Ejemplo n.º 5
0
class ZaakTypeInformatieObjectTypeValidationTests(APITestCase):
    maxDiff = None

    list_url = reverse_lazy(ZaakTypeInformatieObjectType)

    def test_catalogus_mismatch(self):
        zaaktype = ZaakTypeFactory.create()
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create()
        informatieobjecttype_url = reverse(informatieobjecttype)
        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype": f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "relations-incorrect-catalogus")
class BesluitInformatieObjectCMISAPITests(JWTAuthMixin, APICMISTestCase):

    list_url = reverse_lazy("besluitinformatieobject-list",
                            kwargs={"version": "1"})

    heeft_alle_autorisaties = True

    def test_create(self):
        besluit = BesluitFactory.create()

        io = EnkelvoudigInformatieObjectFactory.create(
            informatieobjecttype__concept=False)
        io_url = f"http://testserver{reverse(io)}"
        self.adapter.get(io_url, json=serialise_eio(io, io_url))

        besluit.besluittype.informatieobjecttypen.add(io.informatieobjecttype)
        besluit_url = reverse(besluit)
        content = {
            "informatieobject": io_url,
            "besluit": f"http://testserver{besluit_url}",
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        # Test response
        self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                         response.data)

        # Test database
        self.assertEqual(BesluitInformatieObject.objects.count(), 1)
        stored_object = BesluitInformatieObject.objects.get()
        self.assertEqual(stored_object.besluit, besluit)

        expected_url = reverse(stored_object)

        expected_response = content.copy()
        expected_response.update({"url": f"http://testserver{expected_url}"})
        self.assertEqual(response.json(), expected_response)

    def test_duplicate_object(self):
        """
        Test the (informatieobject, object) unique together validation.
        """
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = f"http://testserver{reverse(io)}"
        self.adapter.get(io_url, json=serialise_eio(io, io_url))

        bio = BesluitInformatieObjectFactory.create(informatieobject=io_url)
        besluit_url = reverse(bio.besluit)

        content = {
            "informatieobject": io_url,
            "besluit": f"http://testserver{besluit_url}",
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unique")

    def test_read_besluit(self):
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = f"http://testserver{reverse(io)}"
        self.adapter.get(io_url, json=serialise_eio(io, io_url))

        bio = BesluitInformatieObjectFactory.create(informatieobject=io_url)
        bio_detail_url = reverse(bio)

        response = self.client.get(bio_detail_url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        besluit_url = reverse(bio.besluit)
        expected = {
            "url": f"http://testserver{bio_detail_url}",
            "informatieobject": io_url,
            "besluit": f"http://testserver{besluit_url}",
        }

        self.assertEqual(response.json(), expected)

    def test_filter_by_besluit(self):
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = io.get_url()
        self.adapter.get(io_url, json=serialise_eio(io, io_url))
        bio = BesluitInformatieObjectFactory.create(informatieobject=io_url)
        besluit_url = reverse(bio.besluit)
        bio_list_url = reverse("besluitinformatieobject-list")

        response = self.client.get(
            bio_list_url,
            {"besluit": f"http://openzaak.nl{besluit_url}"},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["besluit"],
                         f"http://openzaak.nl{besluit_url}")

    def test_filter_by_informatieobject(self):
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = f"http://openzaak.nl{reverse(io)}"
        self.adapter.get(io_url, json=serialise_eio(io, io_url))

        BesluitInformatieObjectFactory.create(informatieobject=io_url)
        bio_list_url = reverse("besluitinformatieobject-list")

        response = self.client.get(
            bio_list_url,
            {"informatieobject": io_url},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["informatieobject"], io_url)

    def test_put_besluit_not_allowed(self):
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = io.get_url()
        self.adapter.get(io_url, json=serialise_eio(io, io_url))
        bio = BesluitInformatieObjectFactory.create(informatieobject=io_url)
        bio_detail_url = reverse(bio)
        besluit = BesluitFactory.create()
        besluit_url = reverse(besluit)
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = reverse(io)

        response = self.client.put(
            bio_detail_url,
            {
                "besluit": f"http://testserver{besluit_url}",
                "informatieobject": f"http://testserver{io_url}",
            },
        )

        self.assertEqual(response.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED, response.data)

    def test_patch_besluit_not_allowed(self):
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = io.get_url()
        self.adapter.get(io_url, json=serialise_eio(io, io_url))
        bio = BesluitInformatieObjectFactory.create(informatieobject=io_url)
        bio_detail_url = reverse(bio)
        besluit = BesluitFactory.create()
        besluit_url = reverse(besluit)
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = reverse(io)

        response = self.client.patch(
            bio_detail_url,
            {
                "besluit": f"http://testserver{besluit_url}",
                "informatieobject": f"http://testserver{io_url}",
            },
        )

        self.assertEqual(response.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED, response.data)

    def test_delete(self):
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = io.get_url()
        self.adapter.get(io_url, json=serialise_eio(io, io_url))
        bio = BesluitInformatieObjectFactory.create(informatieobject=io_url)
        bio_url = reverse(bio)

        response = self.client.delete(bio_url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT,
                         response.data)

        # Relation is gone, besluit still exists.
        self.assertFalse(BesluitInformatieObject.objects.exists())
        self.assertTrue(Besluit.objects.exists())
class ZaakInformatieobjectTypeAPITests(APITestCase):
    maxDiff = None

    list_url = reverse_lazy(ZaakInformatieobjectType)

    def test_get_list(self):
        ZaakInformatieobjectTypeFactory.create_batch(3)

        response = self.client.get(self.list_url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 3)

    def test_get_detail(self):
        ztiot = ZaakInformatieobjectTypeFactory.create()
        url = reverse(ztiot)
        zaaktype_url = reverse(
            ztiot.zaaktype,
            kwargs={'catalogus_uuid': ztiot.zaaktype.catalogus.uuid})
        informatie_object_type_url = reverse(
            ztiot.informatie_object_type,
            kwargs={
                'catalogus_uuid': ztiot.informatie_object_type.catalogus.uuid
            })

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        expected = {
            'url': f'http://testserver{url}',
            'zaaktype': f'http://testserver{zaaktype_url}',
            'informatieObjectType':
            f'http://testserver{informatie_object_type_url}',
            'volgnummer': ztiot.volgnummer,
            'richting': ztiot.richting,
            'statusType': None,
        }
        self.assertEqual(response.json(), expected)

    def test_filter_zaaktype(self):
        ztiot1, ztiot2 = ZaakInformatieobjectTypeFactory.create_batch(2)
        url = f'http://testserver{reverse(ztiot1)}'
        zaaktype1_url = reverse(
            ztiot1.zaaktype,
            kwargs={'catalogus_uuid': ztiot1.zaaktype.catalogus.uuid})
        zaaktype2_url = reverse(
            ztiot2.zaaktype,
            kwargs={'catalogus_uuid': ztiot2.zaaktype.catalogus.uuid})

        zaaktype1_url = f'http://testserver{zaaktype1_url}'
        zaaktype2_url = f'http://testserver{zaaktype2_url}'

        response = self.client.get(self.list_url, {'zaaktype': zaaktype1_url})

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json()[0]['url'], url)
        self.assertEqual(response.json()[0]['zaaktype'], zaaktype1_url)
        self.assertNotEqual(response.json()[0]['zaaktype'], zaaktype2_url)

    def test_filter_informatieobjecttype(self):
        ztiot1, ztiot2 = ZaakInformatieobjectTypeFactory.create_batch(2)
        url = f'http://testserver{reverse(ztiot1)}'
        informatie_object_type1_url = reverse(
            ztiot1.informatie_object_type,
            kwargs={
                'catalogus_uuid': ztiot1.informatie_object_type.catalogus.uuid
            })
        informatie_object_type2_url = reverse(
            ztiot2.informatie_object_type,
            kwargs={
                'catalogus_uuid': ztiot2.informatie_object_type.catalogus.uuid
            })

        informatie_object_type1_url = f'http://testserver{informatie_object_type1_url}'
        informatie_object_type2_url = f'http://testserver{informatie_object_type2_url}'

        response = self.client.get(
            self.list_url,
            {'informatieObjectType': informatie_object_type1_url})

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json()[0]['url'], url)
        self.assertEqual(response.json()[0]['informatieObjectType'],
                         informatie_object_type1_url)
        self.assertNotEqual(response.json()[0]['informatieObjectType'],
                            informatie_object_type2_url)
Ejemplo n.º 8
0
class BesluitValidationTests(JWTAuthMixin, APITestCase):
    url = reverse_lazy("besluit-list")
    heeft_alle_autorisaties = True

    def test_rsin_invalid(self):
        cases = [
            ("1234567", "invalid-length"),
            ("12345678", "invalid-length"),
            ("123456789", "invalid"),
        ]

        for rsin, error_code in cases:
            with self.subTest(rsin=rsin, error_code=error_code):
                response = self.client.post(
                    self.url, {"verantwoordelijkeOrganisatie": rsin})

                self.assertEqual(response.status_code,
                                 status.HTTP_400_BAD_REQUEST)
                error = get_validation_errors(response,
                                              "verantwoordelijkeOrganisatie")
                self.assertEqual(error["code"], error_code)

    @freeze_time("2018-09-06T12:08+0200")
    def test_future_datum(self):
        response = self.client.post(self.url, {"datum": "2018-09-07"})

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        error = get_validation_errors(response, "datum")
        self.assertEqual(error["code"], UntilTodayValidator.code)

    def test_duplicate_rsin_identificatie(self):
        besluit = BesluitFactory.create(identificatie="123456")
        besluittype_url = reverse(besluit.besluittype)

        response = self.client.post(
            self.url,
            {
                "verantwoordelijkeOrganisatie":
                besluit.verantwoordelijke_organisatie,
                "identificatie": "123456",
                "besluittype": f"http://testserver{besluittype_url}",
                "datum": "2018-09-06",
                "ingangsdatum": "2018-10-01",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        error = get_validation_errors(response, "identificatie")
        self.assertEqual(error["code"], "identificatie-niet-uniek")

    def test_change_immutable_fields(self):
        besluit = BesluitFactory.create(identificatie="123456")
        besluit2 = BesluitFactory.create(identificatie="123456")

        url = reverse(besluit)

        response = self.client.patch(
            url,
            {
                "verantwoordelijkeOrganisatie":
                besluit2.verantwoordelijke_organisatie,
                "identificatie": "123456789",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        identificatie_error = get_validation_errors(response, "identificatie")
        self.assertEqual(identificatie_error["code"],
                         IsImmutableValidator.code)

        verantwoordelijke_organisatie_error = get_validation_errors(
            response, "verantwoordelijkeOrganisatie")
        self.assertEqual(verantwoordelijke_organisatie_error["code"],
                         IsImmutableValidator.code)

    def test_validate_besluittype_valid(self):
        besluittype = BesluitTypeFactory.create()
        besluittype_url = reverse(besluittype)
        url = reverse("besluit-list")

        response = self.client.post(
            url,
            {
                "verantwoordelijkeOrganisatie": "000000000",
                "identificatie": "123456",
                "besluittype": f"http://testserver{besluittype_url}",
                "datum": "2018-09-06",
                "ingangsdatum": "2018-10-01",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                         response.data)

    def test_besluittype_invalid(self):
        list_url = reverse("besluit-list")

        response = self.client.post(
            list_url,
            {
                "verantwoordelijkeOrganisatie": "000000000",
                "identificatie": "123456",
                "besluittype": "https://example.com/zrc/zaken/1234",
                "datum": "2018-09-06",
                "ingangsdatum": "2018-10-01",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "besluittype")
        self.assertEqual(error["code"], "no_match")

    def test_zaaktype_besluittype_relation(self):
        besluittype = BesluitTypeFactory.create()
        besluittype_url = reverse(besluittype)
        zaak = ZaakFactory.create(zaaktype__concept=False)
        zaak_url = reverse(zaak)
        besluittype.zaaktypes.add(zaak.zaaktype)
        list_url = reverse("besluit-list")

        response = self.client.post(
            list_url,
            {
                "verantwoordelijkeOrganisatie": "000000000",
                "identificatie": "123456",
                "besluittype": f"http://testserver{besluittype_url}",
                "zaak": f"http://testserver{zaak_url}",
                "datum": "2018-09-06",
                "ingangsdatum": "2018-10-01",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                         response.data)

    def test_no_zaaktype_besluittype_relation(self):
        besluittype = BesluitTypeFactory.create()
        besluittype_url = reverse(besluittype)
        zaak = ZaakFactory.create()
        zaak_url = reverse(zaak)
        list_url = reverse("besluit-list")

        response = self.client.post(
            list_url,
            {
                "verantwoordelijkeOrganisatie": "000000000",
                "identificatie": "123456",
                "besluittype": f"http://testserver{besluittype_url}",
                "zaak": f"http://testserver{zaak_url}",
                "datum": "2018-09-06",
                "ingangsdatum": "2018-10-01",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "zaaktype-mismatch")

    def test_relation_with_non_published_zaaktype(self):
        zaak = ZaakFactory.create(zaaktype__concept=True)
        zaak_url = reverse(zaak)
        besluittype = BesluitTypeFactory.create()
        besluittype_url = reverse(besluittype)
        besluittype.zaaktypes.add(zaak.zaaktype)
        list_url = reverse("besluit-list")

        response = self.client.post(
            list_url,
            {
                "verantwoordelijkeOrganisatie": "000000000",
                "identificatie": "123456",
                "besluittype": f"http://testserver{besluittype_url}",
                "zaak": f"http://testserver{zaak_url}",
                "datum": "2018-09-06",
                "ingangsdatum": "2018-10-01",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "zaaktype-mismatch")
class ExternalDocumentsAPITests(JWTAuthMixin, APITestCase):
    heeft_alle_autorisaties = True
    list_url = reverse_lazy(BesluitInformatieObject)
    base = "https://external.documenten.nl/api/v1/"

    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        Service.objects.create(
            api_type=APITypes.drc,
            api_root=cls.base,
            label="external documents",
            auth_type=AuthTypes.no_auth,
        )

    def test_create_bio_external_document(self):
        document = f"{self.base}enkelvoudiginformatieobjecten/{uuid.uuid4()}"
        besluit = BesluitFactory.create(besluittype__concept=False)
        besluit_url = f"http://openzaak.nl{reverse(besluit)}"
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=besluit.besluittype.catalogus, concept=False
        )
        informatieobjecttype_url = f"http://openzaak.nl{reverse(informatieobjecttype)}"
        informatieobjecttype.besluittypen.add(besluit.besluittype)
        eio_response = get_eio_response(
            document, informatieobjecttype=informatieobjecttype_url
        )
        oio_response = get_oio_response(document, besluit_url, "besluit")

        with self.subTest(section="bio-create"):
            with requests_mock.Mocker(real_http=True) as m:
                mock_service_oas_get(m, APITypes.drc, self.base)
                m.get(document, json=eio_response)
                m.post(
                    "https://external.documenten.nl/api/v1/objectinformatieobjecten",
                    json=oio_response,
                    status_code=201,
                )

                response = self.client.post(
                    self.list_url,
                    {"besluit": besluit_url, "informatieobject": document},
                )

            self.assertEqual(
                response.status_code, status.HTTP_201_CREATED, response.data
            )
            posts = [req for req in m.request_history if req.method == "POST"]
            self.assertEqual(len(posts), 1)
            request = posts[0]
            self.assertEqual(
                request.url,
                "https://external.documenten.nl/api/v1/objectinformatieobjecten",
            )
            self.assertEqual(
                request.json(),
                {
                    "informatieobject": document,
                    "object": besluit_url,
                    "objectType": "besluit",
                },
            )

            self.assertFalse(ObjectInformatieObject.objects.exists())

            bio = BesluitInformatieObject.objects.get()
            self.assertEqual(bio._objectinformatieobject_url, oio_response["url"])

        with self.subTest(section="bio-list"):
            list_response = self.client.get(
                self.list_url, {"besluit": besluit_url}, HTTP_HOST="openzaak.nl",
            )

            self.assertEqual(
                list_response.status_code, status.HTTP_200_OK, response.data
            )
            data = list_response.json()

            self.assertEqual(len(data), 1)
            self.assertEqual(data[0]["informatieobject"], document)

    def test_create_bio_fail_bad_url(self):
        besluit = BesluitFactory.create(besluittype__concept=False)
        besluit_url = f"http://openzaak.nl{reverse(besluit)}"
        data = {"besluit": besluit_url, "informatieobject": "abcd"}

        response = self.client.post(self.list_url, data, HTTP_HOST="openzaak.nl")

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "informatieobject")
        self.assertEqual(error["code"], "bad-url")

    def test_create_bio_fail_not_json(self):
        besluit = BesluitFactory.create(besluittype__concept=False)
        besluit_url = f"http://openzaak.nl{reverse(besluit)}"
        data = {"besluit": besluit_url, "informatieobject": "http://example.com"}

        response = self.client.post(self.list_url, data, HTTP_HOST="openzaak.nl")

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "informatieobject")
        self.assertEqual(error["code"], "invalid-resource")

    def test_create_bio_fail_invalid_schema(self):
        base = "https://external.documenten.nl/api/v1/"
        document = f"{base}enkelvoudiginformatieobjecten/{uuid.uuid4()}"
        besluit = BesluitFactory.create(besluittype__concept=False)
        besluit_url = f"http://openzaak.nl{reverse(besluit)}"
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=besluit.besluittype.catalogus, concept=False
        )
        informatieobjecttype_url = f"http://openzaak.nl{reverse(informatieobjecttype)}"
        informatieobjecttype.besluittypen.add(besluit.besluittype)

        with requests_mock.Mocker(real_http=True) as m:
            m.get(
                document,
                json={
                    "url": document,
                    "beschrijving": "",
                    "ontvangstdatum": None,
                    "informatieobjecttype": informatieobjecttype_url,
                    "locked": False,
                },
            )

            response = self.client.post(
                self.list_url, {"besluit": besluit_url, "informatieobject": document},
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "informatieobject")
        self.assertEqual(error["code"], "invalid-resource")
Ejemplo n.º 10
0
class ResultaatTypeAPITests(TypeCheckMixin, APITestCase):
    maxDiff = None

    list_url = reverse_lazy(ResultaatType)

    def test_get_list(self):
        ResultaatTypeFactory.create_batch(3, zaaktype__concept=False)

        response = self.api_client.get(self.list_url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()['results']
        self.assertEqual(len(data), 3)
        self.assertResponseTypes(
            data[0],
            (
                ('url', str),
                ('zaaktype', str),
                ('omschrijving', str),
                ('resultaattypeomschrijving', str),
                ('omschrijvingGeneriek', str),
                ('selectielijstklasse', str),
                ('toelichting', str),
                ('archiefnominatie', str),
                ('archiefactietermijn', str),
                ('brondatumArchiefprocedure', dict),
            )
        )

    def test_get_list_default_definitief(self):
        resultaattype1 = ResultaatTypeFactory.create(zaaktype__concept=True)
        resultaattype2 = ResultaatTypeFactory.create(zaaktype__concept=False)
        resultaattype_list_url = reverse('resultaattype-list')
        resultaattype2_url = reverse('resultaattype-detail', kwargs={'uuid': resultaattype2.uuid})

        response = self.client.get(resultaattype_list_url)
        self.assertEqual(response.status_code, 200)

        data = response.json()['results']

        self.assertEqual(len(data), 1)
        self.assertEqual(data[0]['url'], f'http://testserver{resultaattype2_url}')

    def test_get_detail(self):
        resultaattype = ResultaatTypeFactory.create()
        url = reverse(resultaattype)
        zaaktype_url = reverse('zaaktype-detail', kwargs={
            'uuid': resultaattype.zaaktype.uuid,
        })

        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response_data = response.json()

        self.assertEqual(response_data, {
            'url': f'http://testserver{url}',
            'zaaktype': f'http://testserver{zaaktype_url}',
            'omschrijving': resultaattype.omschrijving,
            'resultaattypeomschrijving': resultaattype.resultaattypeomschrijving,
            'omschrijvingGeneriek': resultaattype.omschrijving_generiek,
            'selectielijstklasse': resultaattype.selectielijstklasse,
            'toelichting': '',
            'archiefnominatie': resultaattype.archiefnominatie,
            'archiefactietermijn': 'P10Y',
            'brondatumArchiefprocedure': {
                'afleidingswijze': None,
                'datumkenmerk': None,
                'einddatumBekend': False,
                'objecttype': None,
                'registratie': None,
                'procestermijn': None,
            }
        })

    def test_resultaattypen_embedded_zaaktype(self):
        resultaattype = ResultaatTypeFactory.create()
        url = f'http://testserver{reverse(resultaattype)}'
        zaaktype_url = reverse('zaaktype-detail', kwargs={
            'uuid': resultaattype.zaaktype.uuid,
        })

        response = self.client.get(zaaktype_url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.json()['resultaattypen'],
            [url]
        )

    def test_resultaattype_afleidingswijze_procestermijn(self):
        resultaattype = ResultaatTypeFactory.create(
            brondatum_archiefprocedure_afleidingswijze='procestermijn',
            brondatum_archiefprocedure_procestermijn='P5Y',
        )

        url = reverse(resultaattype)
        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        brondatumArchiefprocedure = response.json()['brondatumArchiefprocedure']

        afleidingswijze = resultaattype.brondatum_archiefprocedure_afleidingswijze
        procestermijn = resultaattype.brondatum_archiefprocedure_procestermijn

        self.assertEqual(brondatumArchiefprocedure['afleidingswijze'], afleidingswijze)

        # Verify that the procestermijn was serialized correctly
        self.assertEqual(brondatumArchiefprocedure['procestermijn'], procestermijn)

    @override_settings(LINK_FETCHER='vng_api_common.mocks.link_fetcher_200')
    @patch('vng_api_common.oas.fetcher.fetch', return_value={})
    @patch('vng_api_common.validators.obj_has_shape', return_value=True)
    def test_create_resultaattype(self, mock_shape, mock_fetch):
        zaaktype = ZaakTypeFactory.create(
            selectielijst_procestype=PROCESTYPE_URL,
        )
        zaaktype_url = reverse('zaaktype-detail', kwargs={
            'uuid': zaaktype.uuid,
        })
        resultaattypeomschrijving_url = 'http://example.com/omschrijving/1'
        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'omschrijving': 'illum',
            'resultaattypeomschrijving': resultaattypeomschrijving_url,
            'selectielijstklasse': SELECTIELIJSTKLASSE_URL,
            'archiefnominatie': 'blijvend_bewaren',
            'archiefactietermijn': 'P10Y',
            'brondatumArchiefprocedure': {
                'afleidingswijze': BrondatumArchiefprocedureAfleidingswijze.afgehandeld,
                'einddatumBekend': False,
                'procestermijn': 'P10Y',
                'datumkenmerk': '',
                'objecttype': '',
                'registratie': '',
            }
        }

        responses = {
            SELECTIELIJSTKLASSE_URL: {
                'url': SELECTIELIJSTKLASSE_URL,
                'procesType': PROCESTYPE_URL,
                'procestermijn': Procestermijn.nihil,
            },
        }

        with mock_client(responses):
            with requests_mock.Mocker() as m:
                m.register_uri('GET', resultaattypeomschrijving_url, json={
                    'omschrijving': 'test'
                })
                response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        resultaattype = ResultaatType.objects.get()

        self.assertEqual(resultaattype.omschrijving_generiek, 'test')
        self.assertEqual(resultaattype.zaaktype, zaaktype)
        self.assertEqual(
            resultaattype.brondatum_archiefprocedure_afleidingswijze,
            BrondatumArchiefprocedureAfleidingswijze.afgehandeld
        )

    @override_settings(LINK_FETCHER='vng_api_common.mocks.link_fetcher_200')
    @patch('vng_api_common.oas.fetcher.fetch', return_value={})
    @patch('vng_api_common.validators.obj_has_shape', return_value=True)
    def test_create_resultaattype_fail_not_concept_zaaktype(self, mock_shape, mock_fetch):
        zaaktype = ZaakTypeFactory.create(
            selectielijst_procestype=PROCESTYPE_URL,
            concept=False
        )
        zaaktype_url = reverse('zaaktype-detail', kwargs={
            'uuid': zaaktype.uuid,
        })
        resultaattypeomschrijving_url = 'http://example.com/omschrijving/1'
        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'omschrijving': 'illum',
            'resultaattypeomschrijving': resultaattypeomschrijving_url,
            'selectielijstklasse': SELECTIELIJSTKLASSE_URL,
            'archiefnominatie': 'blijvend_bewaren',
            'archiefactietermijn': 'P10Y',
            'brondatumArchiefprocedure': {
                'afleidingswijze': BrondatumArchiefprocedureAfleidingswijze.afgehandeld,
                'einddatumBekend': False,
                'procestermijn': 'P10Y',
                'datumkenmerk': '',
                'objecttype': '',
                'registratie': '',
            }
        }

        responses = {
            SELECTIELIJSTKLASSE_URL: {
                'url': SELECTIELIJSTKLASSE_URL,
                'procesType': PROCESTYPE_URL,
                'procestermijn': Procestermijn.nihil,
            },
        }

        with mock_client(responses):
            with requests_mock.Mocker() as m:
                m.register_uri('GET', resultaattypeomschrijving_url, json={
                    'omschrijving': 'test'
                })
                response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        data = response.json()
        self.assertEqual(data['detail'], 'Creating a related object to non-concept object is forbidden')

    def test_delete_resultaattype(self):
        resultaattype = ResultaatTypeFactory.create()
        resultaattype_url = reverse('resultaattype-detail', kwargs={'uuid': resultaattype.uuid})

        response = self.client.delete(resultaattype_url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(ResultaatType.objects.filter(id=resultaattype.id))

    def test_delete_resultaattype_fail_not_concept_zaaktype(self):
        resultaattype = ResultaatTypeFactory.create(zaaktype__concept=False)
        resultaattype_url = reverse('resultaattype-detail', kwargs={'uuid': resultaattype.uuid})

        response = self.client.delete(resultaattype_url)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        data = response.json()
        self.assertEqual(data['detail'], 'Alleen concepten kunnen worden verwijderd.')
class ExternalInformatieObjectAPITests(JWTAuthMixin, APITestCase):
    heeft_alle_autorisaties = True
    list_url = reverse_lazy(BesluitInformatieObject)
    base = "https://external.documenten.nl/api/v1/"
    document = f"{base}enkelvoudiginformatieobjecten/{uuid.uuid4()}"

    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        Service.objects.create(
            api_type=APITypes.drc,
            api_root=cls.base,
            label="external documents",
            auth_type=AuthTypes.no_auth,
        )

    def test_besluittype_internal_iotype_internal_fail(self):
        besluit = BesluitFactory.create()
        besluit_url = f"http://openbesluit.nl{reverse(besluit)}"
        informatieobjecttype = InformatieObjectTypeFactory.create()
        eio_response = get_eio_response(
            self.document,
            informatieobjecttype=f"http://openbesluit.nl{reverse(informatieobjecttype)}",
        )

        with requests_mock.Mocker(real_http=True) as m:
            m.get(self.document, json=eio_response)
            response = self.client.post(
                self.list_url,
                {"besluit": besluit_url, "informatieobject": self.document},
                HTTP_HOST="openbesluit.nl",
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(
            error["code"], "missing-besluittype-informatieobjecttype-relation"
        )

    def test_besluittype_external_iotype_external_success(self):
        catalogus = f"{self.base}catalogussen/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluittype = f"{self.base}besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"
        besluit = BesluitFactory.create(besluittype=besluittype)
        besluit_url = f"http://openbesluit.nl{reverse(besluit)}"
        informatieobjecttype = f"{self.base}informatieobjecttypen/{uuid.uuid4()}"
        besluittype_data = get_besluittype_response(catalogus, besluittype)
        besluittype_data["informatieobjecttypen"] = [informatieobjecttype]

        with requests_mock.Mocker(real_http=True) as m:
            mock_service_oas_get(m, APITypes.drc, self.base)
            m.get(besluittype, json=besluittype_data)
            m.get(
                informatieobjecttype,
                json=get_informatieobjecttype_response(catalogus, informatieobjecttype),
            )
            m.get(
                self.document,
                json=get_eio_response(
                    self.document, informatieobjecttype=informatieobjecttype
                ),
            )
            m.post(
                f"{self.base}objectinformatieobjecten",
                json=get_oio_response(self.document, besluit_url),
                status_code=201,
            )

            response = self.client.post(
                self.list_url,
                {"besluit": besluit_url, "informatieobject": self.document},
                HTTP_HOST="openbesluit.nl",
            )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_besluittype_external_iotype_external_fail(self):
        catalogus = f"{self.base}catalogussen/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluittype = f"{self.base}besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"
        besluit = BesluitFactory.create(besluittype=besluittype)
        besluit_url = f"http://openbesluit.nl{reverse(besluit)}"
        informatieobjecttype = f"{self.base}informatieobjecttypen/{uuid.uuid4()}"

        with requests_mock.Mocker(real_http=True) as m:
            m.get(besluittype, json=get_besluittype_response(catalogus, besluittype))
            m.get(
                informatieobjecttype,
                json=get_informatieobjecttype_response(catalogus, informatieobjecttype),
            )
            m.get(
                self.document,
                json=get_eio_response(
                    self.document, informatieobjecttype=informatieobjecttype
                ),
            )

            response = self.client.post(
                self.list_url,
                {"besluit": besluit_url, "informatieobject": self.document},
                HTTP_HOST="openbesluit.nl",
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(
            error["code"], "missing-besluittype-informatieobjecttype-relation"
        )

    def test_besluittype_internal_iotype_external(self):
        besluit = BesluitFactory.create()
        besluit_url = f"http://openbesluit.nl{reverse(besluit)}"
        informatieobjecttype = f"{self.base}informatieobjecttypen/{uuid.uuid4()}"
        catalogus = f"{self.base}catalogussen/1c8e36be-338c-4c07-ac5e-1adf55bec04a"

        with requests_mock.Mocker(real_http=True) as m:
            m.get(
                informatieobjecttype,
                json=get_informatieobjecttype_response(catalogus, informatieobjecttype),
            )
            m.get(
                catalogus, json=get_catalogus_response(catalogus, informatieobjecttype)
            )
            m.get(
                self.document,
                json=get_eio_response(
                    self.document, informatieobjecttype=informatieobjecttype
                ),
            )

            response = self.client.post(
                self.list_url,
                {"besluit": besluit_url, "informatieobject": self.document},
                HTTP_HOST="openbesluit.nl",
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(
            error["code"], "missing-besluittype-informatieobjecttype-relation"
        )

    def test_besluittype_external_iotype_internal(self):
        catalogus = f"{self.base}catalogussen/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluittype = f"{self.base}besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"
        besluit = BesluitFactory.create(besluittype=besluittype)
        besluit_url = f"http://openbesluit.nl{reverse(besluit)}"
        informatieobjecttype = InformatieObjectTypeFactory.create()
        eio_response = get_eio_response(
            self.document,
            informatieobjecttype=f"http://openbesluit.nl{reverse(informatieobjecttype)}",
        )

        with requests_mock.Mocker(real_http=True) as m:
            m.get(besluittype, json=get_besluittype_response(catalogus, besluittype))
            m.get(self.document, json=eio_response)

            response = self.client.post(
                self.list_url,
                {"besluit": besluit_url, "informatieobject": self.document},
                HTTP_HOST="openbesluit.nl",
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(
            error["code"], "missing-besluittype-informatieobjecttype-relation"
        )
Ejemplo n.º 12
0
class EnkelvoudigInformatieObjectVersionHistoryAPITests(
        JWTAuthMixin, APITestCase):
    list_url = reverse_lazy(EnkelvoudigInformatieObject)
    heeft_alle_autorisaties = True

    def test_eio_update(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1", informatieobjecttype__concept=False)

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})

        eio_response = self.client.get(eio_url)
        eio_data = eio_response.data

        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        eio_data.update({
            "beschrijving": "beschrijving2",
            "inhoud": b64encode(b"aaaaa"),
            "lock": lock,
        })

        for i in ["integriteit", "ondertekening"]:
            eio_data.pop(i)

        response = self.client.put(eio_url, eio_data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response_data = response.json()

        self.assertEqual(response_data["beschrijving"], "beschrijving2")

        eios = EnkelvoudigInformatieObject.objects.filter(
            uuid=eio.uuid).order_by("-versie")

        self.assertEqual(len(eios), 2)

        latest_version = eios.first()
        self.assertEqual(latest_version.versie, 2)
        self.assertEqual(latest_version.beschrijving, "beschrijving2")

        first_version = eios[1]
        self.assertEqual(first_version.versie, 1)
        self.assertEqual(first_version.beschrijving, "beschrijving1")

    def test_eio_partial_update(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1")

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        response = self.client.patch(eio_url, {
            "beschrijving": "beschrijving2",
            "lock": lock
        })

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response_data = response.json()

        self.assertEqual(response_data["beschrijving"], "beschrijving2")

        eios = EnkelvoudigInformatieObject.objects.filter(
            uuid=eio.uuid).order_by("-versie")
        self.assertEqual(len(eios), 2)

        latest_version = eios.first()
        self.assertEqual(latest_version.versie, 2)
        self.assertEqual(latest_version.beschrijving, "beschrijving2")

        first_version = eios[1]
        self.assertEqual(first_version.versie, 1)
        self.assertEqual(first_version.beschrijving, "beschrijving1")

    def test_eio_delete(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1")

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {
            "beschrijving": "beschrijving2",
            "lock": lock
        })

        response = self.client.delete(eio_url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(EnkelvoudigInformatieObjectCanonical.objects.exists())
        self.assertFalse(EnkelvoudigInformatieObject.objects.exists())

    def test_eio_detail_retrieves_latest_version(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1")

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {
            "beschrijving": "beschrijving2",
            "lock": lock
        })

        response = self.client.get(eio_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["beschrijving"], "beschrijving2")

    def test_eio_list_shows_latest_versions(self):
        eio1 = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="object1")

        eio1_url = reverse("enkelvoudiginformatieobject-detail",
                           kwargs={"uuid": eio1.uuid})
        lock1 = self.client.post(f"{eio1_url}/lock").data["lock"]
        self.client.patch(eio1_url, {
            "beschrijving": "object1 versie2",
            "lock": lock1
        })

        eio2 = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="object2")

        eio2_url = reverse("enkelvoudiginformatieobject-detail",
                           kwargs={"uuid": eio2.uuid})
        lock2 = self.client.post(f"{eio2_url}/lock").data["lock"]
        self.client.patch(eio2_url, {
            "beschrijving": "object2 versie2",
            "lock": lock2
        })

        response = self.client.get(reverse(EnkelvoudigInformatieObject))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = response.data["results"]
        self.assertEqual(len(response_data), 2)

        self.assertEqual(response_data[0]["beschrijving"], "object1 versie2")
        self.assertEqual(response_data[1]["beschrijving"], "object2 versie2")

    def test_eio_detail_filter_by_version(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1")

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {
            "beschrijving": "beschrijving2",
            "lock": lock
        })

        response = self.client.get(eio_url, {"versie": 1})

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["beschrijving"], "beschrijving1")

    def test_eio_detail_filter_by_wrong_version_gives_404(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1")

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {
            "beschrijving": "beschrijving2",
            "lock": lock
        })

        response = self.client.get(eio_url, {"versie": 100})
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_eio_detail_filter_by_registratie_op(self):
        with freeze_time("2019-01-01 12:00:00"):
            eio = EnkelvoudigInformatieObjectFactory.create(
                beschrijving="beschrijving1")

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        with freeze_time("2019-01-01 13:00:00"):
            self.client.patch(eio_url, {
                "beschrijving": "beschrijving2",
                "lock": lock
            })

        response = self.client.get(eio_url,
                                   {"registratieOp": "2019-01-01T12:00:00"})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["beschrijving"], "beschrijving1")

    @freeze_time("2019-01-01 12:00:00")
    def test_eio_detail_filter_by_wrong_registratie_op_gives_404(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1")

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {
            "beschrijving": "beschrijving2",
            "lock": lock
        })

        response = self.client.get(eio_url,
                                   {"registratieOp": "2019-01-01T11:59:00"})
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_eio_download_content_filter_by_version(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1", inhoud__data=b"inhoud1")

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(
            eio_url,
            {
                "inhoud": b64encode(b"inhoud2"),
                "beschrijving": "beschrijving2",
                "lock": lock,
            },
        )

        response = self.client.get(eio_url, {"versie": "1"})
        response_download = self.client.get(response.data["inhoud"])

        try:
            self.assertEqual(
                list(response_download.streaming_content)[0], b"inhoud1")
        except AttributeError:
            self.assertEqual(response_download.content, b"inhoud1")

    def test_eio_download_content_filter_by_registratie(self):
        with freeze_time("2019-01-01 12:00:00"):
            eio = EnkelvoudigInformatieObjectFactory.create(
                beschrijving="beschrijving1", inhoud__data=b"inhoud1")

        eio_url = reverse("enkelvoudiginformatieobject-detail",
                          kwargs={"uuid": eio.uuid})
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        with freeze_time("2019-01-01 13:00:00"):
            self.client.patch(
                eio_url,
                {
                    "inhoud": b64encode(b"inhoud2"),
                    "beschrijving": "beschrijving2",
                    "lock": lock,
                },
            )

        response = self.client.get(eio_url,
                                   {"registratieOp": "2019-01-01T12:00:00"})
        response_download = self.client.get(response.data["inhoud"])

        try:
            self.assertEqual(
                list(response_download.streaming_content)[0], b"inhoud1")
        except AttributeError:
            self.assertEqual(response_download.content, b"inhoud1")
Ejemplo n.º 13
0
class ZaakInformatieObjectCMISAPITests(JWTAuthMixin, APICMISTestCase,
                                       OioMixin):

    list_url = reverse_lazy(ZaakInformatieObject)
    heeft_alle_autorisaties = True

    def setUp(self):
        super().setUp()
        site = Site.objects.get_current()
        site.domain = "testserver"
        site.save()

    @freeze_time("2018-09-19T12:25:19+0200")
    def test_create(self):
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        zaak_url = reverse(zaak)
        io = EnkelvoudigInformatieObjectFactory.create(
            informatieobjecttype__concept=False)
        io_url = f"http://testserver{reverse(io)}"
        self.adapter.get(io_url, json=serialise_eio(io, io_url))

        ZaakTypeInformatieObjectTypeFactory.create(
            informatieobjecttype=io.informatieobjecttype,
            zaaktype=zaak.zaaktype)

        titel = "some titel"
        beschrijving = "some beschrijving"
        content = {
            "informatieobject": io_url,
            "zaak": f"http://testserver{zaak_url}",
            "titel": titel,
            "beschrijving": beschrijving,
            "aardRelatieWeergave": "bla",  # Should be ignored by the API
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        # Test response
        self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                         response.data)

        # Test database
        self.assertEqual(ZaakInformatieObject.objects.count(), 1)
        stored_object = ZaakInformatieObject.objects.get()
        self.assertEqual(stored_object.zaak, zaak)
        self.assertEqual(stored_object.aard_relatie, RelatieAarden.hoort_bij)

        expected_url = reverse(stored_object)

        expected_response = content.copy()
        expected_response.update({
            "url":
            f"http://testserver{expected_url}",
            "uuid":
            str(stored_object.uuid),
            "titel":
            titel,
            "beschrijving":
            beschrijving,
            "registratiedatum":
            "2018-09-19T10:25:19Z",
            "aardRelatieWeergave":
            RelatieAarden.labels[RelatieAarden.hoort_bij],
        })

        self.assertEqual(response.json(), expected_response)

        self.assertEqual(ObjectInformatieObject.objects.count(), 1)
        self.assertEqual(EnkelvoudigInformatieObject.objects.count(), 1)

    @freeze_time("2018-09-20 12:00:00")
    def test_registratiedatum_ignored(self):
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        zaak_url = reverse(zaak)
        io = EnkelvoudigInformatieObjectFactory.create(
            informatieobjecttype__concept=False)
        io_url = f"http://testserver{reverse(io)}"
        self.adapter.get(io_url, json=serialise_eio(io, io_url))

        ZaakTypeInformatieObjectTypeFactory.create(
            informatieobjecttype=io.informatieobjecttype,
            zaaktype=zaak.zaaktype)
        content = {
            "informatieobject": io_url,
            "zaak": f"http://testserver{zaak_url}",
            "registratiedatum": "2018-09-19T12:25:20+0200",
        }

        # Send to the API
        self.client.post(self.list_url, content)

        oio = ZaakInformatieObject.objects.get()

        self.assertEqual(
            oio.registratiedatum,
            datetime(2018, 9, 20, 12, 0, 0).replace(tzinfo=timezone.utc),
        )

    def test_duplicate_object(self):
        """
        Test the (informatieobject, object) unique together validation.
        """
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = f"http://testserver{reverse(eio)}"
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        zio_type = ZaakTypeInformatieObjectTypeFactory.create(
            informatieobjecttype__concept=False, zaaktype__concept=False)
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        zio = ZaakInformatieObjectFactory.create(
            informatieobject=eio_url,
            zaak=zaak,
            informatieobject__latest_version__informatieobjecttype=zio_type.
            informatieobjecttype,
        )
        zaak_url = reverse(zio.zaak)

        content = {
            "informatieobject": eio_url,
            "zaak": f"http://testserver{zaak_url}",
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)
        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unique")

    @freeze_time("2018-09-20 12:00:00")
    def test_read_zaakinformatieobject(self):
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = f"http://testserver{reverse(eio)}"
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        zio = ZaakInformatieObjectFactory.create(informatieobject=eio_url,
                                                 zaak=zaak)
        zio_detail_url = reverse(zio)

        response = self.client.get(zio_detail_url)

        # Test response
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        zaak_url = reverse(zio.zaak)
        expected = {
            "url": f"http://testserver{zio_detail_url}",
            "uuid": str(zio.uuid),
            "informatieobject": eio_url,
            "zaak": f"http://testserver{zaak_url}",
            "aardRelatieWeergave":
            RelatieAarden.labels[RelatieAarden.hoort_bij],
            "titel": "",
            "beschrijving": "",
            "registratiedatum": "2018-09-20T12:00:00Z",
        }

        self.assertEqual(response.json(), expected)

    def test_filter_by_zaak(self):
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = eio.get_url()
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        zio = ZaakInformatieObjectFactory.create(informatieobject=eio_url,
                                                 zaak=zaak)
        zaak_url = reverse(zio.zaak)
        zio_list_url = reverse("zaakinformatieobject-list")

        response = self.client.get(
            zio_list_url,
            {"zaak": f"http://openzaak.nl{zaak_url}"},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["zaak"],
                         f"http://openzaak.nl{zaak_url}")

    def test_filter_by_informatieobject(self):
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = f"http://openzaak.nl{reverse(eio)}"
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        ZaakInformatieObjectFactory.create(informatieobject=eio_url, zaak=zaak)

        zio_list_url = reverse("zaakinformatieobject-list")

        response = self.client.get(
            zio_list_url,
            {"informatieobject": eio_url},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["informatieobject"], eio_url)

    def test_update_zaak_and_informatieobject_fails(self):
        zaak = ZaakFactory.create()
        zaak_url = reverse(zaak)
        eio1 = EnkelvoudigInformatieObjectFactory.create()
        eio1_url = f"http://testserver{reverse(eio1)}"
        self.adapter.get(eio1_url, json=serialise_eio(eio1, eio1_url))
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        zio = ZaakInformatieObjectFactory.create(informatieobject=eio1_url,
                                                 zaak=zaak)
        zio_detail_url = reverse(zio)
        eio2 = EnkelvoudigInformatieObjectFactory.create()
        eio2_url = f"http://testserver{reverse(eio2)}"
        self.adapter.get(eio2_url, json=serialise_eio(eio2, eio2_url))

        response = self.client.put(
            zio_detail_url,
            {
                "zaak": f"http://testserver{zaak_url}",
                "informatieobject": eio2_url,
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        for field in ["zaak", "informatieobject"]:
            with self.subTest(field=field):
                error = get_validation_errors(response, field)
                self.assertEqual(error["code"], IsImmutableValidator.code)

    def test_partial_update_zaak_and_informatieobject_fails(self):
        self.create_zaak_besluit_services()
        zaak1 = self.create_zaak()
        zaak2 = self.create_zaak()
        zaak1_url = reverse(zaak1)

        eio1 = EnkelvoudigInformatieObjectFactory.create()
        eio1_url = eio1.get_url()
        self.adapter.get(eio1_url, json=serialise_eio(eio1, eio1_url))
        zio = ZaakInformatieObjectFactory.create(informatieobject=eio1_url,
                                                 zaak=zaak2)
        zio_detail_url = reverse(zio)

        eio2 = EnkelvoudigInformatieObjectFactory.create()
        eio2_url = f"http://testserver{reverse(eio2)}"
        self.adapter.get(eio2_url, json=serialise_eio(eio2, eio2_url))

        response = self.client.patch(
            zio_detail_url,
            {
                "zaak": f"http://testserver{zaak1_url}",
                "informatieobject": eio2_url,
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        for field in ["zaak", "informatieobject"]:
            with self.subTest(field=field):
                error = get_validation_errors(response, field)
                self.assertEqual(error["code"], IsImmutableValidator.code)

    def test_update_zio_metadata(self):
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        zaak_url = reverse(zaak)
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = f"http://testserver{reverse(io)}"
        self.adapter.get(io_url, json=serialise_eio(io, io_url))

        ZaakTypeInformatieObjectTypeFactory.create(
            zaaktype=zaak.zaaktype,
            informatieobjecttype=io.informatieobjecttype)

        zio = ZaakInformatieObjectFactory.create(zaak=zaak,
                                                 informatieobject=io_url)
        zio_detail_url = reverse(zio)

        response = self.client.put(
            zio_detail_url,
            {
                "zaak": f"http://testserver{zaak_url}",
                "informatieobject": io_url,
                "titel": "updated title",
                "beschrijving": "same",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK,
                         response.data)

        self.assertEqual(response.data["titel"], "updated title")
        self.assertEqual(response.data["beschrijving"], "same")

        zio.refresh_from_db()
        self.assertEqual(zio.titel, "updated title")
        self.assertEqual(zio.beschrijving, "same")

    def test_partial_update_zio_metadata(self):
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        io = EnkelvoudigInformatieObjectFactory.create()
        io_url = io.get_url()
        self.adapter.get(io_url, json=serialise_eio(io, io_url))

        ZaakTypeInformatieObjectTypeFactory.create(
            zaaktype=zaak.zaaktype,
            informatieobjecttype=io.informatieobjecttype)

        zio = ZaakInformatieObjectFactory.create(zaak=zaak,
                                                 informatieobject=io_url)
        zio_detail_url = reverse(zio)

        response = self.client.patch(zio_detail_url, {
            "titel": "updated title",
            "beschrijving": "same"
        })

        self.assertEqual(response.status_code, status.HTTP_200_OK,
                         response.data)

        self.assertEqual(response.data["titel"], "updated title")
        self.assertEqual(response.data["beschrijving"], "same")

        zio.refresh_from_db()
        self.assertEqual(zio.titel, "updated title")
        self.assertEqual(zio.beschrijving, "same")

    @freeze_time("2018-09-19T12:25:19+0200")
    def test_delete(self):
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = eio.get_url()
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        zio = ZaakInformatieObjectFactory.create(informatieobject=eio_url,
                                                 zaak=zaak)
        zio_url = reverse(zio)

        response = self.client.delete(zio_url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT,
                         response.data)

        # Relation is gone, zaak still exists.
        self.assertFalse(ZaakInformatieObject.objects.exists())
        self.assertTrue(Zaak.objects.exists())

    def test_representation(self):
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        io = EnkelvoudigInformatieObjectFactory.create(
            informatieobjecttype__concept=False)
        io_url = f"http://testserver{reverse(io)}"
        self.adapter.get(io_url, json=serialise_eio(io, io_url))

        ZaakTypeInformatieObjectTypeFactory.create(
            informatieobjecttype=io.informatieobjecttype,
            zaaktype=zaak.zaaktype)
        zio = ZaakInformatieObjectFactory.create(
            zaak=zaak,
            informatieobject=io_url,
        )
        zio_representation = str(zio)
        expected_representation = f"{zaak.identificatie} - {io_url}"
        self.assertEqual(expected_representation, zio_representation)

    def test_delete_document_unrelated_to_zaak(self):
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()

        # Create a document related to a zaak
        eio_related = EnkelvoudigInformatieObjectFactory.create()
        eio_related_url = f"http://openzaak.nl{reverse(eio_related)}"
        self.adapter.get(eio_related_url,
                         json=serialise_eio(eio_related, eio_related_url))

        ZaakInformatieObjectFactory.create(informatieobject=eio_related_url,
                                           zaak=zaak)

        # Create a document unrelated to a zaak
        eio_unrelated = EnkelvoudigInformatieObjectFactory.create()
        eio_unrelated_url = f"http://openzaak.nl{reverse(eio_unrelated)}"

        response = self.client.delete(eio_unrelated_url)

        self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)
Ejemplo n.º 14
0
class ZaakInformatieobjectTypeFilterAPITests(APITestCase):
    maxDiff = None
    list_url = reverse_lazy(ZaakInformatieobjectType)

    def test_filter_zaaktype(self):
        ztiot1, ztiot2 = ZaakInformatieobjectTypeFactory.create_batch(
            2, zaaktype__concept=False, informatieobjecttype__concept=False)
        url = f"http://testserver.com{reverse(ztiot1)}"
        zaaktype1_url = reverse(ztiot1.zaaktype)
        zaaktype2_url = reverse(ztiot2.zaaktype)
        zaaktype1_url = f"http://testserver.com{zaaktype1_url}"
        zaaktype2_url = f"http://testserver.com{zaaktype2_url}"

        response = self.client.get(self.list_url, {"zaaktype": zaaktype1_url},
                                   HTTP_HOST="testserver.com")

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()["results"]

        self.assertEqual(data[0]["url"], url)
        self.assertEqual(data[0]["zaaktype"], zaaktype1_url)
        self.assertNotEqual(data[0]["zaaktype"], zaaktype2_url)

    def test_filter_informatieobjecttype(self):
        ztiot1, ztiot2 = ZaakInformatieobjectTypeFactory.create_batch(
            2, zaaktype__concept=False, informatieobjecttype__concept=False)
        url = f"http://testserver.com{reverse(ztiot1)}"
        informatieobjecttype1_url = reverse(ztiot1.informatieobjecttype)
        informatieobjecttype2_url = reverse(ztiot2.informatieobjecttype)
        informatieobjecttype1_url = f"http://testserver.com{informatieobjecttype1_url}"
        informatieobjecttype2_url = f"http://testserver.com{informatieobjecttype2_url}"

        response = self.client.get(
            self.list_url,
            {"informatieobjecttype": informatieobjecttype1_url},
            HTTP_HOST="testserver.com",
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()["results"]

        self.assertEqual(data[0]["url"], url)
        self.assertEqual(data[0]["informatieobjecttype"],
                         informatieobjecttype1_url)
        self.assertNotEqual(data[0]["informatieobjecttype"],
                            informatieobjecttype2_url)

    def test_filter_ziot_status_alles(self):
        ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=True)
        ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=True)
        ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=False)
        ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=False)

        response = self.client.get(self.list_url, {"status": "alles"})
        self.assertEqual(response.status_code, 200)

        data = response.json()["results"]

        self.assertEqual(len(data), 4)

    def test_filter_ziot_status_concept(self):
        ziot1 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=True)
        ziot2 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=True)
        ziot3 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=False)
        ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=False)
        ziot1_url = reverse(ziot1)
        ziot2_url = reverse(ziot2)
        ziot3_url = reverse(ziot3)

        response = self.client.get(self.list_url, {"status": "concept"})
        self.assertEqual(response.status_code, 200)

        data = response.json()["results"]

        self.assertEqual(len(data), 3)

        urls = {obj["url"] for obj in data}
        self.assertEqual(
            urls,
            {
                f"http://testserver{ziot1_url}",
                f"http://testserver{ziot2_url}",
                f"http://testserver{ziot3_url}",
            },
        )

    def test_filter_ziot_status_definitief(self):
        ziot1 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=True)
        ziot2 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=True)
        ziot3 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=False)
        ziot4 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=False)
        ziot4_url = reverse(ziot4)

        response = self.client.get(self.list_url, {"status": "definitief"})
        self.assertEqual(response.status_code, 200)

        data = response.json()["results"]

        self.assertEqual(len(data), 1)
        self.assertEqual(data[0]["url"], f"http://testserver{ziot4_url}")
Ejemplo n.º 15
0
class EnkelvoudigInformatieObjectAPITests(JWTAuthMixin, APITestCase):

    list_url = reverse_lazy(EnkelvoudigInformatieObject)
    heeft_alle_autorisaties = True

    def test_list(self):
        EnkelvoudigInformatieObjectFactory.create_batch(4)
        url = reverse("enkelvoudiginformatieobject-list")
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK,
                         response.data)
        self.assertEqual(len(response.data["results"]), 4)

    def test_create(self):
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        content = {
            "identificatie": uuid.uuid4().hex,
            "bronorganisatie": "159351741",
            "creatiedatum": "2018-06-27",
            "titel": "detailed summary",
            "auteur": "test_auteur",
            "formaat": "txt",
            "taal": "eng",
            "bestandsnaam": "dummy.txt",
            "inhoud": b64encode(b"some file content").decode("utf-8"),
            "link": "http://een.link",
            "beschrijving": "test_beschrijving",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "vertrouwelijkheidaanduiding": "openbaar",
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        # Test response
        self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                         response.data)

        # Test database
        stored_object = EnkelvoudigInformatieObject.objects.get()

        self.assertEqual(EnkelvoudigInformatieObject.objects.count(), 1)
        self.assertEqual(stored_object.identificatie, content["identificatie"])
        self.assertEqual(stored_object.bronorganisatie, "159351741")
        self.assertEqual(stored_object.creatiedatum, date(2018, 6, 27))
        self.assertEqual(stored_object.titel, "detailed summary")
        self.assertEqual(stored_object.auteur, "test_auteur")
        self.assertEqual(stored_object.formaat, "txt")
        self.assertEqual(stored_object.taal, "eng")
        self.assertEqual(stored_object.versie, 1)
        self.assertAlmostEqual(stored_object.begin_registratie, timezone.now())
        self.assertEqual(stored_object.bestandsnaam, "dummy.txt")
        self.assertEqual(stored_object.inhoud.read(), b"some file content")
        self.assertEqual(stored_object.link, "http://een.link")
        self.assertEqual(stored_object.beschrijving, "test_beschrijving")
        self.assertEqual(stored_object.informatieobjecttype,
                         informatieobjecttype)
        self.assertEqual(stored_object.vertrouwelijkheidaanduiding, "openbaar")

        expected_url = reverse(stored_object)
        expected_file_url = get_operation_url(
            "enkelvoudiginformatieobject_download", uuid=stored_object.uuid)

        expected_response = content.copy()
        expected_response.update({
            "url":
            f"http://testserver{expected_url}",
            "inhoud":
            f"http://testserver{expected_file_url}?versie=1",
            "versie":
            1,
            "beginRegistratie":
            stored_object.begin_registratie.isoformat().replace("+00:00", "Z"),
            "vertrouwelijkheidaanduiding":
            "openbaar",
            "bestandsomvang":
            stored_object.inhoud.size,
            "integriteit": {
                "algoritme": "",
                "waarde": "",
                "datum": None
            },
            "ontvangstdatum":
            None,
            "verzenddatum":
            None,
            "ondertekening": {
                "soort": "",
                "datum": None
            },
            "indicatieGebruiksrecht":
            None,
            "status":
            "",
            "locked":
            False,
        })

        response_data = response.json()
        self.assertEqual(sorted(response_data.keys()),
                         sorted(expected_response.keys()))

        for key in response_data.keys():
            with self.subTest(field=key):
                self.assertEqual(response_data[key], expected_response[key])

    def test_create_without_identificatie(self):
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        content = {
            "bronorganisatie": "159351741",
            "creatiedatum": "2018-06-27",
            "titel": "detailed summary",
            "auteur": "test_auteur",
            "formaat": "txt",
            "taal": "eng",
            "bestandsnaam": "dummy.txt",
            "inhoud": b64encode(b"some file content").decode("utf-8"),
            "link": "http://een.link",
            "beschrijving": "test_beschrijving",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "vertrouwelijkheidaanduiding": "openbaar",
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        # Test response
        self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                         response.data)

        # Test database
        stored_object = EnkelvoudigInformatieObject.objects.get()

        self.assertEqual(EnkelvoudigInformatieObject.objects.count(), 1)

        # Test generation of human readable identificatie
        self.assertEqual(stored_object.identificatie,
                         "DOCUMENT-2018-0000000001")

    def test_create_fail_informatieobjecttype_max_length(self):
        informatieobjecttype = InformatieObjectTypeFactory.create()
        informatieobjecttype_url = reverse(informatieobjecttype)
        content = {
            "identificatie":
            uuid.uuid4().hex,
            "bronorganisatie":
            "159351741",
            "creatiedatum":
            "2018-06-27",
            "titel":
            "detailed summary",
            "auteur":
            "test_auteur",
            "formaat":
            "txt",
            "taal":
            "eng",
            "bestandsnaam":
            "dummy.txt",
            "inhoud":
            b64encode(b"some file content").decode("utf-8"),
            "link":
            "http://een.link",
            "beschrijving":
            "test_beschrijving",
            "informatieobjecttype":
            f"http://testserver/some-very-long-url-addres-which-exceeds-maximum-"
            f"length-of-hyperlinkedrelatedfield/aaaaaaaaaaaaaaaaaaaaaaaaa/"
            f"{informatieobjecttype_url}",
            "vertrouwelijkheidaanduiding":
            "openbaar",
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        error = get_validation_errors(response, "informatieobjecttype")
        self.assertEqual(error["code"], "max_length")

    def test_read(self):
        test_object = EnkelvoudigInformatieObjectFactory.create()
        # Retrieve from the API
        detail_url = reverse(test_object)

        response = self.client.get(detail_url)

        # Test response
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        file_url = get_operation_url("enkelvoudiginformatieobject_download",
                                     uuid=test_object.uuid)
        expected = {
            "url":
            f"http://testserver{detail_url}",
            "identificatie":
            str(test_object.identificatie),
            "bronorganisatie":
            test_object.bronorganisatie,
            "creatiedatum":
            "2018-06-27",
            "titel":
            "some titel",
            "auteur":
            "some auteur",
            "status":
            "",
            "formaat":
            "some formaat",
            "taal":
            "nld",
            "beginRegistratie":
            test_object.begin_registratie.isoformat().replace("+00:00", "Z"),
            "versie":
            1,
            "bestandsnaam":
            "",
            "inhoud":
            f"http://testserver{file_url}?versie=1",
            "bestandsomvang":
            test_object.inhoud.size,
            "link":
            "",
            "beschrijving":
            "",
            "ontvangstdatum":
            None,
            "verzenddatum":
            None,
            "ondertekening": {
                "soort": "",
                "datum": None
            },
            "indicatieGebruiksrecht":
            None,
            "vertrouwelijkheidaanduiding":
            "openbaar",
            "integriteit": {
                "algoritme": "",
                "waarde": "",
                "datum": None
            },
            "informatieobjecttype":
            f"http://testserver{reverse(test_object.informatieobjecttype)}",
            "locked":
            False,
        }

        response_data = response.json()
        self.assertEqual(sorted(response_data.keys()), sorted(expected.keys()))

        for key in response_data.keys():
            with self.subTest(field=key):
                self.assertEqual(response_data[key], expected[key])

    def test_bestandsomvang(self):
        """
        Assert that the API shows the filesize.
        """
        test_object = EnkelvoudigInformatieObjectFactory.create(
            inhoud__data=b"some content")

        # Retrieve from the API
        detail_url = reverse(
            "enkelvoudiginformatieobject-detail",
            kwargs={
                "version": "1",
                "uuid": test_object.uuid
            },
        )

        response = self.client.get(detail_url)

        # Test response
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["bestandsomvang"], 12)  # 12 bytes

    def test_integrity_empty(self):
        """
        Assert that integrity is optional.
        """
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        content = {
            "identificatie": uuid.uuid4().hex,
            "bronorganisatie": "159351741",
            "creatiedatum": "2018-12-13",
            "titel": "Voorbeelddocument",
            "auteur": "test_auteur",
            "formaat": "text/plain",
            "taal": "eng",
            "bestandsnaam": "dummy.txt",
            "vertrouwelijkheidaanduiding": "openbaar",
            "inhoud": b64encode(b"some file content").decode("utf-8"),
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "integriteit": None,
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        stored_object = EnkelvoudigInformatieObject.objects.get()
        self.assertEqual(stored_object.integriteit, {
            "algoritme": "",
            "waarde": "",
            "datum": None
        })

    def test_integrity_provided(self):
        """
        Assert that integrity is saved.
        """
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        content = {
            "identificatie": uuid.uuid4().hex,
            "bronorganisatie": "159351741",
            "creatiedatum": "2018-12-13",
            "titel": "Voorbeelddocument",
            "auteur": "test_auteur",
            "formaat": "text/plain",
            "taal": "eng",
            "bestandsnaam": "dummy.txt",
            "vertrouwelijkheidaanduiding": "openbaar",
            "inhoud": b64encode(b"some file content").decode("utf-8"),
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "integriteit": {
                "algoritme": "md5",
                "waarde": "27c3a009a3cbba674d0b3e836f2d4685",
                "datum": "2018-12-13",
            },
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        stored_object = EnkelvoudigInformatieObject.objects.get()
        self.assertEqual(
            stored_object.integriteit,
            {
                "algoritme": "md5",
                "waarde": "27c3a009a3cbba674d0b3e836f2d4685",
                "datum": date(2018, 12, 13),
            },
        )

    def test_filter_by_identification(self):
        EnkelvoudigInformatieObjectFactory.create(identificatie="foo")
        EnkelvoudigInformatieObjectFactory.create(identificatie="bar")

        response = self.client.get(self.list_url, {"identificatie": "foo"})

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response_data = response.json()["results"]

        self.assertEqual(len(response_data), 1)
        self.assertEqual(response_data[0]["identificatie"], "foo")

    def test_destroy_no_relations_allowed(self):
        """
        Assert that destroying is possible when there are no relations.
        """
        eio = EnkelvoudigInformatieObjectFactory.create()
        url = reverse(eio)

        response = self.client.delete(url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        self.assertFalse(EnkelvoudigInformatieObject.objects.exists())

    def test_destroy_with_relations_not_allowed(self):
        """
        Assert that destroying is not possible when there are relations.
        """
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        ZaakInformatieObjectFactory.create(informatieobject=eio.canonical)

        response = self.client.delete(eio_path)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "pending-relations")

    def test_validate_unknown_query_params(self):
        EnkelvoudigInformatieObjectFactory.create_batch(2)
        url = reverse(EnkelvoudigInformatieObject)

        response = self.client.get(url, {"someparam": "somevalue"})

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unknown-parameters")

    def test_eio_download_with_accept_application_octet_stream_header(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1", inhoud__data=b"inhoud1")

        eio_url = get_operation_url("enkelvoudiginformatieobject_download",
                                    uuid=eio.uuid)

        response = self.client.get(eio_url,
                                   HTTP_ACCEPT="application/octet-stream")
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        try:
            self.assertEqual(list(response.streaming_content)[0], b"inhoud1")
        except AttributeError:
            self.assertEqual(response._container[0], b"inhoud1")

    def test_invalid_inhoud(self):
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        content = {
            "identificatie": uuid.uuid4().hex,
            "bronorganisatie": "159351741",
            "creatiedatum": "2018-06-27",
            "titel": "detailed summary",
            "auteur": "test_auteur",
            "formaat": "txt",
            "taal": "eng",
            "bestandsnaam": "dummy.txt",
            "inhoud": [1, 2, 3],
            "link": "http://een.link",
            "beschrijving": "test_beschrijving",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "vertrouwelijkheidaanduiding": "openbaar",
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        # Test response
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        error = get_validation_errors(response, "inhoud")

        self.assertEqual(error["code"], "invalid")

    def test_inhoud_invalid_utf8_char_not_b64_encoded(self):
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        content = {
            "identificatie": uuid.uuid4().hex,
            "bronorganisatie": "159351741",
            "creatiedatum": "2018-06-27",
            "titel": "detailed summary",
            "auteur": "test_auteur",
            "formaat": "txt",
            "taal": "eng",
            "bestandsnaam": "dummy.txt",
            "inhoud": "<",
            "link": "http://een.link",
            "beschrijving": "test_beschrijving",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "vertrouwelijkheidaanduiding": "openbaar",
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        # Test response
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_download_deleted_eio(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1", inhoud__data=b"inhoud1")

        eio_url = get_operation_url("enkelvoudiginformatieobject_download",
                                    uuid=eio.uuid)

        response = self.client.delete(reverse(eio))

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        response = self.client.get(eio_url,
                                   HTTP_ACCEPT="application/octet-stream")

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Ejemplo n.º 16
0
class ZaakInformatieobjectTypeAPITests(APITestCase):
    maxDiff = None
    heeft_alle_autorisaties = False
    scopes = [SCOPE_CATALOGI_WRITE, SCOPE_CATALOGI_READ]

    list_url = reverse_lazy(ZaakInformatieobjectType)

    def test_get_list_default_definitief(self):
        ziot1 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=True)
        ziot2 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=True)
        ziot3 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=False)
        ziot4 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=False)
        ziot4_url = reverse(ziot4)

        response = self.client.get(self.list_url)
        self.assertEqual(response.status_code, 200)

        data = response.json()["results"]

        self.assertEqual(len(data), 1)
        self.assertEqual(data[0]["url"], f"http://testserver{ziot4_url}")

    def test_get_detail(self):
        ztiot = ZaakInformatieobjectTypeFactory.create()
        url = reverse(ztiot)
        zaaktype_url = reverse(ztiot.zaaktype)
        informatieobjecttype_url = reverse(ztiot.informatieobjecttype)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        expected = {
            "url": f"http://testserver{url}",
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": ztiot.volgnummer,
            "richting": ztiot.richting,
            "statustype": None,
        }
        self.assertEqual(response.json(), expected)

    def test_create_ziot(self):
        zaaktype = ZaakTypeFactory.create()
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus)
        informatieobjecttype_url = reverse(informatieobjecttype)
        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        ziot = ZaakInformatieobjectType.objects.get(volgnummer=13)

        self.assertEqual(ziot.zaaktype, zaaktype)
        self.assertEqual(ziot.informatieobjecttype, informatieobjecttype)

    def test_create_ziot_not_concept_zaaktype(self):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus)
        informatieobjecttype_url = reverse(informatieobjecttype)
        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_ziot_not_concept_informatieobjecttype(self):
        zaaktype = ZaakTypeFactory.create()
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False, catalogus=zaaktype.catalogus)
        informatieobjecttype_url = reverse(informatieobjecttype)
        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_ziot_fail_not_concept_zaaktype_and_informatieobjecttype(
            self):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False, catalogus=zaaktype.catalogus)
        informatieobjecttype_url = reverse(informatieobjecttype)
        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "non-concept-relation")

    def test_create_ziot_fail_catalogus_mismatch(self):
        zaaktype = ZaakTypeFactory.create()
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "relations-incorrect-catalogus")

    def test_create_ziot_fail_not_unique(self):
        ziot = ZaakInformatieobjectTypeFactory(volgnummer=1)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=ziot.zaaktype.catalogus)
        data = {
            "zaaktype": f"http://testserver.com{reverse(ziot.zaaktype)}",
            "informatieobjecttype":
            f"http://testserver.com{reverse(informatieobjecttype)}",
            "volgnummer": ziot.volgnummer,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unique")

    def test_delete_ziot(self):
        ziot = ZaakInformatieobjectTypeFactory.create()
        ziot_url = reverse(ziot)

        response = self.client.delete(ziot_url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(ZaakInformatieobjectType.objects.filter(id=ziot.id))

    def test_delete_ziot_not_concept_zaaktype(self):
        ziot = ZaakInformatieobjectTypeFactory.create(zaaktype__concept=False)
        ziot_url = reverse(ziot)

        response = self.client.delete(ziot_url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(ZaakInformatieobjectType.objects.filter(id=ziot.id))

    def test_delete_ziot_not_concept_informatieobjecttype(self):
        ziot = ZaakInformatieobjectTypeFactory.create(
            informatieobjecttype__concept=False)
        ziot_url = reverse(ziot)

        response = self.client.delete(ziot_url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(ZaakInformatieobjectType.objects.filter(id=ziot.id))

    def test_delete_ziot_fail_not_concept(self):
        ziot = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=False)
        ziot_url = reverse(ziot)

        response = self.client.delete(ziot_url)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "non-concept-relation")

    def test_update_ziot(self):
        zaaktype = ZaakTypeFactory.create()
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus)
        informatieobjecttype_url = reverse(informatieobjecttype)
        ziot = ZaakInformatieobjectTypeFactory.create(
            zaaktype=zaaktype, informatieobjecttype=informatieobjecttype)
        ziot_url = reverse(ziot)

        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.put(ziot_url, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["volgnummer"], 13)

        ziot.refresh_from_db()
        self.assertEqual(ziot.volgnummer, 13)

    def test_partial_update_ziot(self):
        zaaktype = ZaakTypeFactory.create()
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus)
        ziot = ZaakInformatieobjectTypeFactory.create(
            zaaktype=zaaktype, informatieobjecttype=informatieobjecttype)
        ziot_url = reverse(ziot)

        response = self.client.patch(ziot_url, {"volgnummer": 12})

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["volgnummer"], 12)

        ziot.refresh_from_db()
        self.assertEqual(ziot.volgnummer, 12)

    def test_partial_update_ziot_informatieobjecttype(self):
        zaaktype = ZaakTypeFactory.create()
        ziot = ZaakInformatieobjectTypeFactory.create(zaaktype=zaaktype)
        ziot_url = reverse(ziot)
        informatieobjecttype = InformatieObjectTypeFactory.create()
        informatieobjecttype_url = reverse(informatieobjecttype)

        response = self.client.patch(
            ziot_url, {"informatieobjecttype": informatieobjecttype_url})

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "relations-incorrect-catalogus")

    def test_update_ziot_not_concept_zaaktype(self):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus)
        informatieobjecttype_url = reverse(informatieobjecttype)
        ziot = ZaakInformatieobjectTypeFactory.create(
            zaaktype=zaaktype, informatieobjecttype=informatieobjecttype)
        ziot_url = reverse(ziot)

        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.put(ziot_url, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["volgnummer"], 13)

        ziot.refresh_from_db()
        self.assertEqual(ziot.volgnummer, 13)

    def test_update_ziot_not_concept_informatieobjecttype(self):
        zaaktype = ZaakTypeFactory.create()
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus, concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        ziot = ZaakInformatieobjectTypeFactory.create(
            zaaktype=zaaktype, informatieobjecttype=informatieobjecttype)
        ziot_url = reverse(ziot)

        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.put(ziot_url, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["volgnummer"], 13)

        ziot.refresh_from_db()
        self.assertEqual(ziot.volgnummer, 13)

    def test_update_ziot_not_concept_zaaktype_and_informatieobjecttype_fails(
            self):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus, concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        ziot = ZaakInformatieobjectTypeFactory.create(
            zaaktype=zaaktype, informatieobjecttype=informatieobjecttype)
        ziot_url = reverse(ziot)

        data = {
            "zaaktype": f"http://testserver{zaaktype_url}",
            "informatieobjecttype":
            f"http://testserver{informatieobjecttype_url}",
            "volgnummer": 13,
            "richting": RichtingChoices.inkomend,
        }

        response = self.client.put(ziot_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "non-concept-relation")

    def test_partial_update_ziot_not_concept_zaaktype(self):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus)
        informatieobjecttype_url = reverse(informatieobjecttype)
        ziot = ZaakInformatieobjectTypeFactory.create(
            zaaktype=zaaktype, informatieobjecttype=informatieobjecttype)
        ziot_url = reverse(ziot)

        response = self.client.patch(ziot_url, {"volgnummer": 12})

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["volgnummer"], 12)

        ziot.refresh_from_db()
        self.assertEqual(ziot.volgnummer, 12)

    def test_partial_update_ziot_not_concept_informatieobjecttype(self):
        zaaktype = ZaakTypeFactory.create()
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus, concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        ziot = ZaakInformatieobjectTypeFactory.create(
            zaaktype=zaaktype, informatieobjecttype=informatieobjecttype)
        ziot_url = reverse(ziot)

        response = self.client.patch(ziot_url, {"volgnummer": 12})

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["volgnummer"], 12)

        ziot.refresh_from_db()
        self.assertEqual(ziot.volgnummer, 12)

    def test_partial_update_ziot_not_concept_zaaktype_and_informatieobjecttype_fails(
        self, ):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=zaaktype.catalogus, concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        ziot = ZaakInformatieobjectTypeFactory.create(
            zaaktype=zaaktype, informatieobjecttype=informatieobjecttype)
        ziot_url = reverse(ziot)

        response = self.client.patch(ziot_url, {"volgnummer": 12})

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "non-concept-relation")

    def test_full_update_ziot_informatieobjecttype(self):
        zaaktype = ZaakTypeFactory.create()
        ziot = ZaakInformatieobjectTypeFactory.create(zaaktype=zaaktype)
        ziot_url = reverse(ziot)
        informatieobjecttype = InformatieObjectTypeFactory.create()
        informatieobjecttype_url = reverse(informatieobjecttype)
        zaaktype_url = reverse(ziot.zaaktype)

        response = self.client.put(
            ziot_url,
            {
                "zaaktype": f"http://testserver{zaaktype_url}",
                "informatieobjecttype": informatieobjecttype_url,
                "volgnummer": ziot.volgnummer,
                "richting": ziot.richting,
                "statustype": None,
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "relations-incorrect-catalogus")
Ejemplo n.º 17
0
class EnkelvoudigInformatieObjectVersionHistoryAPITests(JWTAuthMixin, APICMISTestCase):
    list_url = reverse_lazy(EnkelvoudigInformatieObject)
    heeft_alle_autorisaties = True

    def test_eio_update(self):
        import os

        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1", informatieobjecttype__concept=False
        )

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )

        eio_response = self.client.get(eio_url)
        eio_data = eio_response.data

        lock_response = self.client.post(f"{eio_url}/lock")
        self.assertEqual(lock_response.status_code, status.HTTP_200_OK)
        lock = lock_response.data["lock"]
        eio_data.update(
            {
                "beschrijving": "beschrijving2",
                "inhoud": b64encode(b"aaaaa"),
                "lock": lock,
            }
        )

        del eio_data["integriteit"]
        del eio_data["ondertekening"]

        response = self.client.put(eio_url, eio_data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response_data = response.json()

        self.assertEqual(response_data["beschrijving"], "beschrijving2")

        # The private working copy and the original count as 2 documents in Alfresco
        eios = EnkelvoudigInformatieObject.objects.filter(uuid=eio.uuid).order_by(
            "-versie"
        )

        os.environ["foo"] = "bar"

        self.assertEqual(len(eios), 2)

        latest_version = eios[0]
        self.assertEqual(latest_version.versie, 2)
        self.assertEqual(latest_version.beschrijving, "beschrijving2")

        first_version = eios[1]
        self.assertEqual(first_version.versie, 1)
        self.assertEqual(first_version.beschrijving, "beschrijving1")

    def test_eio_partial_update(self):
        eio = EnkelvoudigInformatieObjectFactory.create(beschrijving="beschrijving1")

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        response = self.client.patch(
            eio_url, {"beschrijving": "beschrijving2", "lock": lock}
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response_data = response.json()

        self.assertEqual(response_data["beschrijving"], "beschrijving2")

        eios = EnkelvoudigInformatieObject.objects.filter(uuid=eio.uuid).order_by(
            "-versie"
        )
        self.assertEqual(len(eios), 2)

        latest_version = eios.first()
        self.assertEqual(latest_version.versie, 2)
        self.assertEqual(latest_version.beschrijving, "beschrijving2")

        first_version = eios[1]
        self.assertEqual(first_version.versie, 1)
        self.assertEqual(first_version.beschrijving, "beschrijving1")

    def test_eio_delete(self):
        eio = EnkelvoudigInformatieObjectFactory.create(beschrijving="beschrijving1")

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {"beschrijving": "beschrijving2", "lock": lock})

        response = self.client.delete(eio_url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(EnkelvoudigInformatieObjectCanonical.objects.exists())
        self.assertFalse(EnkelvoudigInformatieObject.objects.exists())

    def test_eio_update_content(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            inhoud=BytesIO(b"Content before update"),
            informatieobjecttype__concept=False,
        )

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )

        eio_response = self.client.get(eio_url)
        eio_data = eio_response.data

        lock_response = self.client.post(f"{eio_url}/lock")
        self.assertEqual(lock_response.status_code, status.HTTP_200_OK)
        lock = lock_response.data["lock"]
        eio_data.update(
            {"inhoud": b64encode(b"Content after update"), "lock": lock,}
        )

        del eio_data["integriteit"]
        del eio_data["ondertekening"]

        update_response = self.client.put(eio_url, eio_data)
        self.assertEqual(update_response.status_code, status.HTTP_200_OK)

        unlock_url = get_operation_url(
            "enkelvoudiginformatieobject_unlock", uuid=eio.uuid
        )

        unlock_content = {"lock": lock}
        unlock_response = self.client.post(unlock_url, unlock_content)
        self.assertEqual(unlock_response.status_code, status.HTTP_204_NO_CONTENT)

        updated_eio = EnkelvoudigInformatieObject.objects.first()
        self.assertEqual(updated_eio.inhoud.read(), b"Content after update")

    def test_eio_detail_retrieves_latest_version(self):
        eio = EnkelvoudigInformatieObjectFactory.create(beschrijving="beschrijving1")

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {"beschrijving": "beschrijving2", "lock": lock})

        response = self.client.get(eio_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["beschrijving"], "beschrijving2")

    def test_eio_list_shows_latest_versions(self):
        eio1 = EnkelvoudigInformatieObjectFactory.create(beschrijving="object1")

        eio1_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio1.uuid}
        )
        lock1 = self.client.post(f"{eio1_url}/lock").data["lock"]
        self.client.patch(eio1_url, {"beschrijving": "object1 versie2", "lock": lock1})

        eio2 = EnkelvoudigInformatieObjectFactory.create(beschrijving="object2",)

        eio2_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio2.uuid}
        )
        lock2 = self.client.post(f"{eio2_url}/lock").data["lock"]
        self.client.patch(eio2_url, {"beschrijving": "object2 versie2", "lock": lock2})

        import os

        os.environ["foo"] = "bar"

        response = self.client.get(reverse(EnkelvoudigInformatieObject))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = response.data["results"]
        self.assertEqual(len(response_data), 2)

        self.assertEqual(response_data[0]["beschrijving"], "object1 versie2")
        self.assertEqual(response_data[1]["beschrijving"], "object2 versie2")

    def test_eio_detail_filter_by_version(self):
        eio = EnkelvoudigInformatieObjectFactory.create(beschrijving="beschrijving1")

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {"beschrijving": "beschrijving2", "lock": lock})

        response = self.client.get(eio_url, {"versie": 1})

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["beschrijving"], "beschrijving1")

    def test_eio_detail_filter_by_wrong_version_gives_404(self):
        eio = EnkelvoudigInformatieObjectFactory.create(beschrijving="beschrijving1")

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {"beschrijving": "beschrijving2", "lock": lock})

        response = self.client.get(eio_url, {"versie": 100})
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_eio_detail_filter_by_registratie_op(self):
        with freeze_time("2019-01-01 12:00:00"):
            eio = EnkelvoudigInformatieObjectFactory.create(
                beschrijving="beschrijving1"
            )

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        with freeze_time("2019-01-01 13:00:00"):
            self.client.patch(eio_url, {"beschrijving": "beschrijving2", "lock": lock})

        response = self.client.get(eio_url, {"registratieOp": "2019-01-01T12:00:00"})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["beschrijving"], "beschrijving1")

    @freeze_time("2019-01-01 12:00:00")
    def test_eio_detail_filter_by_wrong_registratie_op_gives_404(self):
        eio = EnkelvoudigInformatieObjectFactory.create(beschrijving="beschrijving1")

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(eio_url, {"beschrijving": "beschrijving2", "lock": lock})

        response = self.client.get(eio_url, {"registratieOp": "2019-01-01T11:59:00"})
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_eio_download_content_filter_by_version(self):
        eio = EnkelvoudigInformatieObjectFactory.create(
            beschrijving="beschrijving1", inhoud__data=b"inhoud1"
        )

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        self.client.patch(
            eio_url,
            {
                "inhoud": b64encode(b"inhoud2"),
                "beschrijving": "beschrijving2",
                "lock": lock,
            },
        )

        response = self.client.get(eio_url, {"versie": "1"})
        response_download = self.client.get(response.data["inhoud"])

        self.assertTrue(response_download.streaming)
        self.assertEqual(response_download.getvalue(), b"inhoud1")

    def test_eio_download_content_filter_by_registratie(self):
        with freeze_time("2019-01-01 12:00:00"):
            eio = EnkelvoudigInformatieObjectFactory.create(
                beschrijving="beschrijving1", inhoud__data=b"inhoud1"
            )

        eio_url = reverse(
            "enkelvoudiginformatieobject-detail", kwargs={"uuid": eio.uuid}
        )
        lock = self.client.post(f"{eio_url}/lock").data["lock"]
        with freeze_time("2019-01-01 13:00:00"):
            self.client.patch(
                eio_url,
                {
                    "inhoud": b64encode(b"inhoud2"),
                    "beschrijving": "beschrijving2",
                    "lock": lock,
                },
            )

        response = self.client.get(eio_url, {"registratieOp": "2019-01-01T12:00:00"})
        response_download = self.client.get(response.data["inhoud"])
        self.assertEqual(response_download.getvalue(), b"inhoud1")
class ExternalDocumentDestroyTests(JWTAuthMixin, APITestCase):
    heeft_alle_autorisaties = True

    list_url = reverse_lazy(BesluitInformatieObject)
    base = "https://external.documenten.nl/api/v1/"
    document = f"{base}enkelvoudiginformatieobjecten/{uuid.uuid4()}"

    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        Service.objects.create(
            api_type=APITypes.drc,
            api_root=cls.base,
            label="external documents",
            auth_type=AuthTypes.no_auth,
        )

    def test_destroy_with_external_informatieobject(self):
        oio = f"{self.base}objectinformatieobjecten/{uuid.uuid4()}"
        informatieobjecttype = InformatieObjectTypeFactory.create()

        with requests_mock.Mocker(real_http=True) as m:
            mock_service_oas_get(m, APITypes.drc, self.base)
            m.get(
                self.document,
                json=get_eio_response(
                    self.document,
                    informatieobjecttype=f"http://openzaak.nl{reverse(informatieobjecttype)}",
                ),
            )
            m.delete(oio, status_code=204)

            bio = BesluitInformatieObjectFactory.create(
                informatieobject=self.document, _objectinformatieobject_url=oio
            )
            bio_url = reverse(bio)

            response = self.client.delete(bio_url, HTTP_HOST="openzaak.nl")

        self.assertEqual(
            response.status_code, status.HTTP_204_NO_CONTENT, response.data
        )
        self.assertEqual(BesluitInformatieObject.objects.count(), 0)

        history_delete = [
            req
            for req in m.request_history
            if req.method == "DELETE" and req.url == oio
        ]
        self.assertEqual(len(history_delete), 1)

    def test_destroy_with_external_informatieobject_fail_send(self):
        oio = f"{self.base}objectinformatieobjecten/{uuid.uuid4()}"
        informatieobjecttype = InformatieObjectTypeFactory.create()

        with requests_mock.Mocker(real_http=True) as m:
            mock_service_oas_get(m, APITypes.drc, self.base)
            m.get(
                self.document,
                json=get_eio_response(
                    self.document,
                    informatieobjecttype=f"http://openzaak.nl{reverse(informatieobjecttype)}",
                ),
            )
            m.delete(oio, status_code=404, text="Not found")

            bio = BesluitInformatieObjectFactory.create(
                informatieobject=self.document, _objectinformatieobject_url=oio
            )
            bio_url = reverse(bio)

            response = self.client.delete(bio_url, HTTP_HOST="openzaak.nl")

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "informatieobject")
        self.assertEqual(error["code"], "pending-relations")
Ejemplo n.º 19
0
class InformatieObjectStatusTests(JWTAuthMixin, APITestCase):

    url = reverse_lazy("enkelvoudiginformatieobject-list")
    heeft_alle_autorisaties = True

    def test_ontvangen_informatieobjecten(self):
        """
        Assert certain statuses are not allowed for received documents.

        RGBZ 2.00.02 deel II Concept 20180613: De waarden ?in bewerking?
        en ?ter vaststelling? zijn niet van toepassing op ontvangen
        informatieobjecten.
        """
        informatieobjecttype = InformatieObjectTypeFactory.create()
        informatieobjecttype_url = reverse(informatieobjecttype)
        invalid_statuses = (Statussen.in_bewerking, Statussen.ter_vaststelling)
        data = {
            "bronorganisatie": "319582462",
            "creatiedatum": "2018-12-24",
            "titel": "dummy",
            "auteur": "dummy",
            "taal": "nld",
            "inhoud": "aGVsbG8gd29ybGQ=",
            "informatieobjecttype": informatieobjecttype_url,
            "ontvangstdatum": "2018-12-24",
        }

        for invalid_status in invalid_statuses:
            with self.subTest(status=invalid_status):
                _data = data.copy()
                _data["status"] = invalid_status

                response = self.client.post(self.url, _data)

            self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
            error = get_validation_errors(response, "status")
            self.assertEqual(error["code"], "invalid_for_received")

    def test_informatieobjecten_niet_ontvangen(self):
        """
        All statusses should be allowed when the informatieobject doesn't have
        a receive date.
        """
        for valid_status, _ in Statussen.choices:
            with self.subTest(status=status):
                data = {"ontvangstdatum": None, "status": valid_status}

                response = self.client.post(self.url, data)

            error = get_validation_errors(response, "status")
            self.assertIsNone(error)

    def test_status_set_ontvangstdatum_is_set_later(self):
        """
        Assert that setting the ontvangstdatum later, after an 'invalid' status
        has been set, is not possible.
        """
        eio = EnkelvoudigInformatieObjectFactory.create(ontvangstdatum=None)
        url = reverse("enkelvoudiginformatieobject-detail",
                      kwargs={"uuid": eio.uuid})

        for invalid_status in (Statussen.in_bewerking,
                               Statussen.ter_vaststelling):
            with self.subTest(status=invalid_status):
                eio.status = invalid_status
                eio.save()
                data = {"ontvangstdatum": "2018-12-24"}

                response = self.client.patch(url, data)

                self.assertEqual(response.status_code,
                                 status.HTTP_400_BAD_REQUEST)
                error = get_validation_errors(response, "status")
                self.assertEqual(error["code"], "invalid_for_received")
class OIOCreateExternalURLsTests(JWTAuthMixin, APICMISTestCase):
    heeft_alle_autorisaties = True
    list_url = reverse_lazy(ObjectInformatieObject)

    besluit = "https://externe.catalogus.nl/api/v1/besluiten/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
    besluittype = "https://externe.catalogus.nl/api/v1/besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"
    zaak = (
        "https://externe.catalogus.nl/api/v1/zaken/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
    )
    zaaktype = "https://externe.catalogus.nl/api/v1/zaaktypen/b71f72ef-198d-44d8-af64-ae1932df830a"
    catalogus = "https://externe.catalogus.nl/api/v1/catalogussen/5c4c492b-3548-4258-b17f-0e2e31dcfe25"

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        # Mocking the calls for the CMIS adapter
        Service.objects.create(
            api_type=APITypes.zrc,
            api_root="https://externe.catalogus.nl/api/v1/",
            label="external zaken",
            auth_type=AuthTypes.no_auth,
        )

    def test_create_external_zaak(self):
        mock_service_oas_get(self.adapter, APITypes.zrc,
                             "https://externe.catalogus.nl/api/v1/")

        self.adapter.get(self.zaak,
                         json=get_zaak_response(self.zaak, self.zaaktype))
        self.adapter.get(self.zaaktype,
                         json=get_zaak_response(self.catalogus, self.zaaktype))

        # The test
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"

        response = self.client.post(
            self.list_url,
            {
                "object": self.zaak,
                "informatieobject": eio_url,
                "objectType": "zaak",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                         response.data)

        oio = ObjectInformatieObject.objects.get()
        self.assertEqual(oio.get_informatieobject_url(), eio_url)

        self.assertEqual(oio.object, self.zaak)

    def test_create_external_besluit(self):
        mock_service_oas_get(self.adapter, APITypes.zrc,
                             "https://externe.catalogus.nl/api/v1/")

        self.adapter.get(
            self.besluit,
            json=get_besluit_response(self.besluit, self.besluittype,
                                      self.zaak),
        )
        self.adapter.get(self.zaak,
                         json=get_zaak_response(self.zaak, self.zaaktype))
        self.adapter.get(self.zaaktype,
                         json=get_zaak_response(self.catalogus, self.zaaktype))

        # The test
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"

        response = self.client.post(
            self.list_url,
            {
                "object": self.besluit,
                "informatieobject": eio_url,
                "objectType": "besluit",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                         response.data)

        oio = ObjectInformatieObject.objects.get()

        self.assertEqual(oio.get_informatieobject_url(), eio_url)
        self.assertEqual(oio.object, self.besluit)

    def test_create_external_zaak_fail_invalid_schema(self):
        zaak = "https://externe.catalogus.nl/api/v1/zaken/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        zaaktype = "https://externe.catalogus.nl/api/v1/zaaktypen/b71f72ef-198d-44d8-af64-ae1932df830a"

        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = reverse(eio)

        self.adapter.register_uri(
            "GET",
            zaak,
            json={
                "url": zaak,
                "uuid": "d781cd1b-f100-4051-9543-153b93299da4",
                "identificatie": "ZAAK-2019-0000000001",
                "zaaktype": zaaktype,
            },
        )

        response = self.client.post(
            self.list_url,
            {
                "object": zaak,
                "informatieobject": f"http://testserver{eio_url}",
                "objectType": "zaak",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "object")
        self.assertEqual(error["code"], "invalid-resource")

    def test_create_external_besluit_fail_invalid_schema(self):
        besluit = "https://externe.catalogus.nl/api/v1/besluiten/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluittype = "https://externe.catalogus.nl/api/v1/besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"

        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = reverse(eio)

        self.adapter.register_uri(
            "GET",
            besluit,
            json={
                "url": besluit,
                "identificatie": "BESLUIT-2019-0000000001",
                "besluittype": besluittype,
            },
        )

        response = self.client.post(
            self.list_url,
            {
                "object": besluit,
                "informatieobject": f"http://testserver{eio_url}",
                "objectType": "besluit",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "object")
        self.assertEqual(error["code"], "invalid-resource")

    def test_create_fail_not_unique(self):
        mock_service_oas_get(self.adapter, APITypes.zrc,
                             "https://externe.catalogus.nl/api/v1/")

        self.adapter.get(
            self.besluit,
            json=get_besluit_response(self.besluit, self.besluittype,
                                      self.zaak),
        )
        self.adapter.get(self.zaak,
                         json=get_zaak_response(self.zaak, self.zaaktype))
        self.adapter.get(self.zaaktype,
                         json=get_zaak_response(self.catalogus, self.zaaktype))

        # The test
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = f"http://testserver{reverse(eio)}"

        ObjectInformatieObject.objects.create(informatieobject=eio_url,
                                              besluit=self.besluit,
                                              object_type="besluit")

        response = self.client.post(
            self.list_url,
            {
                "object": self.besluit,
                "informatieobject": eio_url,
                "objectType": "besluit",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unique")

    def test_read_external_zaak(self):
        mock_service_oas_get(self.adapter, APITypes.zrc,
                             "https://externe.catalogus.nl/api/v1/")

        self.adapter.get(self.zaak,
                         json=get_zaak_response(self.zaak, self.zaaktype))
        self.adapter.get(self.zaaktype,
                         json=get_zaak_response(self.catalogus, self.zaaktype))

        eio = EnkelvoudigInformatieObjectFactory.create()
        oio = ObjectInformatieObject.objects.create(
            informatieobject=f"http://testserver{reverse(eio)}",
            zaak=self.zaak,
            object_type="zaak",
        )

        url = reverse(oio)

        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()

        self.assertEqual(data["object"], self.zaak)
        self.assertEqual(data["informatieobject"],
                         f"http://testserver{reverse(eio)}")

    def test_read_external_besluit(self):
        mock_service_oas_get(self.adapter, APITypes.zrc,
                             "https://externe.catalogus.nl/api/v1/")

        self.adapter.get(
            self.besluit,
            json=get_besluit_response(self.besluit, self.besluittype,
                                      self.zaak),
        )
        self.adapter.get(self.zaak,
                         json=get_zaak_response(self.zaak, self.zaaktype))
        self.adapter.get(self.zaaktype,
                         json=get_zaak_response(self.catalogus, self.zaaktype))

        # The test
        eio = EnkelvoudigInformatieObjectFactory.create()
        oio = ObjectInformatieObject.objects.create(
            informatieobject=f"http://testserver{reverse(eio)}",
            besluit=self.besluit,
            object_type="besluit",
        )

        url = reverse(oio)

        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()

        self.assertEqual(data["object"], self.besluit)
        self.assertEqual(data["informatieobject"],
                         f"http://testserver{reverse(eio)}")

    def test_list_filter_by_external_zaak(self):
        eio = EnkelvoudigInformatieObjectFactory.create()

        mock_service_oas_get(self.adapter, APITypes.zrc,
                             "https://externe.catalogus.nl/api/v1/")

        zaak1 = "https://externe.catalogus.nl/api/v1/zaken/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        zaak2 = "https://externe.catalogus.nl/api/v1/zaken/b923543f-97aa-4a55-8c20-889b5906cf75"
        zaaktype1 = "https://externe.catalogus.nl/api/v1/zaaktypen/b71f72ef-198d-44d8-af64-ae1932df830a"
        zaaktype2 = "https://externe.catalogus.nl/api/v1/zaaktypen/5c4c492b-3548-4258-b17f-0e2e31dcfe25"
        catalogus1 = "https://externe.catalogus.nl/api/v1/catalogussen/5c4c492b-3548-4258-b17f-0e2e31dcfe25"
        catalogus2 = "https://externe.catalogus.nl/api/v1/catalogussen/a8e03e86-152d-4e8c-83fc-047645cfc585"

        self.adapter.get(zaak1, json=get_zaak_response(zaak1, zaaktype1))
        self.adapter.get(zaaktype1,
                         json=get_zaak_response(catalogus1, zaaktype1))
        self.adapter.get(zaak2, json=get_zaak_response(zaak2, zaaktype2))
        self.adapter.get(zaaktype2,
                         json=get_zaak_response(catalogus2, zaaktype2))

        ObjectInformatieObject.objects.create(
            informatieobject=f"http://testserver{reverse(eio)}",
            zaak=zaak1,
            object_type="zaak",
        )
        ObjectInformatieObject.objects.create(
            informatieobject=f"http://testserver{reverse(eio)}",
            zaak=zaak2,
            object_type="zaak",
        )

        url = reverse(ObjectInformatieObject)

        response = self.client.get(url, {"object": zaak2})

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["object"], zaak2)

    def test_list_filter_by_external_besluit(self):
        eio = EnkelvoudigInformatieObjectFactory.create()
        mock_service_oas_get(self.adapter, APITypes.zrc,
                             "https://externe.catalogus.nl/api/v1/")

        # Needed for the CMIS adapter
        zaak1 = "https://externe.catalogus.nl/api/v1/zaken/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        zaak2 = "https://externe.catalogus.nl/api/v1/zaken/b923543f-97aa-4a55-8c20-889b5906cf75"
        zaaktype1 = "https://externe.catalogus.nl/api/v1/zaaktypen/b71f72ef-198d-44d8-af64-ae1932df830a"
        zaaktype2 = "https://externe.catalogus.nl/api/v1/zaaktypen/5c4c492b-3548-4258-b17f-0e2e31dcfe25"
        catalogus1 = "https://externe.catalogus.nl/api/v1/catalogussen/5c4c492b-3548-4258-b17f-0e2e31dcfe25"
        catalogus2 = "https://externe.catalogus.nl/api/v1/catalogussen/a8e03e86-152d-4e8c-83fc-047645cfc585"
        besluit1 = "https://externe.catalogus.nl/api/v1/besluiten/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluit2 = "https://externe.catalogus.nl/api/v1/besluiten/b923543f-97aa-4a55-8c20-889b5906cf75"
        besluittype1 = "https://externe.catalogus.nl/api/v1/besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"
        besluittype2 = "https://externe.catalogus.nl/api/v1/besluittypen/3665b9be-6ac5-4075-8736-d79598e5325c"

        self.adapter.get(zaak1, json=get_zaak_response(zaak1, zaaktype1))
        self.adapter.get(zaaktype1,
                         json=get_zaak_response(catalogus1, zaaktype1))
        self.adapter.get(zaak2, json=get_zaak_response(zaak2, zaaktype2))
        self.adapter.get(zaaktype2,
                         json=get_zaak_response(catalogus2, zaaktype2))
        self.adapter.get(besluit1,
                         json=get_besluit_response(besluit1, besluittype1,
                                                   zaak1))
        self.adapter.get(besluit2,
                         json=get_besluit_response(besluit2, besluittype2,
                                                   zaak2))

        ObjectInformatieObject.objects.create(
            informatieobject=f"http://testserver{reverse(eio)}",
            besluit=besluit1,
            object_type="besluit",
        )
        ObjectInformatieObject.objects.create(
            informatieobject=f"http://testserver{reverse(eio)}",
            besluit=besluit2,
            object_type="besluit",
        )

        url = reverse(ObjectInformatieObject)

        response = self.client.get(url, {"object": besluit2})

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["object"], besluit2)

    def test_destroy_external_zaak(self):
        mock_service_oas_get(self.adapter, APITypes.zrc,
                             "https://externe.catalogus.nl/api/v1/")

        self.adapter.get(self.zaak,
                         json=get_zaak_response(self.zaak, self.zaaktype))
        self.adapter.get(self.zaaktype,
                         json=get_zaak_response(self.catalogus, self.zaaktype))

        eio = EnkelvoudigInformatieObjectFactory.create()
        oio = ObjectInformatieObject.objects.create(
            informatieobject=f"http://testserver{reverse(eio)}",
            zaak=self.zaak,
            object_type="zaak",
        )
        url = reverse(oio)

        self.adapter.get(self.zaak,
                         json=get_zaak_response(self.zaak, self.zaaktype))

        response = self.client.delete(url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(ObjectInformatieObject.objects.count(), 0)

    def test_destroy_external_besluit(self):
        mock_service_oas_get(self.adapter, APITypes.zrc,
                             "https://externe.catalogus.nl/api/v1/")

        self.adapter.get(
            self.besluit,
            json=get_besluit_response(self.besluit, self.besluittype,
                                      self.zaak),
        )
        self.adapter.get(self.zaak,
                         json=get_zaak_response(self.zaak, self.zaaktype))
        self.adapter.get(self.zaaktype,
                         json=get_zaak_response(self.catalogus, self.zaaktype))

        eio = EnkelvoudigInformatieObjectFactory.create()

        oio = ObjectInformatieObject.objects.create(
            informatieobject=f"http://testserver{reverse(eio)}",
            besluit=self.besluit,
            object_type="besluit",
        )

        url = reverse(oio)

        self.adapter.register_uri(
            "GET",
            self.besluit,
            json=get_besluit_response(self.besluit, self.besluittype),
        )

        response = self.client.delete(url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(ObjectInformatieObject.objects.count(), 0)
class AuditTrailTests(JWTAuthMixin, APITestCase):

    informatieobject_list_url = reverse_lazy(EnkelvoudigInformatieObject)
    objectinformatieobject_list_url = reverse_lazy(ObjectInformatieObject)
    gebruiksrechten_list_url = reverse_lazy(Gebruiksrechten)

    heeft_alle_autorisaties = True

    def _create_enkelvoudiginformatieobject(self, **HEADERS):
        content = {
            'identificatie': uuid.uuid4().hex,
            'bronorganisatie': '159351741',
            'creatiedatum': '2018-06-27',
            'titel': 'detailed summary',
            'auteur': 'test_auteur',
            'formaat': 'txt',
            'taal': 'eng',
            'bestandsnaam': 'dummy.txt',
            'inhoud': b64encode(b'some file content').decode('utf-8'),
            'link': 'http://een.link',
            'beschrijving': 'test_beschrijving',
            'informatieobjecttype':
            'https://example.com/ztc/api/v1/catalogus/1/informatieobjecttype/1',
            'vertrouwelijkheidaanduiding': 'openbaar',
        }

        response = self.client.post(self.informatieobject_list_url, content,
                                    **HEADERS)

        return response.data

    def test_create_enkelvoudiginformatieobject_audittrail(self):
        informatieobject_data = self._create_enkelvoudiginformatieobject()
        informatieobject_url = informatieobject_data['url']

        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 1)

        # Verify that the audittrail for the EnkelvoudigInformatieObject creation contains the correct
        # information
        informatieobject_create_audittrail = audittrails.get()
        self.assertEqual(informatieobject_create_audittrail.bron, 'DRC')
        self.assertEqual(informatieobject_create_audittrail.actie, 'create')
        self.assertEqual(informatieobject_create_audittrail.resultaat, 201)
        self.assertEqual(informatieobject_create_audittrail.oud, None)
        self.assertEqual(informatieobject_create_audittrail.nieuw,
                         informatieobject_data)

    @override_settings(ZDS_CLIENT_CLASS='vng_api_common.mocks.MockClient')
    def test_create_objectinformatieobject_audittrail(self):
        informatieobject = EnkelvoudigInformatieObjectFactory.create()

        content = {
            'informatieobject':
            reverse('enkelvoudiginformatieobject-detail',
                    kwargs={'uuid': informatieobject.uuid}),
            'object':
            ZAAK,
            'objectType':
            ObjectTypes.zaak,
        }

        # Send to the API
        objectinformatieobject_response = self.client.post(
            self.objectinformatieobject_list_url, content).data

        informatieobject_url = objectinformatieobject_response[
            'informatieobject']
        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 1)

        # Verify that the audittrail for the ObjectInformatieObject creation
        # contains the correct information
        objectinformatieobject_create_audittrail = audittrails.get()
        self.assertEqual(objectinformatieobject_create_audittrail.bron, 'DRC')
        self.assertEqual(objectinformatieobject_create_audittrail.actie,
                         'create')
        self.assertEqual(objectinformatieobject_create_audittrail.resultaat,
                         201)
        self.assertEqual(objectinformatieobject_create_audittrail.oud, None)
        self.assertEqual(objectinformatieobject_create_audittrail.nieuw,
                         objectinformatieobject_response)

    def test_create_and_delete_gebruiksrechten_audittrail(self):
        informatieobject = EnkelvoudigInformatieObjectFactory.create()

        content = {
            'informatieobject':
            reverse('enkelvoudiginformatieobject-detail',
                    kwargs={'uuid': informatieobject.uuid}),
            'startdatum':
            datetime.now(),
            'omschrijvingVoorwaarden':
            'test'
        }

        gebruiksrechten_response = self.client.post(
            self.gebruiksrechten_list_url, content).data

        informatieobject_url = gebruiksrechten_response['informatieobject']
        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 1)

        # Verify that the audittrail for the Gebruiksrechten creation
        # contains the correct information
        gebruiksrechten_create_audittrail = audittrails.get()
        self.assertEqual(gebruiksrechten_create_audittrail.bron, 'DRC')
        self.assertEqual(gebruiksrechten_create_audittrail.actie, 'create')
        self.assertEqual(gebruiksrechten_create_audittrail.resultaat, 201)
        self.assertEqual(gebruiksrechten_create_audittrail.oud, None)
        self.assertEqual(gebruiksrechten_create_audittrail.nieuw,
                         gebruiksrechten_response)

        delete_response = self.client.delete(gebruiksrechten_response['url'])

        self.assertEqual(delete_response.status_code,
                         status.HTTP_204_NO_CONTENT)
        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 2)

        # Verify that the audittrail for the Gebruiksrechten deletion
        # contains the correct information
        gebruiksrechten_delete_audittrail = audittrails[1]
        self.assertEqual(gebruiksrechten_delete_audittrail.bron, 'DRC')
        self.assertEqual(gebruiksrechten_delete_audittrail.actie, 'destroy')
        self.assertEqual(gebruiksrechten_delete_audittrail.resultaat, 204)
        self.assertEqual(gebruiksrechten_delete_audittrail.oud,
                         gebruiksrechten_response)
        self.assertEqual(gebruiksrechten_delete_audittrail.nieuw, None)

    def test_update_enkelvoudiginformatieobject_audittrail(self):
        informatieobject_data = self._create_enkelvoudiginformatieobject()
        informatieobject_url = informatieobject_data['url']

        # lock for update
        eio = EnkelvoudigInformatieObjectCanonical.objects.get()
        eio.lock = '0f60f6d2d2714c809ed762372f5a363a'
        eio.save()

        content = {
            'identificatie': uuid.uuid4().hex,
            'bronorganisatie': '159351741',
            'creatiedatum': '2018-06-27',
            'titel': 'aangepast',
            'auteur': 'aangepaste auteur',
            'formaat': 'txt',
            'taal': 'eng',
            'bestandsnaam': 'dummy.txt',
            'inhoud': b64encode(b'some file content').decode('utf-8'),
            'link': 'http://een.link',
            'beschrijving': 'test_beschrijving',
            'informatieobjecttype':
            'https://example.com/ztc/api/v1/catalogus/1/informatieobjecttype/1',
            'vertrouwelijkheidaanduiding': 'openbaar',
            'lock': '0f60f6d2d2714c809ed762372f5a363a'
        }

        informatieobject_response = self.client.put(informatieobject_url,
                                                    content).data

        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 2)

        # Verify that the audittrail for the EnkelvoudigInformatieObject update
        # contains the correct information
        informatieobject_update_audittrail = audittrails[1]
        self.assertEqual(informatieobject_update_audittrail.bron, 'DRC')
        self.assertEqual(informatieobject_update_audittrail.actie, 'update')
        self.assertEqual(informatieobject_update_audittrail.resultaat, 200)

        # locked is False upon InformatieObject creation, but the
        # InformatieObject must be locked before updating is possible, so
        # locked will be True in the version before changes as shown
        # in the audittrail
        informatieobject_data['locked'] = True
        self.assertEqual(informatieobject_update_audittrail.oud,
                         informatieobject_data)
        self.assertEqual(informatieobject_update_audittrail.nieuw,
                         informatieobject_response)

    def test_partial_update_enkelvoudiginformatieobject_audittrail(self):
        informatieobject_data = self._create_enkelvoudiginformatieobject()
        informatieobject_url = informatieobject_data['url']

        # lock for update
        eio = EnkelvoudigInformatieObjectCanonical.objects.get()
        eio.lock = '0f60f6d2d2714c809ed762372f5a363a'
        eio.save()

        informatieobject_response = self.client.patch(
            informatieobject_url, {
                'titel': 'changed',
                'lock': '0f60f6d2d2714c809ed762372f5a363a'
            }).data

        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 2)

        # Verify that the audittrail for the EnkelvoudigInformatieObject
        # partial update contains the correct information
        informatieobject_partial_update_audittrail = audittrails[1]
        self.assertEqual(informatieobject_partial_update_audittrail.bron,
                         'DRC')
        self.assertEqual(informatieobject_partial_update_audittrail.actie,
                         'partial_update')
        self.assertEqual(informatieobject_partial_update_audittrail.resultaat,
                         200)

        # locked is False upon InformatieObject creation, but the
        # InformatieObject must be locked before updating is possible, so
        # locked will be True in the version before changes as shown
        # in the audittrail
        informatieobject_data['locked'] = True
        self.assertEqual(informatieobject_partial_update_audittrail.oud,
                         informatieobject_data)
        self.assertEqual(informatieobject_partial_update_audittrail.nieuw,
                         informatieobject_response)

    def test_audittrail_applicatie_information(self):
        object_response = self._create_enkelvoudiginformatieobject()

        audittrail = AuditTrail.objects.filter(
            hoofd_object=object_response['url']).get()

        # Verify that the application id stored in the AuditTrail matches
        # the id of the Application used for the request
        self.assertEqual(audittrail.applicatie_id, str(self.applicatie.uuid))

        # Verify that the application representation stored in the AuditTrail
        # matches the label of the Application used for the request
        self.assertEqual(audittrail.applicatie_weergave, self.applicatie.label)

    def test_audittrail_user_information(self):
        object_response = self._create_enkelvoudiginformatieobject()

        audittrail = AuditTrail.objects.filter(
            hoofd_object=object_response['url']).get()

        # Verify that the user id stored in the AuditTrail matches
        # the user id in the JWT token for the request
        self.assertIn(audittrail.gebruikers_id, self.user_id)

        # Verify that the user representation stored in the AuditTrail matches
        # the user representation in the JWT token for the request
        self.assertEqual(audittrail.gebruikers_weergave,
                         self.user_representation)

    def test_audittrail_toelichting(self):
        toelichting = 'blaaaa'
        object_response = self._create_enkelvoudiginformatieobject(
            HTTP_X_AUDIT_TOELICHTING=toelichting)

        audittrail = AuditTrail.objects.filter(
            hoofd_object=object_response['url']).get()

        # Verify that the toelichting stored in the AuditTrail matches
        # the X-Audit-Toelichting header in the HTTP request
        self.assertEqual(audittrail.toelichting, toelichting)

    def test_read_audittrail(self):
        self._create_enkelvoudiginformatieobject()

        eio = EnkelvoudigInformatieObject.objects.get()
        audittrails = AuditTrail.objects.get()
        audittrails_url = reverse(
            audittrails, kwargs={'enkelvoudiginformatieobject_uuid': eio.uuid})

        response_audittrails = self.client.get(audittrails_url)

        self.assertEqual(response_audittrails.status_code, status.HTTP_200_OK)

    def test_audittrail_resource_weergave(self):
        eio_response = self._create_enkelvoudiginformatieobject()

        eio_uuid = get_uuid_from_path(eio_response['url'])
        eio_unique_representation = EnkelvoudigInformatieObject.objects.get(
            uuid=eio_uuid).unique_representation()

        audittrail = AuditTrail.objects.filter(
            hoofd_object=eio_response['url']).get()

        # Verify that the resource weergave stored in the AuditTrail matches
        # the unique representation as defined in the Zaak model
        self.assertIn(audittrail.resource_weergave, eio_unique_representation)
class OIOCreateExternalURLsTests(JWTAuthMixin, APITestCase):
    heeft_alle_autorisaties = True
    list_url = reverse_lazy(ObjectInformatieObject)

    def test_create_external_zaak(self):
        zaak = "https://externe.catalogus.nl/api/v1/zaken/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        zaaktype = "https://externe.catalogus.nl/api/v1/zaaktypen/b71f72ef-198d-44d8-af64-ae1932df830a"

        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"

        with requests_mock.Mocker(real_http=True) as m:
            m.get(zaak, json=get_zaak_response(zaak, zaaktype))

            response = self.client.post(
                self.list_url,
                {"object": zaak, "informatieobject": eio_url, "objectType": "zaak",},
            )

            self.assertEqual(
                response.status_code, status.HTTP_201_CREATED, response.data
            )

            oio = ObjectInformatieObject.objects.get()

            self.assertEqual(oio.informatieobject, eio.canonical)
            self.assertEqual(oio.object, zaak)

    def test_create_external_besluit(self):
        besluit = "https://externe.catalogus.nl/api/v1/besluiten/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluittype = "https://externe.catalogus.nl/api/v1/besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"

        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"

        with requests_mock.Mocker(real_http=True) as m:
            m.get(besluit, json=get_besluit_response(besluit, besluittype))

            response = self.client.post(
                self.list_url,
                {
                    "object": besluit,
                    "informatieobject": eio_url,
                    "objectType": "besluit",
                },
            )

            self.assertEqual(
                response.status_code, status.HTTP_201_CREATED, response.data
            )

            oio = ObjectInformatieObject.objects.get()

            self.assertEqual(oio.informatieobject, eio.canonical)
            self.assertEqual(oio.object, besluit)

    def test_create_external_zaak_fail_invalid_schema(self):
        zaak = "https://externe.catalogus.nl/api/v1/zaken/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        zaaktype = "https://externe.catalogus.nl/api/v1/zaaktypen/b71f72ef-198d-44d8-af64-ae1932df830a"

        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = reverse(eio)

        with requests_mock.Mocker(real_http=True) as m:
            m.get(
                zaak,
                json={
                    "url": zaak,
                    "uuid": "d781cd1b-f100-4051-9543-153b93299da4",
                    "identificatie": "ZAAK-2019-0000000001",
                    "zaaktype": zaaktype,
                },
            )

            response = self.client.post(
                self.list_url,
                {
                    "object": zaak,
                    "informatieobject": f"http://testserver{eio_url}",
                    "objectType": "zaak",
                },
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "object")
        self.assertEqual(error["code"], "invalid-resource")

    def test_create_external_besluit_fail_invalid_schema(self):
        besluit = "https://externe.catalogus.nl/api/v1/besluiten/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluittype = "https://externe.catalogus.nl/api/v1/besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"

        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = reverse(eio)

        with requests_mock.Mocker(real_http=True) as m:
            m.get(
                besluit,
                json={
                    "url": besluit,
                    "identificatie": "BESLUIT-2019-0000000001",
                    "besluittype": besluittype,
                },
            )

            response = self.client.post(
                self.list_url,
                {
                    "object": besluit,
                    "informatieobject": f"http://testserver{eio_url}",
                    "objectType": "besluit",
                },
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "object")
        self.assertEqual(error["code"], "invalid-resource")

    def test_create_fail_not_unique(self):
        besluit = "https://externe.catalogus.nl/api/v1/besluiten/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluittype = "https://externe.catalogus.nl/api/v1/besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"

        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_url = f"http://testserver{reverse(eio)}"

        ObjectInformatieObject.objects.create(
            informatieobject=eio.canonical, besluit=besluit, object_type="besluit"
        )

        with requests_mock.Mocker(real_http=True) as m:
            m.get(besluit, json=get_besluit_response(besluit, besluittype))

            response = self.client.post(
                self.list_url,
                {
                    "object": besluit,
                    "informatieobject": eio_url,
                    "objectType": "besluit",
                },
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unique")

    def test_read_external_zaak(self):
        zaak = "https://externe.catalogus.nl/api/v1/zaken/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        eio = EnkelvoudigInformatieObjectFactory.create()
        oio = ObjectInformatieObject.objects.create(
            informatieobject=eio.canonical, zaak=zaak, object_type="zaak"
        )
        url = reverse(oio)

        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()

        self.assertEqual(data["object"], zaak)
        self.assertEqual(data["informatieobject"], f"http://testserver{reverse(eio)}")

    def test_read_external_besluit(self):
        besluit = "https://externe.catalogus.nl/api/v1/besluiten/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        eio = EnkelvoudigInformatieObjectFactory.create()
        oio = ObjectInformatieObject.objects.create(
            informatieobject=eio.canonical, besluit=besluit, object_type="besluit"
        )
        url = reverse(oio)

        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()

        self.assertEqual(data["object"], besluit)
        self.assertEqual(data["informatieobject"], f"http://testserver{reverse(eio)}")

    def test_list_filter_by_external_zaak(self):
        eio = EnkelvoudigInformatieObjectFactory.create()
        zaak1 = "https://externe.catalogus.nl/api/v1/zaken/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        zaak2 = "https://externe.catalogus.nl/api/v1/zaken/b923543f-97aa-4a55-8c20-889b5906cf75"
        ObjectInformatieObject.objects.create(
            informatieobject=eio.canonical, zaak=zaak1, object_type="zaak"
        )
        ObjectInformatieObject.objects.create(
            informatieobject=eio.canonical, zaak=zaak2, object_type="zaak"
        )

        url = reverse(ObjectInformatieObject)

        response = self.client.get(url, {"object": zaak2})

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["object"], zaak2)

    def test_list_filter_by_external_besluit(self):
        eio = EnkelvoudigInformatieObjectFactory.create()
        besluit1 = "https://externe.catalogus.nl/api/v1/besluiten/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluit2 = "https://externe.catalogus.nl/api/v1/besluiten/b923543f-97aa-4a55-8c20-889b5906cf75"
        ObjectInformatieObject.objects.create(
            informatieobject=eio.canonical, besluit=besluit1, object_type="besluit"
        )
        ObjectInformatieObject.objects.create(
            informatieobject=eio.canonical, besluit=besluit2, object_type="besluit"
        )
        url = reverse(ObjectInformatieObject)

        response = self.client.get(url, {"object": besluit2})

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["object"], besluit2)

    def test_destroy_external_zaak(self):
        zaak = "https://externe.catalogus.nl/api/v1/zaken/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        zaaktype = "https://externe.catalogus.nl/api/v1/zaaktypen/b71f72ef-198d-44d8-af64-ae1932df830a"
        eio = EnkelvoudigInformatieObjectFactory.create()
        oio = ObjectInformatieObject.objects.create(
            informatieobject=eio.canonical, zaak=zaak, object_type="zaak"
        )
        url = reverse(oio)

        with requests_mock.Mocker(real_http=True) as m:
            m.get(zaak, json=get_zaak_response(zaak, zaaktype))

            response = self.client.delete(url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(ObjectInformatieObject.objects.count(), 0)

    def test_destroy_external_besluit(self):
        besluit = "https://externe.catalogus.nl/api/v1/besluiten/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        besluittype = "https://externe.catalogus.nl/api/v1/besluittypen/b71f72ef-198d-44d8-af64-ae1932df830a"
        eio = EnkelvoudigInformatieObjectFactory.create()
        oio = ObjectInformatieObject.objects.create(
            informatieobject=eio.canonical, besluit=besluit, object_type="besluit"
        )
        url = reverse(oio)

        with requests_mock.Mocker(real_http=True) as m:
            m.get(besluit, json=get_besluit_response(besluit, besluittype))

            response = self.client.delete(url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(ObjectInformatieObject.objects.count(), 0)
Ejemplo n.º 23
0
class ResultaatTypeValidationTests(APITestCase):
    list_url = reverse_lazy(ResultaatType)

    @patch('vng_api_common.oas.fetcher.fetch', return_value={})
    @patch('vng_api_common.validators.obj_has_shape', return_value=False)
    def test_validate_wrong_resultaattypeomschrijving(self, mock_shape, mock_fetch):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = reverse('zaaktype-detail', kwargs={
            'uuid': zaaktype.uuid,
        })
        resultaattypeomschrijving_url = 'http://example.com/omschrijving/1'
        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'omschrijving': 'illum',
            'resultaattypeomschrijving': resultaattypeomschrijving_url,
            'selectielijstklasse': 'https://garcia.org/',
            'archiefnominatie': 'blijvend_bewaren',
            'archiefactietermijn': 'P10Y',
            'brondatumArchiefprocedure': {
                'afleidingswijze': BrondatumArchiefprocedureAfleidingswijze.afgehandeld,
                'einddatumBekend': False,
                'procestermijn': 'P10Y',
                'datumkenmerk': '',
                'objecttype': '',
                'registratie': '',
            }
        }

        with requests_mock.Mocker() as m:
            m.register_uri('GET', resultaattypeomschrijving_url, json={
                'omschrijving': 'test'
            })
            response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        error = get_validation_errors(response, 'resultaattypeomschrijving')
        self.assertEqual(error['code'], 'invalid-resource')

    @override_settings(LINK_FETCHER='vng_api_common.mocks.link_fetcher_200')
    def test_selectielijstklasse_invalid_resource(self):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = reverse('zaaktype-detail', kwargs={
            'uuid': zaaktype.uuid,
        })

        responses = {
            'http://example.com/resultaten/1234': {
                'some': 'incorrect property'
            }
        }

        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'omschrijving': 'illum',
            'resultaattypeomschrijving': 'https://garcia.org/',
            'selectielijstklasse': 'http://example.com/resultaten/1234',
            'archiefnominatie': 'blijvend_bewaren',
            'archiefactietermijn': 'P10Y',
            'brondatumArchiefprocedure': {
                'afleidingswijze': BrondatumArchiefprocedureAfleidingswijze.afgehandeld,
                'einddatumBekend': False,
                'procestermijn': 'P10Y',
                'datumkenmerk': '',
                'objecttype': '',
                'registratie': '',
            }
        }

        with mock_client(responses):
            response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, 'selectielijstklasse')
        self.assertEqual(error['code'], 'invalid-resource')

    @override_settings(LINK_FETCHER='vng_api_common.mocks.link_fetcher_200')
    @patch('vng_api_common.validators.obj_has_shape', return_value=True)
    def test_selectielijstklasse_procestype_no_match_with_zaaktype_procestype(self, *mocks):
        zaaktype = ZaakTypeFactory.create(
            selectielijst_procestype=PROCESTYPE_URL,
            concept=False
        )
        zaaktype_url = reverse('zaaktype-detail', kwargs={
            'uuid': zaaktype.uuid,
        })

        responses = {
            SELECTIELIJSTKLASSE_URL: {
                'url': SELECTIELIJSTKLASSE_URL,
                'procesType': 'http://somedifferentprocestypeurl.com/',
                'procestermijn': Procestermijn.nihil,
            },
        }

        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'omschrijving': 'illum',
            'resultaattypeomschrijving': 'https://garcia.org/',
            'selectielijstklasse': SELECTIELIJSTKLASSE_URL,
            'archiefnominatie': 'blijvend_bewaren',
            'archiefactietermijn': 'P10Y',
            'brondatumArchiefprocedure': {
                'afleidingswijze': BrondatumArchiefprocedureAfleidingswijze.afgehandeld,
                'einddatumBekend': False,
                'procestermijn': 'P10Y',
                'datumkenmerk': '',
                'objecttype': '',
                'registratie': '',
            }
        }

        with mock_client(responses):
            response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, 'nonFieldErrors')
        self.assertEqual(error['code'], 'procestype-mismatch')

    @override_settings(LINK_FETCHER='vng_api_common.mocks.link_fetcher_200')
    @patch('vng_api_common.validators.obj_has_shape', return_value=True)
    def test_procestermijn_nihil_and_afleidingswijze_niet_afgehandeld_fails(self, *mocks):
        zaaktype = ZaakTypeFactory.create(
            selectielijst_procestype=PROCESTYPE_URL,
            concept=False
        )
        zaaktype_url = reverse('zaaktype-detail', kwargs={
            'uuid': zaaktype.uuid,
        })

        responses = {
            SELECTIELIJSTKLASSE_URL: {
                'url': SELECTIELIJSTKLASSE_URL,
                'procesType': PROCESTYPE_URL,
                'procestermijn': Procestermijn.nihil,
            },
        }

        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'omschrijving': 'illum',
            'resultaattypeomschrijving': 'https://garcia.org/',
            'selectielijstklasse': SELECTIELIJSTKLASSE_URL,
            'archiefnominatie': 'blijvend_bewaren',
            'archiefactietermijn': 'P10Y',
            'brondatumArchiefprocedure': {
                'afleidingswijze': BrondatumArchiefprocedureAfleidingswijze.ander_datumkenmerk,
                'einddatumBekend': False,
                'procestermijn': 'P10Y',
                'datumkenmerk': '',
                'objecttype': '',
                'registratie': '',
            }
        }

        with mock_client(responses):
            response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, 'nonFieldErrors')
        self.assertEqual(error['code'], 'invalid-afleidingswijze-for-procestermijn')

    @override_settings(LINK_FETCHER='vng_api_common.mocks.link_fetcher_200')
    @patch('vng_api_common.validators.obj_has_shape', return_value=True)
    def test_procestermijn_ingeschatte_bestaansduur_procesobject_and_afleidingswijze_niet_termijn_fails(self, *mocks):
        zaaktype = ZaakTypeFactory.create(
            selectielijst_procestype=PROCESTYPE_URL,
            concept=False
        )
        zaaktype_url = reverse('zaaktype-detail', kwargs={
            'uuid': zaaktype.uuid,
        })

        responses = {
            SELECTIELIJSTKLASSE_URL: {
                'url': SELECTIELIJSTKLASSE_URL,
                'procesType': PROCESTYPE_URL,
                'procestermijn': Procestermijn.ingeschatte_bestaansduur_procesobject,
            },
        }

        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'omschrijving': 'illum',
            'resultaattypeomschrijving': 'https://garcia.org/',
            'selectielijstklasse': SELECTIELIJSTKLASSE_URL,
            'archiefnominatie': 'blijvend_bewaren',
            'archiefactietermijn': 'P10Y',
            'brondatumArchiefprocedure': {
                'afleidingswijze': BrondatumArchiefprocedureAfleidingswijze.afgehandeld,
                'einddatumBekend': False,
                'procestermijn': 'P10Y',
                'datumkenmerk': '',
                'objecttype': '',
                'registratie': '',
            }
        }

        with mock_client(responses):
            response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, 'nonFieldErrors')
        self.assertEqual(error['code'], 'invalid-afleidingswijze-for-procestermijn')
class ExternalDocumentsAPITransactionTests(JWTAuthMixin, APITransactionTestCase):
    heeft_alle_autorisaties = True
    list_url = reverse_lazy(BesluitInformatieObject)
    base = "https://external.documenten.nl/api/v1/"

    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        Service.objects.create(
            api_type=APITypes.drc,
            api_root=cls.base,
            label="external documents",
            auth_type=AuthTypes.no_auth,
        )

    @tag("gh-819")
    def test_bio_visibility_outside_transaction(self):
        self.setUpTestData()
        document = f"{self.base}enkelvoudiginformatieobjecten/{uuid.uuid4()}"

        besluit = BesluitFactory.create(besluittype__concept=False)
        besluit_url = f"http://openzaak.nl{reverse(besluit)}"
        informatieobjecttype = InformatieObjectTypeFactory.create(
            catalogus=besluit.besluittype.catalogus, concept=False
        )
        informatieobjecttype_url = f"http://openzaak.nl{reverse(informatieobjecttype)}"
        informatieobjecttype.besluittypen.add(besluit.besluittype)
        eio_response = get_eio_response(
            document, informatieobjecttype=informatieobjecttype_url
        )

        def worker(besluit_id: int):
            """
            Worker to run in a thread.

            When this worker runs, there should be one ZIO visible in the database - it
            must have been committed so that the remote DRC can view this record too.
            """
            bios = BesluitInformatieObject.objects.filter(besluit__id=besluit_id)
            self.assertEqual(bios.count(), 1)
            close_old_connections()

        def mock_create_remote_oio(*args, **kwargs):
            with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
                future = executor.submit(worker, besluit.id)
                future.result()  # raises any exceptions, such as assertionerrors
            return {"url": f"{self.base}objectinformatieobjecten/{uuid.uuid4()}"}

        with patch(
            "openzaak.components.besluiten.api.serializers.create_remote_oio",
            side_effect=mock_create_remote_oio,
        ):
            with requests_mock.Mocker() as m:
                mock_service_oas_get(
                    m, APITypes.drc, self.base, oas_url=settings.DRC_API_SPEC
                )
                m.get(document, json=eio_response)

                response = self.client.post(
                    self.list_url,
                    {"besluit": besluit_url, "informatieobject": document},
                )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data)
class ObjectInformatieObjectTests(JWTAuthMixin, APICMISTestCase, OioMixin):
    heeft_alle_autorisaties = True
    list_url = reverse_lazy("objectinformatieobject-list")

    def test_retrieve_multiple_oios(self):
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()

        # This creates 2 OIOs
        eio_1 = EnkelvoudigInformatieObjectFactory.create()
        eio_1_path = reverse(eio_1)
        eio_1_url = f"http://testserver{eio_1_path}"
        # relate the two
        self.adapter.get(eio_1_url, json=serialise_eio(eio_1, eio_1_url))
        ZaakInformatieObjectFactory.create(zaak=zaak,
                                           informatieobject=eio_1_url)

        eio_2 = EnkelvoudigInformatieObjectFactory.create()
        eio_2_path = reverse(eio_2)
        eio_2_url = f"http://testserver{eio_2_path}"
        # relate the two
        self.adapter.get(eio_2_url, json=serialise_eio(eio_2, eio_2_url))
        ZaakInformatieObjectFactory.create(zaak=zaak,
                                           informatieobject=eio_2_url)

        # Retrieve oios from API
        response = self.client.get(self.list_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(len(response.data), 2)
        self.assertTrue(eio_1_url == response.data[0]["informatieobject"]
                        or eio_1_url == response.data[1]["informatieobject"])
        self.assertTrue(eio_2_url == response.data[0]["informatieobject"]
                        or eio_2_url == response.data[1]["informatieobject"])

    def test_create_with_objecttype_zaak(self):
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"
        # relate the two
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        ZaakInformatieObjectFactory.create(zaak=zaak, informatieobject=eio_url)

        # get OIO created via signals
        ObjectInformatieObject.objects.get()

        zaak_url = reverse(zaak)

        response = self.client.post(
            self.list_url,
            {
                "object": f"http://testserver{zaak_url}",
                "informatieobject": eio_url,
                "objectType": "zaak",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unique")

    def test_create_with_objecttype_besluit(self):
        self.create_zaak_besluit_services()
        besluit = self.create_besluit()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        BesluitInformatieObjectFactory.create(besluit=besluit,
                                              informatieobject=eio_url)

        # get OIO created via signals
        ObjectInformatieObject.objects.get()

        besluit_url = reverse(besluit)

        response = self.client.post(
            self.list_url,
            {
                "object": f"http://testserver{besluit_url}",
                "informatieobject": f"http://testserver{eio_path}",
                "objectType": "besluit",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unique")

    def test_create_with_objecttype_other_fail(self):
        self.create_zaak_besluit_services()
        besluit = self.create_besluit()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"
        # relate the two
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        BesluitInformatieObjectFactory.create(besluit=besluit,
                                              informatieobject=eio_url)

        besluit_url = reverse(besluit)

        response = self.client.post(
            self.list_url,
            {
                "object": f"http://testserver{besluit_url}",
                "informatieobject": eio_url,
                "objectType": "other",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)
        error = get_validation_errors(response, "objectType")
        self.assertEqual(error["code"], "invalid_choice")

    def test_read_with_objecttype_zaak(self):
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"
        # relate the two
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        ZaakInformatieObjectFactory.create(zaak=zaak, informatieobject=eio_url)

        # get OIO created via signals
        oio = ObjectInformatieObject.objects.get()

        oio_url = reverse("objectinformatieobject-detail",
                          kwargs={"uuid": oio.uuid})
        zaak_url = reverse(zaak)

        response = self.client.get(oio_url)

        expeceted_response_data = {
            "url": f"http://testserver{oio_url}",
            "object": make_absolute_uri(zaak_url),
            "informatieobject": eio_url,
            "object_type": "zaak",
        }

        self.assertEqual(response.status_code, status.HTTP_200_OK,
                         response.data)
        self.assertEqual(response.data, expeceted_response_data)

    def test_read_with_objecttype_besluit(self):
        self.create_zaak_besluit_services()
        besluit = self.create_besluit()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"
        # relate the two
        self.adapter.get(eio_url, json=serialise_eio(eio, eio_url))
        BesluitInformatieObjectFactory.create(besluit=besluit,
                                              informatieobject=eio_url)

        # get OIO created via signals
        oio = ObjectInformatieObject.objects.get()

        oio_url = reverse("objectinformatieobject-detail",
                          kwargs={"uuid": oio.uuid})
        besluit_url = reverse(besluit)

        response = self.client.get(oio_url)

        expeceted_response_data = {
            "url": f"http://testserver{oio_url}",
            "object": make_absolute_uri(besluit_url),
            "informatieobject": eio_url,
            "object_type": "besluit",
        }

        self.assertEqual(response.status_code, status.HTTP_200_OK,
                         response.data)
        self.assertEqual(response.data, expeceted_response_data)

    def test_post_object_without_created_relations(self):
        """
        Test the (informatieobject, object) unique together validation.

        This is expected to fail, since there is no actual creation in database.
        It will however become relevant again when we're handling remote
        references.
        """
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        eio = EnkelvoudigInformatieObjectFactory.create()
        zaak_url = reverse(zaak)
        eio_url = reverse(eio)

        content = {
            "informatieobject": f"http://testserver{eio_url}",
            "object": f"http://testserver{zaak_url}",
            "objectType": ObjectTypes.zaak,
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST,
                         response.data)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "inconsistent-relation")

    def test_filter_eio(self):
        eio_1 = EnkelvoudigInformatieObjectFactory.create()
        eio_2 = EnkelvoudigInformatieObjectFactory.create()
        eio_detail_url = f"http://openzaak.nl{reverse(eio_1)}"
        self.adapter.register_uri("GET",
                                  eio_detail_url,
                                  json=serialise_eio(eio_1, eio_detail_url))
        self.create_zaak_besluit_services()
        zaak = self.create_zaak()
        besluit = self.create_besluit()

        BesluitInformatieObjectFactory.create(informatieobject=eio_detail_url,
                                              besluit=besluit)
        ZaakInformatieObjectFactory.create(
            informatieobject=f"http://openzaak.nl{reverse(eio_2)}",
            zaak=zaak)  # may not show up

        response = self.client.get(
            self.list_url,
            {"informatieobject": eio_detail_url},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["informatieobject"], eio_detail_url)

    def test_filter_zaak(self):
        eio_1 = EnkelvoudigInformatieObjectFactory.create()
        eio_detail_url = f"http://openzaak.nl{reverse(eio_1)}"
        self.adapter.register_uri("GET",
                                  eio_detail_url,
                                  json=serialise_eio(eio_1, eio_detail_url))

        self.create_zaak_besluit_services()
        zaak1 = self.create_zaak()
        zio = ZaakInformatieObjectFactory.create(
            informatieobject=eio_detail_url, zaak=zaak1)
        zaak2 = self.create_zaak()
        ZaakInformatieObjectFactory.create(informatieobject=eio_detail_url,
                                           zaak=zaak2)  # may not show up

        zaak_url = reverse(zio.zaak)

        response = self.client.get(
            self.list_url,
            {"object": f"http://openzaak.nl{zaak_url}"},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["informatieobject"], eio_detail_url)

    def test_filter_besluit(self):
        eio_1 = EnkelvoudigInformatieObjectFactory.create()
        eio_detail_url = f"http://openzaak.nl{reverse(eio_1)}"
        self.adapter.register_uri("GET",
                                  eio_detail_url,
                                  json=serialise_eio(eio_1, eio_detail_url))

        self.create_zaak_besluit_services()
        besluit1 = self.create_besluit()
        bio = BesluitInformatieObjectFactory.create(
            informatieobject=eio_detail_url, besluit=besluit1)
        besluit2 = self.create_besluit()
        BesluitInformatieObjectFactory.create(
            informatieobject=eio_detail_url,
            besluit=besluit2)  # may not show up

        besluit_url = reverse(bio.besluit)

        response = self.client.get(
            self.list_url,
            {"object": f"http://openzaak.nl{besluit_url}"},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["informatieobject"], eio_detail_url)

    def test_validate_unknown_query_params(self):
        url = reverse(ObjectInformatieObject)

        response = self.client.get(url, {"someparam": "somevalue"})

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unknown-parameters")
Ejemplo n.º 26
0
class InformatieobjectCreateExternalURLsTests(JWTAuthMixin, APITestCase):
    heeft_alle_autorisaties = True
    list_url = reverse_lazy(EnkelvoudigInformatieObject)

    def test_create_external_informatieobjecttype(self):
        catalogus = "https://externe.catalogus.nl/api/v1/catalogussen/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        informatieobjecttype = (
            "https://externe.catalogus.nl/api/v1/informatieobjecttypen/"
            "b71f72ef-198d-44d8-af64-ae1932df830a")

        with requests_mock.Mocker(real_http=True) as m:
            m.register_uri(
                "GET",
                informatieobjecttype,
                json=get_informatieobjecttype_response(catalogus,
                                                       informatieobjecttype),
            )
            m.register_uri(
                "GET",
                catalogus,
                json=get_catalogus_response(catalogus, informatieobjecttype),
            )

            response = self.client.post(
                self.list_url,
                {
                    "identificatie": "12345",
                    "bronorganisatie": "159351741",
                    "creatiedatum": "2018-06-27",
                    "titel": "detailed summary",
                    "auteur": "test_auteur",
                    "formaat": "txt",
                    "taal": "eng",
                    "bestandsnaam": "dummy.txt",
                    "inhoud": b64encode(b"some file content").decode("utf-8"),
                    "link": "http://een.link",
                    "beschrijving": "test_beschrijving",
                    "informatieobjecttype": informatieobjecttype,
                    "vertrouwelijkheidaanduiding": "openbaar",
                },
            )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED,
                         response.data)

    def test_create_external_informatieobjecttype_fail_bad_url(self):
        response = self.client.post(
            self.list_url,
            {
                "identificatie": "12345",
                "bronorganisatie": "159351741",
                "creatiedatum": "2018-06-27",
                "titel": "detailed summary",
                "auteur": "test_auteur",
                "formaat": "txt",
                "taal": "eng",
                "bestandsnaam": "dummy.txt",
                "inhoud": b64encode(b"some file content").decode("utf-8"),
                "link": "http://een.link",
                "beschrijving": "test_beschrijving",
                "informatieobjecttype": "abcd",
                "vertrouwelijkheidaanduiding": "openbaar",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "informatieobjecttype")
        self.assertEqual(error["code"], "bad-url")

    @override_settings(ALLOWED_HOSTS=["testserver"])
    def test_create_external_informatieobjecttype_fail_not_json_url(self):
        response = self.client.post(
            self.list_url,
            {
                "identificatie": "12345",
                "bronorganisatie": "159351741",
                "creatiedatum": "2018-06-27",
                "titel": "detailed summary",
                "auteur": "test_auteur",
                "formaat": "txt",
                "taal": "eng",
                "bestandsnaam": "dummy.txt",
                "inhoud": b64encode(b"some file content").decode("utf-8"),
                "link": "http://een.link",
                "beschrijving": "test_beschrijving",
                "informatieobjecttype": "http://example.com",
                "vertrouwelijkheidaanduiding": "openbaar",
            },
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "informatieobjecttype")
        self.assertEqual(error["code"], "invalid-resource")

    def test_create_external_informatieobjecttype_fail_invalid_schema(self):
        catalogus = "https://externe.catalogus.nl/api/v1/catalogussen/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        informatieobjecttype = (
            "https://externe.catalogus.nl/api/v1/informatieobjecttypen/"
            "b71f72ef-198d-44d8-af64-ae1932df830a")

        with requests_mock.Mocker(real_http=True) as m:
            m.register_uri(
                "GET",
                informatieobjecttype,
                json={
                    "url": informatieobjecttype,
                    "catalogus": catalogus,
                },
            )
            m.register_uri(
                "GET",
                catalogus,
                json=get_catalogus_response(catalogus, informatieobjecttype),
            )

            response = self.client.post(
                self.list_url,
                {
                    "identificatie": "12345",
                    "bronorganisatie": "159351741",
                    "creatiedatum": "2018-06-27",
                    "titel": "detailed summary",
                    "auteur": "test_auteur",
                    "formaat": "txt",
                    "taal": "eng",
                    "bestandsnaam": "dummy.txt",
                    "inhoud": b64encode(b"some file content").decode("utf-8"),
                    "link": "http://een.link",
                    "beschrijving": "test_beschrijving",
                    "informatieobjecttype": informatieobjecttype,
                    "vertrouwelijkheidaanduiding": "openbaar",
                },
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "informatieobjecttype")
        self.assertEqual(error["code"], "invalid-resource")

    def test_create_external_informatieobjecttype_fail_non_pulish(self):
        catalogus = "https://externe.catalogus.nl/api/v1/catalogussen/1c8e36be-338c-4c07-ac5e-1adf55bec04a"
        informatieobjecttype = (
            "https://externe.catalogus.nl/api/v1/informatieobjecttypen/"
            "b71f72ef-198d-44d8-af64-ae1932df830a")
        informatieobjecttype_data = get_informatieobjecttype_response(
            catalogus, informatieobjecttype)
        informatieobjecttype_data["concept"] = True

        with requests_mock.Mocker(real_http=True) as m:
            m.register_uri(
                "GET",
                informatieobjecttype,
                json=informatieobjecttype_data,
            )
            m.register_uri(
                "GET",
                catalogus,
                json=get_catalogus_response(catalogus, informatieobjecttype),
            )

            response = self.client.post(
                self.list_url,
                {
                    "identificatie": "12345",
                    "bronorganisatie": "159351741",
                    "creatiedatum": "2018-06-27",
                    "titel": "detailed summary",
                    "auteur": "test_auteur",
                    "formaat": "txt",
                    "taal": "eng",
                    "bestandsnaam": "dummy.txt",
                    "inhoud": b64encode(b"some file content").decode("utf-8"),
                    "link": "http://een.link",
                    "beschrijving": "test_beschrijving",
                    "informatieobjecttype": informatieobjecttype,
                    "vertrouwelijkheidaanduiding": "openbaar",
                },
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "informatieobjecttype")
        self.assertEqual(error["code"], "not-published")
Ejemplo n.º 27
0
class AuditTrailTests(JWTAuthMixin, APITestCase):

    informatieobject_list_url = reverse_lazy(EnkelvoudigInformatieObject)
    gebruiksrechten_list_url = reverse_lazy(Gebruiksrechten)

    heeft_alle_autorisaties = True

    def _create_enkelvoudiginformatieobject(self, **HEADERS):
        informatieobjecttype = InformatieObjectTypeFactory.create()
        informatieobjecttype_url = reverse(informatieobjecttype)
        content = {
            "identificatie": uuid.uuid4().hex,
            "bronorganisatie": "159351741",
            "creatiedatum": "2018-06-27",
            "titel": "detailed summary",
            "auteur": "test_auteur",
            "formaat": "txt",
            "taal": "eng",
            "bestandsnaam": "dummy.txt",
            "inhoud": b64encode(b"some file content").decode("utf-8"),
            "link": "http://een.link",
            "beschrijving": "test_beschrijving",
            "informatieobjecttype": informatieobjecttype_url,
            "vertrouwelijkheidaanduiding": "openbaar",
        }

        response = self.client.post(self.informatieobject_list_url, content,
                                    **HEADERS)

        return response.data

    def test_create_enkelvoudiginformatieobject_audittrail(self):
        informatieobject_data = self._create_enkelvoudiginformatieobject()
        informatieobject_url = informatieobject_data["url"]

        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 1)

        # Verify that the audittrail for the EnkelvoudigInformatieObject creation contains the correct
        # information
        informatieobject_create_audittrail = audittrails.get()
        self.assertEqual(informatieobject_create_audittrail.bron, "DRC")
        self.assertEqual(informatieobject_create_audittrail.actie, "create")
        self.assertEqual(informatieobject_create_audittrail.resultaat, 201)
        self.assertEqual(informatieobject_create_audittrail.oud, None)
        self.assertEqual(informatieobject_create_audittrail.nieuw,
                         informatieobject_data)

    @skip("ObjectInformatieObject is not implemented yet")
    def test_create_objectinformatieobject_audittrail(self):
        informatieobject = EnkelvoudigInformatieObjectFactory.create()

        content = {
            "informatieobject":
            reverse(
                "enkelvoudiginformatieobject-detail",
                kwargs={"uuid": informatieobject.uuid},
            ),
            "object":
            ZAAK,
            "objectType":
            ObjectTypes.zaak,
        }

        # Send to the API
        objectinformatieobject_response = self.client.post(
            self.objectinformatieobject_list_url, content).data

        informatieobject_url = objectinformatieobject_response[
            "informatieobject"]
        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 1)

        # Verify that the audittrail for the ObjectInformatieObject creation
        # contains the correct information
        objectinformatieobject_create_audittrail = audittrails.get()
        self.assertEqual(objectinformatieobject_create_audittrail.bron, "DRC")
        self.assertEqual(objectinformatieobject_create_audittrail.actie,
                         "create")
        self.assertEqual(objectinformatieobject_create_audittrail.resultaat,
                         201)
        self.assertEqual(objectinformatieobject_create_audittrail.oud, None)
        self.assertEqual(
            objectinformatieobject_create_audittrail.nieuw,
            objectinformatieobject_response,
        )

    def test_create_and_delete_gebruiksrechten_audittrail(self):
        informatieobject = EnkelvoudigInformatieObjectFactory.create()

        content = {
            "informatieobject":
            reverse(
                "enkelvoudiginformatieobject-detail",
                kwargs={"uuid": informatieobject.uuid},
            ),
            "startdatum":
            datetime.now(),
            "omschrijvingVoorwaarden":
            "test",
        }

        gebruiksrechten_response = self.client.post(
            self.gebruiksrechten_list_url, content).data

        informatieobject_url = gebruiksrechten_response["informatieobject"]
        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 1)

        # Verify that the audittrail for the Gebruiksrechten creation
        # contains the correct information
        gebruiksrechten_create_audittrail = audittrails.get()
        self.assertEqual(gebruiksrechten_create_audittrail.bron, "DRC")
        self.assertEqual(gebruiksrechten_create_audittrail.actie, "create")
        self.assertEqual(gebruiksrechten_create_audittrail.resultaat, 201)
        self.assertEqual(gebruiksrechten_create_audittrail.oud, None)
        self.assertEqual(gebruiksrechten_create_audittrail.nieuw,
                         gebruiksrechten_response)

        delete_response = self.client.delete(gebruiksrechten_response["url"])

        self.assertEqual(delete_response.status_code,
                         status.HTTP_204_NO_CONTENT)
        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 2)

        # Verify that the audittrail for the Gebruiksrechten deletion
        # contains the correct information
        gebruiksrechten_delete_audittrail = audittrails[1]
        self.assertEqual(gebruiksrechten_delete_audittrail.bron, "DRC")
        self.assertEqual(gebruiksrechten_delete_audittrail.actie, "destroy")
        self.assertEqual(gebruiksrechten_delete_audittrail.resultaat, 204)
        self.assertEqual(gebruiksrechten_delete_audittrail.oud,
                         gebruiksrechten_response)
        self.assertEqual(gebruiksrechten_delete_audittrail.nieuw, None)

    def test_update_enkelvoudiginformatieobject_audittrail(self):
        informatieobject_data = self._create_enkelvoudiginformatieobject()
        informatieobject_url = informatieobject_data["url"]
        informatieobjecttype_url = informatieobject_data[
            "informatieobjecttype"]

        # lock for update
        eio = EnkelvoudigInformatieObjectCanonical.objects.get()
        eio.lock = "0f60f6d2d2714c809ed762372f5a363a"
        eio.save()

        content = {
            "identificatie": uuid.uuid4().hex,
            "bronorganisatie": "159351741",
            "creatiedatum": "2018-06-27",
            "titel": "aangepast",
            "auteur": "aangepaste auteur",
            "formaat": "txt",
            "taal": "eng",
            "bestandsnaam": "dummy.txt",
            "inhoud": b64encode(b"some file content").decode("utf-8"),
            "link": "http://een.link",
            "beschrijving": "test_beschrijving",
            "informatieobjecttype": informatieobjecttype_url,
            "vertrouwelijkheidaanduiding": "openbaar",
            "lock": "0f60f6d2d2714c809ed762372f5a363a",
        }

        informatieobject_response = self.client.put(informatieobject_url,
                                                    content).data

        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 2)

        # Verify that the audittrail for the EnkelvoudigInformatieObject update
        # contains the correct information
        informatieobject_update_audittrail = audittrails[1]
        self.assertEqual(informatieobject_update_audittrail.bron, "DRC")
        self.assertEqual(informatieobject_update_audittrail.actie, "update")
        self.assertEqual(informatieobject_update_audittrail.resultaat, 200)

        # locked is False upon InformatieObject creation, but the
        # InformatieObject must be locked before updating is possible, so
        # locked will be True in the version before changes as shown
        # in the audittrail
        informatieobject_data["locked"] = True
        self.assertEqual(informatieobject_update_audittrail.oud,
                         informatieobject_data)
        self.assertEqual(informatieobject_update_audittrail.nieuw,
                         informatieobject_response)

    def test_partial_update_enkelvoudiginformatieobject_audittrail(self):
        informatieobject_data = self._create_enkelvoudiginformatieobject()
        informatieobject_url = informatieobject_data["url"]

        # lock for update
        eio = EnkelvoudigInformatieObjectCanonical.objects.get()
        eio.lock = "0f60f6d2d2714c809ed762372f5a363a"
        eio.save()

        informatieobject_response = self.client.patch(
            informatieobject_url,
            {
                "titel": "changed",
                "lock": "0f60f6d2d2714c809ed762372f5a363a"
            },
        ).data

        audittrails = AuditTrail.objects.filter(
            hoofd_object=informatieobject_url)
        self.assertEqual(audittrails.count(), 2)

        # Verify that the audittrail for the EnkelvoudigInformatieObject
        # partial update contains the correct information
        informatieobject_partial_update_audittrail = audittrails[1]
        self.assertEqual(informatieobject_partial_update_audittrail.bron,
                         "DRC")
        self.assertEqual(informatieobject_partial_update_audittrail.actie,
                         "partial_update")
        self.assertEqual(informatieobject_partial_update_audittrail.resultaat,
                         200)

        # locked is False upon InformatieObject creation, but the
        # InformatieObject must be locked before updating is possible, so
        # locked will be True in the version before changes as shown
        # in the audittrail
        informatieobject_data["locked"] = True
        self.assertEqual(informatieobject_partial_update_audittrail.oud,
                         informatieobject_data)
        self.assertEqual(informatieobject_partial_update_audittrail.nieuw,
                         informatieobject_response)

    def test_audittrail_applicatie_information(self):
        object_response = self._create_enkelvoudiginformatieobject()

        audittrail = AuditTrail.objects.filter(
            hoofd_object=object_response["url"]).get()

        # Verify that the application id stored in the AuditTrail matches
        # the id of the Application used for the request
        self.assertEqual(audittrail.applicatie_id, str(self.applicatie.uuid))

        # Verify that the application representation stored in the AuditTrail
        # matches the label of the Application used for the request
        self.assertEqual(audittrail.applicatie_weergave, self.applicatie.label)

    def test_audittrail_user_information(self):
        object_response = self._create_enkelvoudiginformatieobject()

        audittrail = AuditTrail.objects.filter(
            hoofd_object=object_response["url"]).get()

        # Verify that the user id stored in the AuditTrail matches
        # the user id in the JWT token for the request
        self.assertIn(audittrail.gebruikers_id, self.user_id)

        # Verify that the user representation stored in the AuditTrail matches
        # the user representation in the JWT token for the request
        self.assertEqual(audittrail.gebruikers_weergave,
                         self.user_representation)

    def test_audittrail_toelichting(self):
        toelichting = "blaaaa"
        object_response = self._create_enkelvoudiginformatieobject(
            HTTP_X_AUDIT_TOELICHTING=toelichting)

        audittrail = AuditTrail.objects.filter(
            hoofd_object=object_response["url"]).get()

        # Verify that the toelichting stored in the AuditTrail matches
        # the X-Audit-Toelichting header in the HTTP request
        self.assertEqual(audittrail.toelichting, toelichting)

    def test_read_audittrail(self):
        self._create_enkelvoudiginformatieobject()

        eio = EnkelvoudigInformatieObject.objects.get()
        audittrails = AuditTrail.objects.get()
        audittrails_url = reverse(
            audittrails, kwargs={"enkelvoudiginformatieobject_uuid": eio.uuid})

        response_audittrails = self.client.get(audittrails_url)

        self.assertEqual(response_audittrails.status_code, status.HTTP_200_OK)

    def test_audittrail_resource_weergave(self):
        eio_response = self._create_enkelvoudiginformatieobject()

        eio_uuid = get_uuid_from_path(eio_response["url"])
        eio_unique_representation = EnkelvoudigInformatieObject.objects.get(
            uuid=eio_uuid).unique_representation()

        audittrail = AuditTrail.objects.filter(
            hoofd_object=eio_response["url"]).get()

        # Verify that the resource weergave stored in the AuditTrail matches
        # the unique representation as defined in the Zaak model
        self.assertIn(audittrail.resource_weergave, eio_unique_representation)
Ejemplo n.º 28
0
class ZaakInformatieobjectTypeAPITests(APITestCase):
    maxDiff = None

    list_url = reverse_lazy(ZaakInformatieobjectType)

    def test_get_list_default_definitief(self):
        ziot1 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=True)
        ziot2 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=True)
        ziot3 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=False)
        ziot4 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=False)
        ziot4_url = reverse(ziot4)

        response = self.client.get(self.list_url)
        self.assertEqual(response.status_code, 200)

        data = response.json()['results']

        self.assertEqual(len(data), 1)
        self.assertEqual(data[0]['url'], f'http://testserver{ziot4_url}')

    def test_get_detail(self):
        ztiot = ZaakInformatieobjectTypeFactory.create()
        url = reverse(ztiot)
        zaaktype_url = reverse(ztiot.zaaktype)
        informatieobjecttype_url = reverse(ztiot.informatieobjecttype, )

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        expected = {
            'url': f'http://testserver{url}',
            'zaaktype': f'http://testserver{zaaktype_url}',
            'informatieobjecttype':
            f'http://testserver{informatieobjecttype_url}',
            'volgnummer': ztiot.volgnummer,
            'richting': ztiot.richting,
            'statustype': None,
        }
        self.assertEqual(response.json(), expected)

    def test_create_ziot(self):
        zaaktype = ZaakTypeFactory.create()
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create()
        informatieobjecttype_url = reverse(informatieobjecttype)
        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'informatieobjecttype':
            f'http://testserver{informatieobjecttype_url}',
            'volgnummer': 13,
            'richting': RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        ziot = ZaakInformatieobjectType.objects.get(volgnummer=13)

        self.assertEqual(ziot.zaaktype, zaaktype)
        self.assertEqual(ziot.informatieobjecttype, informatieobjecttype)

    def test_create_ziot_fail_not_concept_zaaktype(self):
        zaaktype = ZaakTypeFactory.create(concept=False)
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create()
        informatieobjecttype_url = reverse(informatieobjecttype)
        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'informatieobjecttype':
            f'http://testserver{informatieobjecttype_url}',
            'volgnummer': 13,
            'richting': RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        data = response.json()
        self.assertEqual(
            data['detail'],
            'Creating relations between non-concept objects is forbidden')

    def test_create_ziot_fail_not_concept_informatieobjecttype(self):
        zaaktype = ZaakTypeFactory.create()
        zaaktype_url = reverse(zaaktype)
        informatieobjecttype = InformatieObjectTypeFactory.create(
            concept=False)
        informatieobjecttype_url = reverse(informatieobjecttype)
        data = {
            'zaaktype': f'http://testserver{zaaktype_url}',
            'informatieobjecttype':
            f'http://testserver{informatieobjecttype_url}',
            'volgnummer': 13,
            'richting': RichtingChoices.inkomend,
        }

        response = self.client.post(self.list_url, data)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        data = response.json()
        self.assertEqual(
            data['detail'],
            'Creating relations between non-concept objects is forbidden')

    def test_delete_ziot(self):
        ziot = ZaakInformatieobjectTypeFactory.create()
        ziot_url = reverse(ziot)

        response = self.client.delete(ziot_url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(ZaakInformatieobjectType.objects.filter(id=ziot.id))

    def test_delete_ziot_fail_not_concept_zaaktype(self):
        ziot = ZaakInformatieobjectTypeFactory.create(zaaktype__concept=False)
        ziot_url = reverse(ziot)

        response = self.client.delete(ziot_url)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        data = response.json()
        self.assertEqual(data['detail'],
                         'Alleen concepten kunnen worden verwijderd.')

    def test_delete_ziot_fail_not_concept_informatieobjecttype(self):
        ziot = ZaakInformatieobjectTypeFactory.create(
            informatieobjecttype__concept=False)
        ziot_url = reverse(ziot)

        response = self.client.delete(ziot_url)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        data = response.json()
        self.assertEqual(data['detail'],
                         'Alleen concepten kunnen worden verwijderd.')
class ObjectInformatieObjectTests(JWTAuthMixin, APITestCase):
    heeft_alle_autorisaties = True
    list_url = reverse_lazy("objectinformatieobject-list")

    def test_create_with_objecttype_zaak(self):
        zaak = ZaakFactory.create()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"
        # relate the two
        ZaakInformatieObjectFactory.create(zaak=zaak, informatieobject=eio.canonical)

        # get OIO created via signals
        ObjectInformatieObject.objects.get()

        zaak_url = reverse(zaak)

        response = self.client.post(
            self.list_url,
            {
                "object": f"http://testserver{zaak_url}",
                "informatieobject": eio_url,
                "objectType": "zaak",
            },
        )

        self.assertEqual(
            response.status_code, status.HTTP_400_BAD_REQUEST, response.data
        )

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unique")

    def test_create_with_objecttype_besluit(self):
        besluit = BesluitFactory.create()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        BesluitInformatieObjectFactory.create(
            besluit=besluit, informatieobject=eio.canonical
        )

        # get OIO created via signals
        ObjectInformatieObject.objects.get()

        besluit_url = reverse(besluit)

        response = self.client.post(
            self.list_url,
            {
                "object": f"http://testserver{besluit_url}",
                "informatieobject": f"http://testserver{eio_path}",
                "objectType": "besluit",
            },
        )

        self.assertEqual(
            response.status_code, status.HTTP_400_BAD_REQUEST, response.data
        )

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unique")

    def test_create_with_objecttype_other_fail(self):
        besluit = BesluitFactory.create()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"
        # relate the two
        BesluitInformatieObjectFactory.create(
            besluit=besluit, informatieobject=eio.canonical
        )

        besluit_url = reverse(besluit)

        response = self.client.post(
            self.list_url,
            {
                "object": f"http://testserver{besluit_url}",
                "informatieobject": eio_url,
                "objectType": "other",
            },
        )

        self.assertEqual(
            response.status_code, status.HTTP_400_BAD_REQUEST, response.data
        )
        error = get_validation_errors(response, "objectType")
        self.assertEqual(error["code"], "invalid_choice")

    def test_read_with_objecttype_zaak(self):
        zaak = ZaakFactory.create()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"
        # relate the two
        ZaakInformatieObjectFactory.create(zaak=zaak, informatieobject=eio.canonical)

        # get OIO created via signals
        oio = ObjectInformatieObject.objects.get()

        oio_url = reverse("objectinformatieobject-detail", kwargs={"uuid": oio.uuid})
        zaak_url = reverse(zaak)

        response = self.client.get(oio_url)

        expeceted_response_data = {
            "url": f"http://testserver{oio_url}",
            "object": f"http://testserver{zaak_url}",
            "informatieobject": eio_url,
            "object_type": "zaak",
        }

        self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
        self.assertEqual(response.data, expeceted_response_data)

    def test_read_with_objecttype_besluit(self):
        besluit = BesluitFactory.create()
        eio = EnkelvoudigInformatieObjectFactory.create()
        eio_path = reverse(eio)
        eio_url = f"http://testserver{eio_path}"
        # relate the two
        BesluitInformatieObjectFactory.create(
            besluit=besluit, informatieobject=eio.canonical
        )

        # get OIO created via signals
        oio = ObjectInformatieObject.objects.get()

        oio_url = reverse("objectinformatieobject-detail", kwargs={"uuid": oio.uuid})
        besluit_url = reverse(besluit)

        response = self.client.get(oio_url)

        expeceted_response_data = {
            "url": f"http://testserver{oio_url}",
            "object": f"http://testserver{besluit_url}",
            "informatieobject": eio_url,
            "object_type": "besluit",
        }

        self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
        self.assertEqual(response.data, expeceted_response_data)

    def test_post_object_without_created_relations(self):
        """
        Test the (informatieobject, object) unique together validation.

        This is expected to fail, since there is no actual creation in database.
        It will however become relevant again when we're handling remote
        references.
        """
        zaak = ZaakFactory.create()
        eio = EnkelvoudigInformatieObjectFactory.create()
        zaak_url = reverse(zaak)
        eio_url = reverse(eio)

        content = {
            "informatieobject": f"http://testserver{eio_url}",
            "object": f"http://testserver{zaak_url}",
            "objectType": ObjectTypes.zaak,
        }

        # Send to the API
        response = self.client.post(self.list_url, content)

        self.assertEqual(
            response.status_code, status.HTTP_400_BAD_REQUEST, response.data
        )

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "inconsistent-relation")

    def test_filter_eio(self):
        bio = BesluitInformatieObjectFactory.create()
        ZaakInformatieObjectFactory.create()  # may not show up
        eio_detail_url = (
            f"http://openzaak.nl{reverse(bio.informatieobject.latest_version)}"
        )

        response = self.client.get(
            self.list_url,
            {"informatieobject": eio_detail_url},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["informatieobject"], eio_detail_url)

    def test_filter_zaak(self):
        zio = ZaakInformatieObjectFactory.create()
        ZaakInformatieObjectFactory.create()  # may not show up
        eio_detail_url = (
            f"http://openzaak.nl{reverse(zio.informatieobject.latest_version)}"
        )
        zaak_url = reverse(zio.zaak)

        response = self.client.get(
            self.list_url,
            {"object": f"http://openzaak.nl{zaak_url}"},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["informatieobject"], eio_detail_url)

    def test_filter_besluit(self):
        bio = BesluitInformatieObjectFactory.create()
        BesluitInformatieObjectFactory.create()  # may not show up
        eio_detail_url = (
            f"http://openzaak.nl{reverse(bio.informatieobject.latest_version)}"
        )
        besluit_url = reverse(bio.besluit)

        response = self.client.get(
            self.list_url,
            {"object": f"http://openzaak.nl{besluit_url}"},
            HTTP_HOST="openzaak.nl",
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]["informatieobject"], eio_detail_url)

    def test_validate_unknown_query_params(self):
        url = reverse(ObjectInformatieObject)

        response = self.client.get(url, {"someparam": "somevalue"})

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        error = get_validation_errors(response, "nonFieldErrors")
        self.assertEqual(error["code"], "unknown-parameters")
Ejemplo n.º 30
0
class ZaakInformatieobjectTypeFilterAPITests(APITestCase):
    maxDiff = None
    list_url = reverse_lazy(ZaakInformatieobjectType)

    def test_filter_zaaktype(self):
        ztiot1, ztiot2 = ZaakInformatieobjectTypeFactory.create_batch(
            2, zaaktype__concept=False, informatieobjecttype__concept=False)
        url = f'http://testserver{reverse(ztiot1)}'
        zaaktype1_url = reverse(ztiot1.zaaktype)
        zaaktype2_url = reverse(ztiot2.zaaktype)
        zaaktype1_url = f'http://testserver{zaaktype1_url}'
        zaaktype2_url = f'http://testserver{zaaktype2_url}'

        response = self.client.get(self.list_url, {'zaaktype': zaaktype1_url})

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()['results']

        self.assertEqual(data[0]['url'], url)
        self.assertEqual(data[0]['zaaktype'], zaaktype1_url)
        self.assertNotEqual(data[0]['zaaktype'], zaaktype2_url)

    def test_filter_informatieobjecttype(self):
        ztiot1, ztiot2 = ZaakInformatieobjectTypeFactory.create_batch(
            2, zaaktype__concept=False, informatieobjecttype__concept=False)
        url = f'http://testserver{reverse(ztiot1)}'
        informatieobjecttype1_url = reverse(ztiot1.informatieobjecttype)
        informatieobjecttype2_url = reverse(ztiot2.informatieobjecttype)
        informatieobjecttype1_url = f'http://testserver{informatieobjecttype1_url}'
        informatieobjecttype2_url = f'http://testserver{informatieobjecttype2_url}'

        response = self.client.get(
            self.list_url, {'informatieobjecttype': informatieobjecttype1_url})

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()['results']

        self.assertEqual(data[0]['url'], url)
        self.assertEqual(data[0]['informatieobjecttype'],
                         informatieobjecttype1_url)
        self.assertNotEqual(data[0]['informatieobjecttype'],
                            informatieobjecttype2_url)

    def test_filter_ziot_status_alles(self):
        ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=True)
        ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=True)
        ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=False)
        ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=False)

        response = self.client.get(self.list_url, {'status': 'alles'})
        self.assertEqual(response.status_code, 200)

        data = response.json()['results']

        self.assertEqual(len(data), 4)

    def test_filter_ziot_status_concept(self):
        ziot1 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=True)
        ziot2 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=True)
        ziot3 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=False)
        ziot4 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=False)
        ziot1_url = reverse(ziot1)

        response = self.client.get(self.list_url, {'status': 'concept'})
        self.assertEqual(response.status_code, 200)

        data = response.json()['results']

        self.assertEqual(len(data), 1)
        self.assertEqual(data[0]['url'], f'http://testserver{ziot1_url}')

    def test_filter_ziot_status_definitief(self):
        ziot1 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=True)
        ziot2 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=True)
        ziot3 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=True, informatieobjecttype__concept=False)
        ziot4 = ZaakInformatieobjectTypeFactory.create(
            zaaktype__concept=False, informatieobjecttype__concept=False)
        ziot4_url = reverse(ziot4)

        response = self.client.get(self.list_url, {'status': 'definitief'})
        self.assertEqual(response.status_code, 200)

        data = response.json()['results']

        self.assertEqual(len(data), 1)
        self.assertEqual(data[0]['url'], f'http://testserver{ziot4_url}')