Skip to content

nautobot.apps.testing

Utilities for apps to implement test automation.

nautobot.apps.testing.APITestCase

Bases: ModelTestCase

Base test case for API requests.

api_version: Specific API version to test. Leave unset to test the default behavior. Override with set_api_version()

Source code in nautobot/utilities/testing/api.py
@tag("api")
class APITestCase(ModelTestCase):
    """
    Base test case for API requests.

    api_version: Specific API version to test. Leave unset to test the default behavior. Override with set_api_version()
    """

    api_version = None

    def setUp(self):
        """
        Create a token for API calls.
        """
        super().setUp()
        self.client.logout()
        self.token = Token.objects.create(user=self.user)
        self.header = {"HTTP_AUTHORIZATION": f"Token {self.token.key}"}
        if self.api_version:
            self.set_api_version(self.api_version)

    def set_api_version(self, api_version):
        """Set or unset a specific API version for requests in this test case."""
        if api_version is None:
            self.header["HTTP_ACCEPT"] = "application/json"
        else:
            self.header["HTTP_ACCEPT"] = f"application/json; version={api_version}"

    def _get_detail_url(self, instance):
        viewname = get_route_for_model(instance, "detail", api=True)
        return reverse(viewname, kwargs={"pk": instance.pk})

    def _get_list_url(self):
        viewname = get_route_for_model(self.model, "list", api=True)
        return reverse(viewname)

setUp()

Create a token for API calls.

Source code in nautobot/utilities/testing/api.py
def setUp(self):
    """
    Create a token for API calls.
    """
    super().setUp()
    self.client.logout()
    self.token = Token.objects.create(user=self.user)
    self.header = {"HTTP_AUTHORIZATION": f"Token {self.token.key}"}
    if self.api_version:
        self.set_api_version(self.api_version)

set_api_version(api_version)

Set or unset a specific API version for requests in this test case.

Source code in nautobot/utilities/testing/api.py
def set_api_version(self, api_version):
    """Set or unset a specific API version for requests in this test case."""
    if api_version is None:
        self.header["HTTP_ACCEPT"] = "application/json"
    else:
        self.header["HTTP_ACCEPT"] = f"application/json; version={api_version}"

nautobot.apps.testing.APIViewTestCases

Source code in nautobot/utilities/testing/api.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
@tag("unit")
class APIViewTestCases:
    class GetObjectViewTestCase(APITestCase):
        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_get_object_anonymous(self):
            """
            GET a single object as an unauthenticated user.
            """
            url = self._get_detail_url(self._get_queryset().first())
            if (
                self.model._meta.app_label,
                self.model._meta.model_name,
            ) in settings.EXEMPT_EXCLUDE_MODELS:
                # Models listed in EXEMPT_EXCLUDE_MODELS should not be accessible to anonymous users
                with disable_warnings("django.request"):
                    self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
            else:
                response = self.client.get(url, **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_get_object_without_permission(self):
            """
            GET a single object as an authenticated user without the required permission.
            """
            url = self._get_detail_url(self._get_queryset().first())

            # Try GET without permission
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_get_object(self):
            """
            GET a single object as an authenticated user with permission to view the object.
            """
            self.assertGreaterEqual(
                self._get_queryset().count(),
                2,
                f"Test requires the creation of at least two {self.model} instances",
            )
            instance1, instance2 = self._get_queryset()[:2]

            # Add object-level permission
            obj_perm = ObjectPermission(
                name="Test permission",
                constraints={"pk": instance1.pk},
                actions=["view"],
            )
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET to non-permitted object
            url = self._get_detail_url(instance2)
            self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_404_NOT_FOUND)

            # Try GET to permitted object
            url = self._get_detail_url(instance1)
            response = self.client.get(url, **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertIsInstance(response.data, dict)
            # Fields that should be present in *ALL* model serializers:
            self.assertIn("id", response.data)
            self.assertEqual(str(response.data["id"]), str(instance1.pk))  # coerce to str to handle both int and uuid
            self.assertIn("url", response.data)
            self.assertIn("display", response.data)
            self.assertIsInstance(response.data["display"], str)
            # Fields that should be present in appropriate model serializers:
            if issubclass(self.model, ChangeLoggedModel):
                self.assertIn("created", response.data)
                self.assertIn("last_updated", response.data)
            # Fields that should be absent by default (opt-in fields):
            self.assertNotIn("computed_fields", response.data)
            self.assertNotIn("relationships", response.data)

            # If opt-in fields are supported on this model, make sure they can be opted into

            custom_fields_registry = registry["model_features"]["custom_fields"]
            # computed fields and custom fields use the same registry
            cf_supported = self.model._meta.model_name in custom_fields_registry.get(self.model._meta.app_label, {})
            if cf_supported:  # custom_fields is not an opt-in field, it should always be present if supported
                self.assertIn("custom_fields", response.data)
                self.assertIsInstance(response.data["custom_fields"], dict)

            relationships_registry = registry["model_features"]["relationships"]
            rel_supported = self.model._meta.model_name in relationships_registry.get(self.model._meta.app_label, {})
            if cf_supported or rel_supported:
                query_params = []
                if cf_supported:
                    query_params.append("include=computed_fields")
                if rel_supported:
                    query_params.append("include=relationships")
                query_string = "&".join(query_params)
                url = f"{url}?{query_string}"

                response = self.client.get(url, **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                self.assertIsInstance(response.data, dict)
                if cf_supported:
                    self.assertIn("computed_fields", response.data)
                    self.assertIsInstance(response.data["computed_fields"], dict)
                else:
                    self.assertNotIn("computed_fields", response.data)
                if rel_supported:
                    self.assertIn("relationships", response.data)
                    self.assertIsInstance(response.data["relationships"], dict)
                else:
                    self.assertNotIn("relationships", response.data)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_options_object(self):
            """
            Make an OPTIONS request for a single object.
            """
            url = self._get_detail_url(self._get_queryset().first())
            response = self.client.options(url, **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)

    class ListObjectsViewTestCase(APITestCase):
        brief_fields = []
        choices_fields = None
        filterset = None

        def get_filterset(self):
            return self.filterset or get_filterset_for_model(self.model)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_list_objects_anonymous(self):
            """
            GET a list of objects as an unauthenticated user.
            """
            url = self._get_list_url()
            if (
                self.model._meta.app_label,
                self.model._meta.model_name,
            ) in settings.EXEMPT_EXCLUDE_MODELS:
                # Models listed in EXEMPT_EXCLUDE_MODELS should not be accessible to anonymous users
                with disable_warnings("django.request"):
                    self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
            else:
                # TODO(Glenn): if we're passing **self.header, we are *by definition* **NOT** anonymous!!
                response = self.client.get(url, **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                self.assertIsInstance(response.data, dict)
                self.assertIn("results", response.data)
                self.assertEqual(len(response.data["results"]), self._get_queryset().count())

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_brief(self):
            """
            GET a list of objects using the "brief" parameter.
            """
            self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
            url = f"{self._get_list_url()}?brief=1"
            response = self.client.get(url, **self.header)

            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertIsInstance(response.data, dict)
            self.assertIn("results", response.data)
            self.assertEqual(len(response.data["results"]), self._get_queryset().count())
            self.assertEqual(
                sorted(response.data["results"][0]),
                self.brief_fields,
                "In order to test the brief API parameter the brief fields need to be manually added to "
                "self.brief_fields. If this is already the case, perhaps the serializer is implemented incorrectly?",
            )

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_without_permission(self):
            """
            GET a list of objects as an authenticated user without the required permission.
            """
            url = self._get_list_url()

            # Try GET without permission
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects(self):
            """
            GET a list of objects as an authenticated user with permission to view the objects.
            """
            self.assertGreaterEqual(
                self._get_queryset().count(),
                3,
                f"Test requires the creation of at least three {self.model} instances",
            )
            instance1, instance2 = self._get_queryset()[:2]

            # Add object-level permission
            obj_perm = ObjectPermission(
                name="Test permission",
                constraints={"pk__in": [instance1.pk, instance2.pk]},
                actions=["view"],
            )
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET to permitted objects
            response = self.client.get(self._get_list_url(), **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertIsInstance(response.data, dict)
            self.assertIn("results", response.data)
            self.assertEqual(len(response.data["results"]), 2)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_filtered(self):
            """
            GET a list of objects filtered by ID.
            """
            self.assertGreaterEqual(
                self._get_queryset().count(),
                3,
                f"Test requires the creation of at least three {self.model} instances",
            )
            self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
            instance1, instance2 = self._get_queryset()[:2]
            response = self.client.get(f"{self._get_list_url()}?id={instance1.pk}&id={instance2.pk}", **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertIsInstance(response.data, dict)
            self.assertIn("results", response.data)
            self.assertEqual(len(response.data["results"]), 2)
            for entry in response.data["results"]:
                self.assertIn(str(entry["id"]), [str(instance1.pk), str(instance2.pk)])

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[], STRICT_FILTERING=True)
        def test_list_objects_unknown_filter_strict_filtering(self):
            """
            GET a list of objects with an unknown filter parameter and strict filtering, expect a 400 response.
            """
            self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
            with disable_warnings("django.request"):
                response = self.client.get(f"{self._get_list_url()}?ice_cream_flavor=rocky-road", **self.header)
            self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
            self.assertIsInstance(response.data, dict)
            self.assertIn("ice_cream_flavor", response.data)
            self.assertIsInstance(response.data["ice_cream_flavor"], list)
            self.assertEqual("Unknown filter field", str(response.data["ice_cream_flavor"][0]))

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[], STRICT_FILTERING=False)
        def test_list_objects_unknown_filter_no_strict_filtering(self):
            """
            GET a list of objects with an unknown filter parameter and no strict filtering, expect it to be ignored.
            """
            self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
            with self.assertLogs("nautobot.utilities.filters") as cm:
                response = self.client.get(f"{self._get_list_url()}?ice_cream_flavor=rocky-road", **self.header)
            self.assertEqual(
                cm.output,
                [
                    f"WARNING:nautobot.utilities.filters:{self.get_filterset().__name__}: "
                    'Unknown filter field "ice_cream_flavor"',
                ],
            )
            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertIsInstance(response.data, dict)
            self.assertIn("results", response.data)
            self.assertEqual(len(response.data["results"]), self._get_queryset().count())

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_options_objects(self):
            """
            Make an OPTIONS request for a list endpoint.
            """
            response = self.client.options(self._get_list_url(), **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_status_options_returns_expected_choices(self):
            # Set to self.choices_fields as empty set to compare classes that shouldn't have any choice fields on serializer.
            if not self.choices_fields:
                self.choices_fields = set()

            # Don't bother testing if there's no `status` field.
            if "status" not in self.choices_fields:
                self.skipTest("Object does not contain a `status` field.")

            # Save self.user as superuser to be able to view available choices on list views.
            self.user.is_superuser = True
            self.user.save()

            response = self.client.options(self._get_list_url(), **self.header)
            data = response.json()

            self.assertIn("actions", data)
            self.assertIn("POST", data["actions"])

            actions = data["actions"]["POST"]
            choices = actions["status"]["choices"]

            # Import Status here to avoid circular import issues w/ test utilities.
            from nautobot.extras.models import Status  # noqa

            # Assert that the expected Status objects matches what is emitted.
            statuses = Status.objects.get_for_model(self.model)
            expected = [{"value": v, "display": d} for (v, d) in statuses.values_list("slug", "name")]
            self.assertListEqual(choices, expected)

    class CreateObjectViewTestCase(APITestCase):
        create_data = []
        validation_excluded_fields = []
        slug_source: Optional[Union[str, Sequence[str]]] = None
        slugify_function = staticmethod(slugify)

        def test_create_object_without_permission(self):
            """
            POST a single object without permission.
            """
            url = self._get_list_url()

            # Try POST without permission
            with disable_warnings("django.request"):
                response = self.client.post(url, self.create_data[0], format="json", **self.header)
                self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

        def check_expected_slug(self, obj):
            slug_source = self.slug_source if isinstance(self.slug_source, (list, tuple)) else [self.slug_source]
            expected_slug = ""
            for source_item in slug_source:
                # e.g. self.slug_source = ["parent__name", "name"]
                source_keys = source_item.split("__")
                try:
                    val = getattr(obj, source_keys[0])
                    for key in source_keys[1:]:
                        val = getattr(val, key)
                except AttributeError:
                    val = ""
                if val:
                    if expected_slug != "":
                        expected_slug += "-"
                    expected_slug += self.slugify_function(val)

            self.assertNotEqual(expected_slug, "")
            self.assertEqual(obj.slug, expected_slug)

        def test_create_object(self):
            """
            POST a single object with permission.
            """
            # Add object-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["add"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            initial_count = self._get_queryset().count()
            for i, create_data in enumerate(self.create_data):
                response = self.client.post(self._get_list_url(), create_data, format="json", **self.header)
                self.assertHttpStatus(response, status.HTTP_201_CREATED)
                self.assertEqual(self._get_queryset().count(), initial_count + i + 1)
                instance = self._get_queryset().get(pk=response.data["id"])
                self.assertInstanceEqual(
                    instance,
                    create_data,
                    exclude=self.validation_excluded_fields,
                    api=True,
                )

                # Check if Slug field is automatically created
                if self.slug_source is not None and "slug" not in create_data:
                    self.check_expected_slug(self._get_queryset().get(pk=response.data["id"]))

                # Verify ObjectChange creation
                if hasattr(self.model, "to_objectchange"):
                    objectchanges = get_changes_for_model(instance)
                    self.assertEqual(len(objectchanges), 1)
                    self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_CREATE)

        def test_bulk_create_objects(self):
            """
            POST a set of objects in a single request.
            """
            # Add object-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["add"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            initial_count = self._get_queryset().count()
            response = self.client.post(self._get_list_url(), self.create_data, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_201_CREATED)
            self.assertEqual(len(response.data), len(self.create_data))
            self.assertEqual(self._get_queryset().count(), initial_count + len(self.create_data))
            for i, obj in enumerate(response.data):
                for field in self.create_data[i]:
                    if field not in self.validation_excluded_fields:
                        self.assertIn(
                            field,
                            obj,
                            f"Bulk create field '{field}' missing from object {i} in response",
                        )
            for i, obj in enumerate(response.data):
                self.assertInstanceEqual(
                    self._get_queryset().get(pk=obj["id"]),
                    self.create_data[i],
                    exclude=self.validation_excluded_fields,
                    api=True,
                )
                if self.slug_source is not None and "slug" not in self.create_data[i]:
                    self.check_expected_slug(self._get_queryset().get(pk=obj["id"]))

    class UpdateObjectViewTestCase(APITestCase):
        update_data = {}
        bulk_update_data: Optional[dict] = None
        validation_excluded_fields = []
        choices_fields = None

        def test_update_object_without_permission(self):
            """
            PATCH a single object without permission.
            """
            url = self._get_detail_url(self._get_queryset().first())
            update_data = self.update_data or getattr(self, "create_data")[0]

            # Try PATCH without permission
            with disable_warnings("django.request"):
                response = self.client.patch(url, update_data, format="json", **self.header)
                self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

        def test_update_object(self):
            """
            PATCH a single object identified by its ID.
            """
            instance = self._get_queryset().first()
            url = self._get_detail_url(instance)
            update_data = self.update_data or getattr(self, "create_data")[0]

            # Add object-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["change"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            response = self.client.patch(url, update_data, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            instance.refresh_from_db()
            self.assertInstanceEqual(instance, update_data, exclude=self.validation_excluded_fields, api=True)

            # Verify ObjectChange creation
            if hasattr(self.model, "to_objectchange"):
                objectchanges = get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_UPDATE)

        def test_bulk_update_objects(self):
            """
            PATCH a set of objects in a single request.
            """
            if self.bulk_update_data is None:
                self.skipTest("Bulk update data not set")

            # Add object-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["change"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            id_list = list(self._get_queryset().values_list("id", flat=True)[:3])
            self.assertEqual(len(id_list), 3, "Insufficient number of objects to test bulk update")
            data = [{"id": id, **self.bulk_update_data} for id in id_list]

            response = self.client.patch(self._get_list_url(), data, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            for i, obj in enumerate(response.data):
                for field, _value in self.bulk_update_data.items():
                    self.assertIn(
                        field,
                        obj,
                        f"Bulk update field '{field}' missing from object {i} in response",
                    )
                    # TODO(Glenn): shouldn't we also check that obj[field] == value?
            for instance in self._get_queryset().filter(pk__in=id_list):
                self.assertInstanceEqual(
                    instance,
                    self.bulk_update_data,
                    exclude=self.validation_excluded_fields,
                    api=True,
                )

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_options_objects_returns_display_and_value(self):
            """
            Make an OPTIONS request for a list endpoint and validate choices use the display and value keys.
            """
            # Save self.user as superuser to be able to view available choices on list views.
            self.user.is_superuser = True
            self.user.save()

            response = self.client.options(self._get_list_url(), **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            data = response.json()

            self.assertIn("actions", data)

            # Grab any field that has choices defined (fields with enums)
            if "POST" in data["actions"]:
                field_choices = {k: v["choices"] for k, v in data["actions"]["POST"].items() if "choices" in v}
            elif "PUT" in data["actions"]:  # JobModelViewSet supports editing but not creation
                field_choices = {k: v["choices"] for k, v in data["actions"]["PUT"].items() if "choices" in v}
            else:
                self.fail(f"Neither PUT nor POST are available actions in: {data['actions']}")

            # Will successfully assert if field_choices has entries and will not fail if model as no enum choices
            # Broken down to provide better failure messages
            for field, choices in field_choices.items():
                for choice in choices:
                    self.assertIn("display", choice, f"A choice in {field} is missing the display key")
                    self.assertIn("value", choice, f"A choice in {field} is missing the value key")

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_options_returns_expected_choices(self):
            """
            Make an OPTIONS request for a list endpoint and validate choices match expected choices for serializer.
            """
            # Set self.choices_fields as empty set to compare classes that shouldn't have any choices on serializer.
            if not self.choices_fields:
                self.choices_fields = set()

            # Save self.user as superuser to be able to view available choices on list views.
            self.user.is_superuser = True
            self.user.save()

            response = self.client.options(self._get_list_url(), **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            data = response.json()

            self.assertIn("actions", data)

            # Grab any field name that has choices defined (fields with enums)
            if "POST" in data["actions"]:
                field_choices = {k for k, v in data["actions"]["POST"].items() if "choices" in v}
            elif "PUT" in data["actions"]:  # JobModelViewSet supports editing but not creation
                field_choices = {k for k, v in data["actions"]["PUT"].items() if "choices" in v}
            else:
                self.fail(f"Neither PUT nor POST are available actions in: {data['actions']}")

            self.assertEqual(
                set(self.choices_fields),
                field_choices,
                "All field names of choice fields for a given model serializer need to be manually added to "
                "self.choices_fields. If this is already the case, perhaps the serializer is implemented incorrectly?",
            )

    class DeleteObjectViewTestCase(APITestCase):
        def get_deletable_object(self):
            """
            Get an instance that can be deleted.

            For some models this may just be any random object, but when we have FKs with `on_delete=models.PROTECT`
            (as is often the case) we need to find or create an instance that doesn't have such entanglements.
            """
            instance = get_deletable_objects(self.model, self._get_queryset()).first()
            if instance is None:
                self.fail("Couldn't find a single deletable object!")
            return instance

        def get_deletable_object_pks(self):
            """
            Get a list of PKs corresponding to objects that can be safely bulk-deleted.

            For some models this may just be any random objects, but when we have FKs with `on_delete=models.PROTECT`
            (as is often the case) we need to find or create an instance that doesn't have such entanglements.
            """
            instances = get_deletable_objects(self.model, self._get_queryset()).values_list("pk", flat=True)[:3]
            if len(instances) < 3:
                self.fail(f"Couldn't find 3 deletable objects, only found {len(instances)}!")
            return instances

        def test_delete_object_without_permission(self):
            """
            DELETE a single object without permission.
            """
            url = self._get_detail_url(self.get_deletable_object())

            # Try DELETE without permission
            with disable_warnings("django.request"):
                response = self.client.delete(url, **self.header)
                self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

        def test_delete_object(self):
            """
            DELETE a single object identified by its primary key.
            """
            instance = self.get_deletable_object()
            url = self._get_detail_url(instance)

            # Add object-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["delete"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            response = self.client.delete(url, **self.header)
            self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
            self.assertFalse(self._get_queryset().filter(pk=instance.pk).exists())

            # Verify ObjectChange creation
            if hasattr(self.model, "to_objectchange"):
                objectchanges = get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_DELETE)

        def test_bulk_delete_objects(self):
            """
            DELETE a set of objects in a single request.
            """
            id_list = self.get_deletable_object_pks()
            # Add object-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["delete"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            data = [{"id": id} for id in id_list]

            initial_count = self._get_queryset().count()
            response = self.client.delete(self._get_list_url(), data, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
            self.assertEqual(self._get_queryset().count(), initial_count - len(id_list))

    class NotesURLViewTestCase(APITestCase):
        """Validate Notes URL on objects that have the Note model Mixin."""

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_notes_url_on_object(self):
            if hasattr(self.model, "notes"):
                instance1 = self._get_queryset().first()
                # Add object-level permission
                obj_perm = ObjectPermission(
                    name="Test permission",
                    constraints={"pk": instance1.pk},
                    actions=["view"],
                )
                obj_perm.save()
                obj_perm.users.add(self.user)
                obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
                url = self._get_detail_url(instance1)
                response = self.client.get(url, **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                self.assertIn("notes_url", response.data)
                self.assertIn(f"{url}notes/", str(response.data["notes_url"]))

    class APIViewTestCase(
        GetObjectViewTestCase,
        ListObjectsViewTestCase,
        CreateObjectViewTestCase,
        UpdateObjectViewTestCase,
        DeleteObjectViewTestCase,
        NotesURLViewTestCase,
    ):
        pass

CreateObjectViewTestCase

Bases: APITestCase

Source code in nautobot/utilities/testing/api.py
class CreateObjectViewTestCase(APITestCase):
    create_data = []
    validation_excluded_fields = []
    slug_source: Optional[Union[str, Sequence[str]]] = None
    slugify_function = staticmethod(slugify)

    def test_create_object_without_permission(self):
        """
        POST a single object without permission.
        """
        url = self._get_list_url()

        # Try POST without permission
        with disable_warnings("django.request"):
            response = self.client.post(url, self.create_data[0], format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

    def check_expected_slug(self, obj):
        slug_source = self.slug_source if isinstance(self.slug_source, (list, tuple)) else [self.slug_source]
        expected_slug = ""
        for source_item in slug_source:
            # e.g. self.slug_source = ["parent__name", "name"]
            source_keys = source_item.split("__")
            try:
                val = getattr(obj, source_keys[0])
                for key in source_keys[1:]:
                    val = getattr(val, key)
            except AttributeError:
                val = ""
            if val:
                if expected_slug != "":
                    expected_slug += "-"
                expected_slug += self.slugify_function(val)

        self.assertNotEqual(expected_slug, "")
        self.assertEqual(obj.slug, expected_slug)

    def test_create_object(self):
        """
        POST a single object with permission.
        """
        # Add object-level permission
        obj_perm = ObjectPermission(name="Test permission", actions=["add"])
        obj_perm.save()
        obj_perm.users.add(self.user)
        obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

        initial_count = self._get_queryset().count()
        for i, create_data in enumerate(self.create_data):
            response = self.client.post(self._get_list_url(), create_data, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_201_CREATED)
            self.assertEqual(self._get_queryset().count(), initial_count + i + 1)
            instance = self._get_queryset().get(pk=response.data["id"])
            self.assertInstanceEqual(
                instance,
                create_data,
                exclude=self.validation_excluded_fields,
                api=True,
            )

            # Check if Slug field is automatically created
            if self.slug_source is not None and "slug" not in create_data:
                self.check_expected_slug(self._get_queryset().get(pk=response.data["id"]))

            # Verify ObjectChange creation
            if hasattr(self.model, "to_objectchange"):
                objectchanges = get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_CREATE)

    def test_bulk_create_objects(self):
        """
        POST a set of objects in a single request.
        """
        # Add object-level permission
        obj_perm = ObjectPermission(name="Test permission", actions=["add"])
        obj_perm.save()
        obj_perm.users.add(self.user)
        obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

        initial_count = self._get_queryset().count()
        response = self.client.post(self._get_list_url(), self.create_data, format="json", **self.header)
        self.assertHttpStatus(response, status.HTTP_201_CREATED)
        self.assertEqual(len(response.data), len(self.create_data))
        self.assertEqual(self._get_queryset().count(), initial_count + len(self.create_data))
        for i, obj in enumerate(response.data):
            for field in self.create_data[i]:
                if field not in self.validation_excluded_fields:
                    self.assertIn(
                        field,
                        obj,
                        f"Bulk create field '{field}' missing from object {i} in response",
                    )
        for i, obj in enumerate(response.data):
            self.assertInstanceEqual(
                self._get_queryset().get(pk=obj["id"]),
                self.create_data[i],
                exclude=self.validation_excluded_fields,
                api=True,
            )
            if self.slug_source is not None and "slug" not in self.create_data[i]:
                self.check_expected_slug(self._get_queryset().get(pk=obj["id"]))

test_bulk_create_objects()

POST a set of objects in a single request.

Source code in nautobot/utilities/testing/api.py
def test_bulk_create_objects(self):
    """
    POST a set of objects in a single request.
    """
    # Add object-level permission
    obj_perm = ObjectPermission(name="Test permission", actions=["add"])
    obj_perm.save()
    obj_perm.users.add(self.user)
    obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

    initial_count = self._get_queryset().count()
    response = self.client.post(self._get_list_url(), self.create_data, format="json", **self.header)
    self.assertHttpStatus(response, status.HTTP_201_CREATED)
    self.assertEqual(len(response.data), len(self.create_data))
    self.assertEqual(self._get_queryset().count(), initial_count + len(self.create_data))
    for i, obj in enumerate(response.data):
        for field in self.create_data[i]:
            if field not in self.validation_excluded_fields:
                self.assertIn(
                    field,
                    obj,
                    f"Bulk create field '{field}' missing from object {i} in response",
                )
    for i, obj in enumerate(response.data):
        self.assertInstanceEqual(
            self._get_queryset().get(pk=obj["id"]),
            self.create_data[i],
            exclude=self.validation_excluded_fields,
            api=True,
        )
        if self.slug_source is not None and "slug" not in self.create_data[i]:
            self.check_expected_slug(self._get_queryset().get(pk=obj["id"]))

test_create_object()

POST a single object with permission.

Source code in nautobot/utilities/testing/api.py
def test_create_object(self):
    """
    POST a single object with permission.
    """
    # Add object-level permission
    obj_perm = ObjectPermission(name="Test permission", actions=["add"])
    obj_perm.save()
    obj_perm.users.add(self.user)
    obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

    initial_count = self._get_queryset().count()
    for i, create_data in enumerate(self.create_data):
        response = self.client.post(self._get_list_url(), create_data, format="json", **self.header)
        self.assertHttpStatus(response, status.HTTP_201_CREATED)
        self.assertEqual(self._get_queryset().count(), initial_count + i + 1)
        instance = self._get_queryset().get(pk=response.data["id"])
        self.assertInstanceEqual(
            instance,
            create_data,
            exclude=self.validation_excluded_fields,
            api=True,
        )

        # Check if Slug field is automatically created
        if self.slug_source is not None and "slug" not in create_data:
            self.check_expected_slug(self._get_queryset().get(pk=response.data["id"]))

        # Verify ObjectChange creation
        if hasattr(self.model, "to_objectchange"):
            objectchanges = get_changes_for_model(instance)
            self.assertEqual(len(objectchanges), 1)
            self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_CREATE)

test_create_object_without_permission()

POST a single object without permission.

Source code in nautobot/utilities/testing/api.py
def test_create_object_without_permission(self):
    """
    POST a single object without permission.
    """
    url = self._get_list_url()

    # Try POST without permission
    with disable_warnings("django.request"):
        response = self.client.post(url, self.create_data[0], format="json", **self.header)
        self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

DeleteObjectViewTestCase

Bases: APITestCase

Source code in nautobot/utilities/testing/api.py
class DeleteObjectViewTestCase(APITestCase):
    def get_deletable_object(self):
        """
        Get an instance that can be deleted.

        For some models this may just be any random object, but when we have FKs with `on_delete=models.PROTECT`
        (as is often the case) we need to find or create an instance that doesn't have such entanglements.
        """
        instance = get_deletable_objects(self.model, self._get_queryset()).first()
        if instance is None:
            self.fail("Couldn't find a single deletable object!")
        return instance

    def get_deletable_object_pks(self):
        """
        Get a list of PKs corresponding to objects that can be safely bulk-deleted.

        For some models this may just be any random objects, but when we have FKs with `on_delete=models.PROTECT`
        (as is often the case) we need to find or create an instance that doesn't have such entanglements.
        """
        instances = get_deletable_objects(self.model, self._get_queryset()).values_list("pk", flat=True)[:3]
        if len(instances) < 3:
            self.fail(f"Couldn't find 3 deletable objects, only found {len(instances)}!")
        return instances

    def test_delete_object_without_permission(self):
        """
        DELETE a single object without permission.
        """
        url = self._get_detail_url(self.get_deletable_object())

        # Try DELETE without permission
        with disable_warnings("django.request"):
            response = self.client.delete(url, **self.header)
            self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

    def test_delete_object(self):
        """
        DELETE a single object identified by its primary key.
        """
        instance = self.get_deletable_object()
        url = self._get_detail_url(instance)

        # Add object-level permission
        obj_perm = ObjectPermission(name="Test permission", actions=["delete"])
        obj_perm.save()
        obj_perm.users.add(self.user)
        obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

        response = self.client.delete(url, **self.header)
        self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
        self.assertFalse(self._get_queryset().filter(pk=instance.pk).exists())

        # Verify ObjectChange creation
        if hasattr(self.model, "to_objectchange"):
            objectchanges = get_changes_for_model(instance)
            self.assertEqual(len(objectchanges), 1)
            self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_DELETE)

    def test_bulk_delete_objects(self):
        """
        DELETE a set of objects in a single request.
        """
        id_list = self.get_deletable_object_pks()
        # Add object-level permission
        obj_perm = ObjectPermission(name="Test permission", actions=["delete"])
        obj_perm.save()
        obj_perm.users.add(self.user)
        obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

        data = [{"id": id} for id in id_list]

        initial_count = self._get_queryset().count()
        response = self.client.delete(self._get_list_url(), data, format="json", **self.header)
        self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
        self.assertEqual(self._get_queryset().count(), initial_count - len(id_list))

get_deletable_object()

Get an instance that can be deleted.

For some models this may just be any random object, but when we have FKs with on_delete=models.PROTECT (as is often the case) we need to find or create an instance that doesn't have such entanglements.

Source code in nautobot/utilities/testing/api.py
def get_deletable_object(self):
    """
    Get an instance that can be deleted.

    For some models this may just be any random object, but when we have FKs with `on_delete=models.PROTECT`
    (as is often the case) we need to find or create an instance that doesn't have such entanglements.
    """
    instance = get_deletable_objects(self.model, self._get_queryset()).first()
    if instance is None:
        self.fail("Couldn't find a single deletable object!")
    return instance

get_deletable_object_pks()

Get a list of PKs corresponding to objects that can be safely bulk-deleted.

For some models this may just be any random objects, but when we have FKs with on_delete=models.PROTECT (as is often the case) we need to find or create an instance that doesn't have such entanglements.

Source code in nautobot/utilities/testing/api.py
def get_deletable_object_pks(self):
    """
    Get a list of PKs corresponding to objects that can be safely bulk-deleted.

    For some models this may just be any random objects, but when we have FKs with `on_delete=models.PROTECT`
    (as is often the case) we need to find or create an instance that doesn't have such entanglements.
    """
    instances = get_deletable_objects(self.model, self._get_queryset()).values_list("pk", flat=True)[:3]
    if len(instances) < 3:
        self.fail(f"Couldn't find 3 deletable objects, only found {len(instances)}!")
    return instances

test_bulk_delete_objects()

DELETE a set of objects in a single request.

Source code in nautobot/utilities/testing/api.py
def test_bulk_delete_objects(self):
    """
    DELETE a set of objects in a single request.
    """
    id_list = self.get_deletable_object_pks()
    # Add object-level permission
    obj_perm = ObjectPermission(name="Test permission", actions=["delete"])
    obj_perm.save()
    obj_perm.users.add(self.user)
    obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

    data = [{"id": id} for id in id_list]

    initial_count = self._get_queryset().count()
    response = self.client.delete(self._get_list_url(), data, format="json", **self.header)
    self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
    self.assertEqual(self._get_queryset().count(), initial_count - len(id_list))

test_delete_object()

DELETE a single object identified by its primary key.

Source code in nautobot/utilities/testing/api.py
def test_delete_object(self):
    """
    DELETE a single object identified by its primary key.
    """
    instance = self.get_deletable_object()
    url = self._get_detail_url(instance)

    # Add object-level permission
    obj_perm = ObjectPermission(name="Test permission", actions=["delete"])
    obj_perm.save()
    obj_perm.users.add(self.user)
    obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

    response = self.client.delete(url, **self.header)
    self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
    self.assertFalse(self._get_queryset().filter(pk=instance.pk).exists())

    # Verify ObjectChange creation
    if hasattr(self.model, "to_objectchange"):
        objectchanges = get_changes_for_model(instance)
        self.assertEqual(len(objectchanges), 1)
        self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_DELETE)

test_delete_object_without_permission()

DELETE a single object without permission.

Source code in nautobot/utilities/testing/api.py
def test_delete_object_without_permission(self):
    """
    DELETE a single object without permission.
    """
    url = self._get_detail_url(self.get_deletable_object())

    # Try DELETE without permission
    with disable_warnings("django.request"):
        response = self.client.delete(url, **self.header)
        self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

GetObjectViewTestCase

Bases: APITestCase

Source code in nautobot/utilities/testing/api.py
class GetObjectViewTestCase(APITestCase):
    @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
    def test_get_object_anonymous(self):
        """
        GET a single object as an unauthenticated user.
        """
        url = self._get_detail_url(self._get_queryset().first())
        if (
            self.model._meta.app_label,
            self.model._meta.model_name,
        ) in settings.EXEMPT_EXCLUDE_MODELS:
            # Models listed in EXEMPT_EXCLUDE_MODELS should not be accessible to anonymous users
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
        else:
            response = self.client.get(url, **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_get_object_without_permission(self):
        """
        GET a single object as an authenticated user without the required permission.
        """
        url = self._get_detail_url(self._get_queryset().first())

        # Try GET without permission
        with disable_warnings("django.request"):
            self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_get_object(self):
        """
        GET a single object as an authenticated user with permission to view the object.
        """
        self.assertGreaterEqual(
            self._get_queryset().count(),
            2,
            f"Test requires the creation of at least two {self.model} instances",
        )
        instance1, instance2 = self._get_queryset()[:2]

        # Add object-level permission
        obj_perm = ObjectPermission(
            name="Test permission",
            constraints={"pk": instance1.pk},
            actions=["view"],
        )
        obj_perm.save()
        obj_perm.users.add(self.user)
        obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

        # Try GET to non-permitted object
        url = self._get_detail_url(instance2)
        self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_404_NOT_FOUND)

        # Try GET to permitted object
        url = self._get_detail_url(instance1)
        response = self.client.get(url, **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        self.assertIsInstance(response.data, dict)
        # Fields that should be present in *ALL* model serializers:
        self.assertIn("id", response.data)
        self.assertEqual(str(response.data["id"]), str(instance1.pk))  # coerce to str to handle both int and uuid
        self.assertIn("url", response.data)
        self.assertIn("display", response.data)
        self.assertIsInstance(response.data["display"], str)
        # Fields that should be present in appropriate model serializers:
        if issubclass(self.model, ChangeLoggedModel):
            self.assertIn("created", response.data)
            self.assertIn("last_updated", response.data)
        # Fields that should be absent by default (opt-in fields):
        self.assertNotIn("computed_fields", response.data)
        self.assertNotIn("relationships", response.data)

        # If opt-in fields are supported on this model, make sure they can be opted into

        custom_fields_registry = registry["model_features"]["custom_fields"]
        # computed fields and custom fields use the same registry
        cf_supported = self.model._meta.model_name in custom_fields_registry.get(self.model._meta.app_label, {})
        if cf_supported:  # custom_fields is not an opt-in field, it should always be present if supported
            self.assertIn("custom_fields", response.data)
            self.assertIsInstance(response.data["custom_fields"], dict)

        relationships_registry = registry["model_features"]["relationships"]
        rel_supported = self.model._meta.model_name in relationships_registry.get(self.model._meta.app_label, {})
        if cf_supported or rel_supported:
            query_params = []
            if cf_supported:
                query_params.append("include=computed_fields")
            if rel_supported:
                query_params.append("include=relationships")
            query_string = "&".join(query_params)
            url = f"{url}?{query_string}"

            response = self.client.get(url, **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertIsInstance(response.data, dict)
            if cf_supported:
                self.assertIn("computed_fields", response.data)
                self.assertIsInstance(response.data["computed_fields"], dict)
            else:
                self.assertNotIn("computed_fields", response.data)
            if rel_supported:
                self.assertIn("relationships", response.data)
                self.assertIsInstance(response.data["relationships"], dict)
            else:
                self.assertNotIn("relationships", response.data)

    @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
    def test_options_object(self):
        """
        Make an OPTIONS request for a single object.
        """
        url = self._get_detail_url(self._get_queryset().first())
        response = self.client.options(url, **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)

test_get_object()

GET a single object as an authenticated user with permission to view the object.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[])
def test_get_object(self):
    """
    GET a single object as an authenticated user with permission to view the object.
    """
    self.assertGreaterEqual(
        self._get_queryset().count(),
        2,
        f"Test requires the creation of at least two {self.model} instances",
    )
    instance1, instance2 = self._get_queryset()[:2]

    # Add object-level permission
    obj_perm = ObjectPermission(
        name="Test permission",
        constraints={"pk": instance1.pk},
        actions=["view"],
    )
    obj_perm.save()
    obj_perm.users.add(self.user)
    obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

    # Try GET to non-permitted object
    url = self._get_detail_url(instance2)
    self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_404_NOT_FOUND)

    # Try GET to permitted object
    url = self._get_detail_url(instance1)
    response = self.client.get(url, **self.header)
    self.assertHttpStatus(response, status.HTTP_200_OK)
    self.assertIsInstance(response.data, dict)
    # Fields that should be present in *ALL* model serializers:
    self.assertIn("id", response.data)
    self.assertEqual(str(response.data["id"]), str(instance1.pk))  # coerce to str to handle both int and uuid
    self.assertIn("url", response.data)
    self.assertIn("display", response.data)
    self.assertIsInstance(response.data["display"], str)
    # Fields that should be present in appropriate model serializers:
    if issubclass(self.model, ChangeLoggedModel):
        self.assertIn("created", response.data)
        self.assertIn("last_updated", response.data)
    # Fields that should be absent by default (opt-in fields):
    self.assertNotIn("computed_fields", response.data)
    self.assertNotIn("relationships", response.data)

    # If opt-in fields are supported on this model, make sure they can be opted into

    custom_fields_registry = registry["model_features"]["custom_fields"]
    # computed fields and custom fields use the same registry
    cf_supported = self.model._meta.model_name in custom_fields_registry.get(self.model._meta.app_label, {})
    if cf_supported:  # custom_fields is not an opt-in field, it should always be present if supported
        self.assertIn("custom_fields", response.data)
        self.assertIsInstance(response.data["custom_fields"], dict)

    relationships_registry = registry["model_features"]["relationships"]
    rel_supported = self.model._meta.model_name in relationships_registry.get(self.model._meta.app_label, {})
    if cf_supported or rel_supported:
        query_params = []
        if cf_supported:
            query_params.append("include=computed_fields")
        if rel_supported:
            query_params.append("include=relationships")
        query_string = "&".join(query_params)
        url = f"{url}?{query_string}"

        response = self.client.get(url, **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        self.assertIsInstance(response.data, dict)
        if cf_supported:
            self.assertIn("computed_fields", response.data)
            self.assertIsInstance(response.data["computed_fields"], dict)
        else:
            self.assertNotIn("computed_fields", response.data)
        if rel_supported:
            self.assertIn("relationships", response.data)
            self.assertIsInstance(response.data["relationships"], dict)
        else:
            self.assertNotIn("relationships", response.data)

test_get_object_anonymous()

GET a single object as an unauthenticated user.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
def test_get_object_anonymous(self):
    """
    GET a single object as an unauthenticated user.
    """
    url = self._get_detail_url(self._get_queryset().first())
    if (
        self.model._meta.app_label,
        self.model._meta.model_name,
    ) in settings.EXEMPT_EXCLUDE_MODELS:
        # Models listed in EXEMPT_EXCLUDE_MODELS should not be accessible to anonymous users
        with disable_warnings("django.request"):
            self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
    else:
        response = self.client.get(url, **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)

test_get_object_without_permission()

GET a single object as an authenticated user without the required permission.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[])
def test_get_object_without_permission(self):
    """
    GET a single object as an authenticated user without the required permission.
    """
    url = self._get_detail_url(self._get_queryset().first())

    # Try GET without permission
    with disable_warnings("django.request"):
        self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)

test_options_object()

Make an OPTIONS request for a single object.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
def test_options_object(self):
    """
    Make an OPTIONS request for a single object.
    """
    url = self._get_detail_url(self._get_queryset().first())
    response = self.client.options(url, **self.header)
    self.assertHttpStatus(response, status.HTTP_200_OK)

ListObjectsViewTestCase

Bases: APITestCase

Source code in nautobot/utilities/testing/api.py
class ListObjectsViewTestCase(APITestCase):
    brief_fields = []
    choices_fields = None
    filterset = None

    def get_filterset(self):
        return self.filterset or get_filterset_for_model(self.model)

    @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
    def test_list_objects_anonymous(self):
        """
        GET a list of objects as an unauthenticated user.
        """
        url = self._get_list_url()
        if (
            self.model._meta.app_label,
            self.model._meta.model_name,
        ) in settings.EXEMPT_EXCLUDE_MODELS:
            # Models listed in EXEMPT_EXCLUDE_MODELS should not be accessible to anonymous users
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
        else:
            # TODO(Glenn): if we're passing **self.header, we are *by definition* **NOT** anonymous!!
            response = self.client.get(url, **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertIsInstance(response.data, dict)
            self.assertIn("results", response.data)
            self.assertEqual(len(response.data["results"]), self._get_queryset().count())

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_list_objects_brief(self):
        """
        GET a list of objects using the "brief" parameter.
        """
        self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
        url = f"{self._get_list_url()}?brief=1"
        response = self.client.get(url, **self.header)

        self.assertHttpStatus(response, status.HTTP_200_OK)
        self.assertIsInstance(response.data, dict)
        self.assertIn("results", response.data)
        self.assertEqual(len(response.data["results"]), self._get_queryset().count())
        self.assertEqual(
            sorted(response.data["results"][0]),
            self.brief_fields,
            "In order to test the brief API parameter the brief fields need to be manually added to "
            "self.brief_fields. If this is already the case, perhaps the serializer is implemented incorrectly?",
        )

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_list_objects_without_permission(self):
        """
        GET a list of objects as an authenticated user without the required permission.
        """
        url = self._get_list_url()

        # Try GET without permission
        with disable_warnings("django.request"):
            self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_list_objects(self):
        """
        GET a list of objects as an authenticated user with permission to view the objects.
        """
        self.assertGreaterEqual(
            self._get_queryset().count(),
            3,
            f"Test requires the creation of at least three {self.model} instances",
        )
        instance1, instance2 = self._get_queryset()[:2]

        # Add object-level permission
        obj_perm = ObjectPermission(
            name="Test permission",
            constraints={"pk__in": [instance1.pk, instance2.pk]},
            actions=["view"],
        )
        obj_perm.save()
        obj_perm.users.add(self.user)
        obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

        # Try GET to permitted objects
        response = self.client.get(self._get_list_url(), **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        self.assertIsInstance(response.data, dict)
        self.assertIn("results", response.data)
        self.assertEqual(len(response.data["results"]), 2)

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_list_objects_filtered(self):
        """
        GET a list of objects filtered by ID.
        """
        self.assertGreaterEqual(
            self._get_queryset().count(),
            3,
            f"Test requires the creation of at least three {self.model} instances",
        )
        self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
        instance1, instance2 = self._get_queryset()[:2]
        response = self.client.get(f"{self._get_list_url()}?id={instance1.pk}&id={instance2.pk}", **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        self.assertIsInstance(response.data, dict)
        self.assertIn("results", response.data)
        self.assertEqual(len(response.data["results"]), 2)
        for entry in response.data["results"]:
            self.assertIn(str(entry["id"]), [str(instance1.pk), str(instance2.pk)])

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[], STRICT_FILTERING=True)
    def test_list_objects_unknown_filter_strict_filtering(self):
        """
        GET a list of objects with an unknown filter parameter and strict filtering, expect a 400 response.
        """
        self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
        with disable_warnings("django.request"):
            response = self.client.get(f"{self._get_list_url()}?ice_cream_flavor=rocky-road", **self.header)
        self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
        self.assertIsInstance(response.data, dict)
        self.assertIn("ice_cream_flavor", response.data)
        self.assertIsInstance(response.data["ice_cream_flavor"], list)
        self.assertEqual("Unknown filter field", str(response.data["ice_cream_flavor"][0]))

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[], STRICT_FILTERING=False)
    def test_list_objects_unknown_filter_no_strict_filtering(self):
        """
        GET a list of objects with an unknown filter parameter and no strict filtering, expect it to be ignored.
        """
        self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
        with self.assertLogs("nautobot.utilities.filters") as cm:
            response = self.client.get(f"{self._get_list_url()}?ice_cream_flavor=rocky-road", **self.header)
        self.assertEqual(
            cm.output,
            [
                f"WARNING:nautobot.utilities.filters:{self.get_filterset().__name__}: "
                'Unknown filter field "ice_cream_flavor"',
            ],
        )
        self.assertHttpStatus(response, status.HTTP_200_OK)
        self.assertIsInstance(response.data, dict)
        self.assertIn("results", response.data)
        self.assertEqual(len(response.data["results"]), self._get_queryset().count())

    @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
    def test_options_objects(self):
        """
        Make an OPTIONS request for a list endpoint.
        """
        response = self.client.options(self._get_list_url(), **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)

    @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
    def test_status_options_returns_expected_choices(self):
        # Set to self.choices_fields as empty set to compare classes that shouldn't have any choice fields on serializer.
        if not self.choices_fields:
            self.choices_fields = set()

        # Don't bother testing if there's no `status` field.
        if "status" not in self.choices_fields:
            self.skipTest("Object does not contain a `status` field.")

        # Save self.user as superuser to be able to view available choices on list views.
        self.user.is_superuser = True
        self.user.save()

        response = self.client.options(self._get_list_url(), **self.header)
        data = response.json()

        self.assertIn("actions", data)
        self.assertIn("POST", data["actions"])

        actions = data["actions"]["POST"]
        choices = actions["status"]["choices"]

        # Import Status here to avoid circular import issues w/ test utilities.
        from nautobot.extras.models import Status  # noqa

        # Assert that the expected Status objects matches what is emitted.
        statuses = Status.objects.get_for_model(self.model)
        expected = [{"value": v, "display": d} for (v, d) in statuses.values_list("slug", "name")]
        self.assertListEqual(choices, expected)

test_list_objects()

GET a list of objects as an authenticated user with permission to view the objects.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[])
def test_list_objects(self):
    """
    GET a list of objects as an authenticated user with permission to view the objects.
    """
    self.assertGreaterEqual(
        self._get_queryset().count(),
        3,
        f"Test requires the creation of at least three {self.model} instances",
    )
    instance1, instance2 = self._get_queryset()[:2]

    # Add object-level permission
    obj_perm = ObjectPermission(
        name="Test permission",
        constraints={"pk__in": [instance1.pk, instance2.pk]},
        actions=["view"],
    )
    obj_perm.save()
    obj_perm.users.add(self.user)
    obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

    # Try GET to permitted objects
    response = self.client.get(self._get_list_url(), **self.header)
    self.assertHttpStatus(response, status.HTTP_200_OK)
    self.assertIsInstance(response.data, dict)
    self.assertIn("results", response.data)
    self.assertEqual(len(response.data["results"]), 2)

test_list_objects_anonymous()

GET a list of objects as an unauthenticated user.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
def test_list_objects_anonymous(self):
    """
    GET a list of objects as an unauthenticated user.
    """
    url = self._get_list_url()
    if (
        self.model._meta.app_label,
        self.model._meta.model_name,
    ) in settings.EXEMPT_EXCLUDE_MODELS:
        # Models listed in EXEMPT_EXCLUDE_MODELS should not be accessible to anonymous users
        with disable_warnings("django.request"):
            self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)
    else:
        # TODO(Glenn): if we're passing **self.header, we are *by definition* **NOT** anonymous!!
        response = self.client.get(url, **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        self.assertIsInstance(response.data, dict)
        self.assertIn("results", response.data)
        self.assertEqual(len(response.data["results"]), self._get_queryset().count())

test_list_objects_brief()

GET a list of objects using the "brief" parameter.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[])
def test_list_objects_brief(self):
    """
    GET a list of objects using the "brief" parameter.
    """
    self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
    url = f"{self._get_list_url()}?brief=1"
    response = self.client.get(url, **self.header)

    self.assertHttpStatus(response, status.HTTP_200_OK)
    self.assertIsInstance(response.data, dict)
    self.assertIn("results", response.data)
    self.assertEqual(len(response.data["results"]), self._get_queryset().count())
    self.assertEqual(
        sorted(response.data["results"][0]),
        self.brief_fields,
        "In order to test the brief API parameter the brief fields need to be manually added to "
        "self.brief_fields. If this is already the case, perhaps the serializer is implemented incorrectly?",
    )

test_list_objects_filtered()

GET a list of objects filtered by ID.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[])
def test_list_objects_filtered(self):
    """
    GET a list of objects filtered by ID.
    """
    self.assertGreaterEqual(
        self._get_queryset().count(),
        3,
        f"Test requires the creation of at least three {self.model} instances",
    )
    self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
    instance1, instance2 = self._get_queryset()[:2]
    response = self.client.get(f"{self._get_list_url()}?id={instance1.pk}&id={instance2.pk}", **self.header)
    self.assertHttpStatus(response, status.HTTP_200_OK)
    self.assertIsInstance(response.data, dict)
    self.assertIn("results", response.data)
    self.assertEqual(len(response.data["results"]), 2)
    for entry in response.data["results"]:
        self.assertIn(str(entry["id"]), [str(instance1.pk), str(instance2.pk)])

test_list_objects_unknown_filter_no_strict_filtering()

GET a list of objects with an unknown filter parameter and no strict filtering, expect it to be ignored.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[], STRICT_FILTERING=False)
def test_list_objects_unknown_filter_no_strict_filtering(self):
    """
    GET a list of objects with an unknown filter parameter and no strict filtering, expect it to be ignored.
    """
    self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
    with self.assertLogs("nautobot.utilities.filters") as cm:
        response = self.client.get(f"{self._get_list_url()}?ice_cream_flavor=rocky-road", **self.header)
    self.assertEqual(
        cm.output,
        [
            f"WARNING:nautobot.utilities.filters:{self.get_filterset().__name__}: "
            'Unknown filter field "ice_cream_flavor"',
        ],
    )
    self.assertHttpStatus(response, status.HTTP_200_OK)
    self.assertIsInstance(response.data, dict)
    self.assertIn("results", response.data)
    self.assertEqual(len(response.data["results"]), self._get_queryset().count())

test_list_objects_unknown_filter_strict_filtering()

GET a list of objects with an unknown filter parameter and strict filtering, expect a 400 response.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[], STRICT_FILTERING=True)
def test_list_objects_unknown_filter_strict_filtering(self):
    """
    GET a list of objects with an unknown filter parameter and strict filtering, expect a 400 response.
    """
    self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
    with disable_warnings("django.request"):
        response = self.client.get(f"{self._get_list_url()}?ice_cream_flavor=rocky-road", **self.header)
    self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
    self.assertIsInstance(response.data, dict)
    self.assertIn("ice_cream_flavor", response.data)
    self.assertIsInstance(response.data["ice_cream_flavor"], list)
    self.assertEqual("Unknown filter field", str(response.data["ice_cream_flavor"][0]))

test_list_objects_without_permission()

GET a list of objects as an authenticated user without the required permission.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[])
def test_list_objects_without_permission(self):
    """
    GET a list of objects as an authenticated user without the required permission.
    """
    url = self._get_list_url()

    # Try GET without permission
    with disable_warnings("django.request"):
        self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_403_FORBIDDEN)

test_options_objects()

Make an OPTIONS request for a list endpoint.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
def test_options_objects(self):
    """
    Make an OPTIONS request for a list endpoint.
    """
    response = self.client.options(self._get_list_url(), **self.header)
    self.assertHttpStatus(response, status.HTTP_200_OK)

NotesURLViewTestCase

Bases: APITestCase

Validate Notes URL on objects that have the Note model Mixin.

Source code in nautobot/utilities/testing/api.py
class NotesURLViewTestCase(APITestCase):
    """Validate Notes URL on objects that have the Note model Mixin."""

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_notes_url_on_object(self):
        if hasattr(self.model, "notes"):
            instance1 = self._get_queryset().first()
            # Add object-level permission
            obj_perm = ObjectPermission(
                name="Test permission",
                constraints={"pk": instance1.pk},
                actions=["view"],
            )
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
            url = self._get_detail_url(instance1)
            response = self.client.get(url, **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertIn("notes_url", response.data)
            self.assertIn(f"{url}notes/", str(response.data["notes_url"]))

UpdateObjectViewTestCase

Bases: APITestCase

Source code in nautobot/utilities/testing/api.py
class UpdateObjectViewTestCase(APITestCase):
    update_data = {}
    bulk_update_data: Optional[dict] = None
    validation_excluded_fields = []
    choices_fields = None

    def test_update_object_without_permission(self):
        """
        PATCH a single object without permission.
        """
        url = self._get_detail_url(self._get_queryset().first())
        update_data = self.update_data or getattr(self, "create_data")[0]

        # Try PATCH without permission
        with disable_warnings("django.request"):
            response = self.client.patch(url, update_data, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

    def test_update_object(self):
        """
        PATCH a single object identified by its ID.
        """
        instance = self._get_queryset().first()
        url = self._get_detail_url(instance)
        update_data = self.update_data or getattr(self, "create_data")[0]

        # Add object-level permission
        obj_perm = ObjectPermission(name="Test permission", actions=["change"])
        obj_perm.save()
        obj_perm.users.add(self.user)
        obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

        response = self.client.patch(url, update_data, format="json", **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        instance.refresh_from_db()
        self.assertInstanceEqual(instance, update_data, exclude=self.validation_excluded_fields, api=True)

        # Verify ObjectChange creation
        if hasattr(self.model, "to_objectchange"):
            objectchanges = get_changes_for_model(instance)
            self.assertEqual(len(objectchanges), 1)
            self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_UPDATE)

    def test_bulk_update_objects(self):
        """
        PATCH a set of objects in a single request.
        """
        if self.bulk_update_data is None:
            self.skipTest("Bulk update data not set")

        # Add object-level permission
        obj_perm = ObjectPermission(name="Test permission", actions=["change"])
        obj_perm.save()
        obj_perm.users.add(self.user)
        obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

        id_list = list(self._get_queryset().values_list("id", flat=True)[:3])
        self.assertEqual(len(id_list), 3, "Insufficient number of objects to test bulk update")
        data = [{"id": id, **self.bulk_update_data} for id in id_list]

        response = self.client.patch(self._get_list_url(), data, format="json", **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        for i, obj in enumerate(response.data):
            for field, _value in self.bulk_update_data.items():
                self.assertIn(
                    field,
                    obj,
                    f"Bulk update field '{field}' missing from object {i} in response",
                )
                # TODO(Glenn): shouldn't we also check that obj[field] == value?
        for instance in self._get_queryset().filter(pk__in=id_list):
            self.assertInstanceEqual(
                instance,
                self.bulk_update_data,
                exclude=self.validation_excluded_fields,
                api=True,
            )

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_options_objects_returns_display_and_value(self):
        """
        Make an OPTIONS request for a list endpoint and validate choices use the display and value keys.
        """
        # Save self.user as superuser to be able to view available choices on list views.
        self.user.is_superuser = True
        self.user.save()

        response = self.client.options(self._get_list_url(), **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        data = response.json()

        self.assertIn("actions", data)

        # Grab any field that has choices defined (fields with enums)
        if "POST" in data["actions"]:
            field_choices = {k: v["choices"] for k, v in data["actions"]["POST"].items() if "choices" in v}
        elif "PUT" in data["actions"]:  # JobModelViewSet supports editing but not creation
            field_choices = {k: v["choices"] for k, v in data["actions"]["PUT"].items() if "choices" in v}
        else:
            self.fail(f"Neither PUT nor POST are available actions in: {data['actions']}")

        # Will successfully assert if field_choices has entries and will not fail if model as no enum choices
        # Broken down to provide better failure messages
        for field, choices in field_choices.items():
            for choice in choices:
                self.assertIn("display", choice, f"A choice in {field} is missing the display key")
                self.assertIn("value", choice, f"A choice in {field} is missing the value key")

    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_options_returns_expected_choices(self):
        """
        Make an OPTIONS request for a list endpoint and validate choices match expected choices for serializer.
        """
        # Set self.choices_fields as empty set to compare classes that shouldn't have any choices on serializer.
        if not self.choices_fields:
            self.choices_fields = set()

        # Save self.user as superuser to be able to view available choices on list views.
        self.user.is_superuser = True
        self.user.save()

        response = self.client.options(self._get_list_url(), **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        data = response.json()

        self.assertIn("actions", data)

        # Grab any field name that has choices defined (fields with enums)
        if "POST" in data["actions"]:
            field_choices = {k for k, v in data["actions"]["POST"].items() if "choices" in v}
        elif "PUT" in data["actions"]:  # JobModelViewSet supports editing but not creation
            field_choices = {k for k, v in data["actions"]["PUT"].items() if "choices" in v}
        else:
            self.fail(f"Neither PUT nor POST are available actions in: {data['actions']}")

        self.assertEqual(
            set(self.choices_fields),
            field_choices,
            "All field names of choice fields for a given model serializer need to be manually added to "
            "self.choices_fields. If this is already the case, perhaps the serializer is implemented incorrectly?",
        )

test_bulk_update_objects()

PATCH a set of objects in a single request.

Source code in nautobot/utilities/testing/api.py
def test_bulk_update_objects(self):
    """
    PATCH a set of objects in a single request.
    """
    if self.bulk_update_data is None:
        self.skipTest("Bulk update data not set")

    # Add object-level permission
    obj_perm = ObjectPermission(name="Test permission", actions=["change"])
    obj_perm.save()
    obj_perm.users.add(self.user)
    obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

    id_list = list(self._get_queryset().values_list("id", flat=True)[:3])
    self.assertEqual(len(id_list), 3, "Insufficient number of objects to test bulk update")
    data = [{"id": id, **self.bulk_update_data} for id in id_list]

    response = self.client.patch(self._get_list_url(), data, format="json", **self.header)
    self.assertHttpStatus(response, status.HTTP_200_OK)
    for i, obj in enumerate(response.data):
        for field, _value in self.bulk_update_data.items():
            self.assertIn(
                field,
                obj,
                f"Bulk update field '{field}' missing from object {i} in response",
            )
            # TODO(Glenn): shouldn't we also check that obj[field] == value?
    for instance in self._get_queryset().filter(pk__in=id_list):
        self.assertInstanceEqual(
            instance,
            self.bulk_update_data,
            exclude=self.validation_excluded_fields,
            api=True,
        )

test_options_objects_returns_display_and_value()

Make an OPTIONS request for a list endpoint and validate choices use the display and value keys.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[])
def test_options_objects_returns_display_and_value(self):
    """
    Make an OPTIONS request for a list endpoint and validate choices use the display and value keys.
    """
    # Save self.user as superuser to be able to view available choices on list views.
    self.user.is_superuser = True
    self.user.save()

    response = self.client.options(self._get_list_url(), **self.header)
    self.assertHttpStatus(response, status.HTTP_200_OK)
    data = response.json()

    self.assertIn("actions", data)

    # Grab any field that has choices defined (fields with enums)
    if "POST" in data["actions"]:
        field_choices = {k: v["choices"] for k, v in data["actions"]["POST"].items() if "choices" in v}
    elif "PUT" in data["actions"]:  # JobModelViewSet supports editing but not creation
        field_choices = {k: v["choices"] for k, v in data["actions"]["PUT"].items() if "choices" in v}
    else:
        self.fail(f"Neither PUT nor POST are available actions in: {data['actions']}")

    # Will successfully assert if field_choices has entries and will not fail if model as no enum choices
    # Broken down to provide better failure messages
    for field, choices in field_choices.items():
        for choice in choices:
            self.assertIn("display", choice, f"A choice in {field} is missing the display key")
            self.assertIn("value", choice, f"A choice in {field} is missing the value key")

test_options_returns_expected_choices()

Make an OPTIONS request for a list endpoint and validate choices match expected choices for serializer.

Source code in nautobot/utilities/testing/api.py
@override_settings(EXEMPT_VIEW_PERMISSIONS=[])
def test_options_returns_expected_choices(self):
    """
    Make an OPTIONS request for a list endpoint and validate choices match expected choices for serializer.
    """
    # Set self.choices_fields as empty set to compare classes that shouldn't have any choices on serializer.
    if not self.choices_fields:
        self.choices_fields = set()

    # Save self.user as superuser to be able to view available choices on list views.
    self.user.is_superuser = True
    self.user.save()

    response = self.client.options(self._get_list_url(), **self.header)
    self.assertHttpStatus(response, status.HTTP_200_OK)
    data = response.json()

    self.assertIn("actions", data)

    # Grab any field name that has choices defined (fields with enums)
    if "POST" in data["actions"]:
        field_choices = {k for k, v in data["actions"]["POST"].items() if "choices" in v}
    elif "PUT" in data["actions"]:  # JobModelViewSet supports editing but not creation
        field_choices = {k for k, v in data["actions"]["PUT"].items() if "choices" in v}
    else:
        self.fail(f"Neither PUT nor POST are available actions in: {data['actions']}")

    self.assertEqual(
        set(self.choices_fields),
        field_choices,
        "All field names of choice fields for a given model serializer need to be manually added to "
        "self.choices_fields. If this is already the case, perhaps the serializer is implemented incorrectly?",
    )

test_update_object()

PATCH a single object identified by its ID.

Source code in nautobot/utilities/testing/api.py
def test_update_object(self):
    """
    PATCH a single object identified by its ID.
    """
    instance = self._get_queryset().first()
    url = self._get_detail_url(instance)
    update_data = self.update_data or getattr(self, "create_data")[0]

    # Add object-level permission
    obj_perm = ObjectPermission(name="Test permission", actions=["change"])
    obj_perm.save()
    obj_perm.users.add(self.user)
    obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

    response = self.client.patch(url, update_data, format="json", **self.header)
    self.assertHttpStatus(response, status.HTTP_200_OK)
    instance.refresh_from_db()
    self.assertInstanceEqual(instance, update_data, exclude=self.validation_excluded_fields, api=True)

    # Verify ObjectChange creation
    if hasattr(self.model, "to_objectchange"):
        objectchanges = get_changes_for_model(instance)
        self.assertEqual(len(objectchanges), 1)
        self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_UPDATE)

test_update_object_without_permission()

PATCH a single object without permission.

Source code in nautobot/utilities/testing/api.py
def test_update_object_without_permission(self):
    """
    PATCH a single object without permission.
    """
    url = self._get_detail_url(self._get_queryset().first())
    update_data = self.update_data or getattr(self, "create_data")[0]

    # Try PATCH without permission
    with disable_warnings("django.request"):
        response = self.client.patch(url, update_data, format="json", **self.header)
        self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

nautobot.apps.testing.FilterTestCases

Source code in nautobot/utilities/testing/filters.py
@tag("unit")
class FilterTestCases:
    class BaseFilterTestCase(TestCase):
        """Base class for testing of FilterSets."""

        def get_filterset_test_values(self, field_name, queryset=None):
            """Returns a list of distinct values from the requested queryset field to use in filterset tests.

            Returns a list for use in testing multiple choice filters. The size of the returned list is random
            but will contain at minimum 2 unique values. The list of values will match at least 2 instances when
            passed to the queryset's filter(field_name__in=[]) method but will fail to match at least one instance.

            Args:
                field_name (str): The name of the field to retrieve test values from.
                queryset (QuerySet): The queryset to retrieve test values. Defaults to `self.queryset`.

            Returns:
                (list): A list of unique values derived from the queryset.

            Raises:
                ValueError: Raised if unable to find a combination of 2 or more unique values
                    to filter the queryset to a subset of the total instances.
            """
            test_values = []
            if queryset is None:
                queryset = self.queryset
            qs_count = queryset.count()
            values_with_count = queryset.values(field_name).annotate(count=Count(field_name)).order_by("count")
            for value in values_with_count:
                # randomly break out of loop after 2 values have been selected
                if len(test_values) > 1 and random.choice([True, False]):
                    break
                if value["count"] < qs_count:
                    qs_count -= value["count"]
                    test_values.append(value[field_name])

            if len(test_values) < 2:
                raise ValueError(
                    f"Cannot find valid test data for {queryset.model._meta.object_name} field {field_name}"
                )
            return test_values

    class FilterTestCase(BaseFilterTestCase):
        """Add common tests for all FilterSets."""

        queryset = None
        filterset = None

        def test_id(self):
            """Verify that the filterset supports filtering by id."""
            params = {"id": self.queryset.values_list("pk", flat=True)[:2]}
            filterset = self.filterset(params, self.queryset)
            self.assertTrue(filterset.is_valid())
            self.assertEqual(filterset.qs.count(), 2)

        def test_invalid_filter(self):
            """Verify that the filterset reports as invalid when initialized with an unsupported filter parameter."""
            params = {"ice_cream_flavor": ["chocolate"]}
            self.assertFalse(self.filterset(params, self.queryset).is_valid())

    class NameSlugFilterTestCase(FilterTestCase):
        """Add simple tests for filtering by name and by slug."""

        def test_name(self):
            """Verify that the filterset supports filtering by name."""
            params = {"name": self.queryset.values_list("name", flat=True)[:2]}
            filterset = self.filterset(params, self.queryset)
            self.assertTrue(filterset.is_valid())
            self.assertEqual(filterset.qs.count(), 2)

        def test_slug(self):
            """Verify that the filterset supports filtering by slug."""
            params = {"slug": self.queryset.values_list("slug", flat=True)[:2]}
            filterset = self.filterset(params, self.queryset)
            self.assertTrue(filterset.is_valid())
            self.assertEqual(filterset.qs.count(), 2)

    class TenancyFilterTestCaseMixin(TestCase):
        """Add test cases for tenant and tenant-group filters."""

        tenancy_related_name = ""

        def test_tenant(self):
            tenants = list(Tenant.objects.filter(**{f"{self.tenancy_related_name}__isnull": False}))[:2]
            params = {"tenant_id": [tenants[0].pk, tenants[1].pk]}
            self.assertQuerysetEqual(
                self.filterset(params, self.queryset).qs, self.queryset.filter(tenant__in=tenants), ordered=False
            )
            params = {"tenant": [tenants[0].slug, tenants[1].slug]}
            self.assertQuerysetEqual(
                self.filterset(params, self.queryset).qs, self.queryset.filter(tenant__in=tenants), ordered=False
            )

        def test_tenant_group(self):
            tenant_groups = list(
                TenantGroup.objects.filter(
                    tenants__isnull=False, **{f"tenants__{self.tenancy_related_name}__isnull": False}
                )
            )[:2]
            tenant_groups_including_children = []
            for tenant_group in tenant_groups:
                tenant_groups_including_children += tenant_group.get_descendants(include_self=True)

            params = {"tenant_group_id": [tenant_groups[0].pk, tenant_groups[1].pk]}
            self.assertQuerysetEqual(
                self.filterset(params, self.queryset).qs,
                self.queryset.filter(tenant__group__in=tenant_groups_including_children),
                ordered=False,
            )

            params = {"tenant_group": [tenant_groups[0].slug, tenant_groups[1].slug]}
            self.assertQuerysetEqual(
                self.filterset(params, self.queryset).qs,
                self.queryset.filter(tenant__group__in=tenant_groups_including_children),
                ordered=False,
            )

BaseFilterTestCase

Bases: TestCase

Base class for testing of FilterSets.

Source code in nautobot/utilities/testing/filters.py
class BaseFilterTestCase(TestCase):
    """Base class for testing of FilterSets."""

    def get_filterset_test_values(self, field_name, queryset=None):
        """Returns a list of distinct values from the requested queryset field to use in filterset tests.

        Returns a list for use in testing multiple choice filters. The size of the returned list is random
        but will contain at minimum 2 unique values. The list of values will match at least 2 instances when
        passed to the queryset's filter(field_name__in=[]) method but will fail to match at least one instance.

        Args:
            field_name (str): The name of the field to retrieve test values from.
            queryset (QuerySet): The queryset to retrieve test values. Defaults to `self.queryset`.

        Returns:
            (list): A list of unique values derived from the queryset.

        Raises:
            ValueError: Raised if unable to find a combination of 2 or more unique values
                to filter the queryset to a subset of the total instances.
        """
        test_values = []
        if queryset is None:
            queryset = self.queryset
        qs_count = queryset.count()
        values_with_count = queryset.values(field_name).annotate(count=Count(field_name)).order_by("count")
        for value in values_with_count:
            # randomly break out of loop after 2 values have been selected
            if len(test_values) > 1 and random.choice([True, False]):
                break
            if value["count"] < qs_count:
                qs_count -= value["count"]
                test_values.append(value[field_name])

        if len(test_values) < 2:
            raise ValueError(
                f"Cannot find valid test data for {queryset.model._meta.object_name} field {field_name}"
            )
        return test_values

get_filterset_test_values(field_name, queryset=None)

Returns a list of distinct values from the requested queryset field to use in filterset tests.

Returns a list for use in testing multiple choice filters. The size of the returned list is random but will contain at minimum 2 unique values. The list of values will match at least 2 instances when passed to the queryset's filter(field_name__in=[]) method but will fail to match at least one instance.

Parameters:

Name Type Description Default
field_name str

The name of the field to retrieve test values from.

required
queryset QuerySet

The queryset to retrieve test values. Defaults to self.queryset.

None

Returns:

Type Description
list

A list of unique values derived from the queryset.

Raises:

Type Description
ValueError

Raised if unable to find a combination of 2 or more unique values to filter the queryset to a subset of the total instances.

Source code in nautobot/utilities/testing/filters.py
def get_filterset_test_values(self, field_name, queryset=None):
    """Returns a list of distinct values from the requested queryset field to use in filterset tests.

    Returns a list for use in testing multiple choice filters. The size of the returned list is random
    but will contain at minimum 2 unique values. The list of values will match at least 2 instances when
    passed to the queryset's filter(field_name__in=[]) method but will fail to match at least one instance.

    Args:
        field_name (str): The name of the field to retrieve test values from.
        queryset (QuerySet): The queryset to retrieve test values. Defaults to `self.queryset`.

    Returns:
        (list): A list of unique values derived from the queryset.

    Raises:
        ValueError: Raised if unable to find a combination of 2 or more unique values
            to filter the queryset to a subset of the total instances.
    """
    test_values = []
    if queryset is None:
        queryset = self.queryset
    qs_count = queryset.count()
    values_with_count = queryset.values(field_name).annotate(count=Count(field_name)).order_by("count")
    for value in values_with_count:
        # randomly break out of loop after 2 values have been selected
        if len(test_values) > 1 and random.choice([True, False]):
            break
        if value["count"] < qs_count:
            qs_count -= value["count"]
            test_values.append(value[field_name])

    if len(test_values) < 2:
        raise ValueError(
            f"Cannot find valid test data for {queryset.model._meta.object_name} field {field_name}"
        )
    return test_values

FilterTestCase

Bases: BaseFilterTestCase

Add common tests for all FilterSets.

Source code in nautobot/utilities/testing/filters.py
class FilterTestCase(BaseFilterTestCase):
    """Add common tests for all FilterSets."""

    queryset = None
    filterset = None

    def test_id(self):
        """Verify that the filterset supports filtering by id."""
        params = {"id": self.queryset.values_list("pk", flat=True)[:2]}
        filterset = self.filterset(params, self.queryset)
        self.assertTrue(filterset.is_valid())
        self.assertEqual(filterset.qs.count(), 2)

    def test_invalid_filter(self):
        """Verify that the filterset reports as invalid when initialized with an unsupported filter parameter."""
        params = {"ice_cream_flavor": ["chocolate"]}
        self.assertFalse(self.filterset(params, self.queryset).is_valid())

test_id()

Verify that the filterset supports filtering by id.

Source code in nautobot/utilities/testing/filters.py
def test_id(self):
    """Verify that the filterset supports filtering by id."""
    params = {"id": self.queryset.values_list("pk", flat=True)[:2]}
    filterset = self.filterset(params, self.queryset)
    self.assertTrue(filterset.is_valid())
    self.assertEqual(filterset.qs.count(), 2)

test_invalid_filter()

Verify that the filterset reports as invalid when initialized with an unsupported filter parameter.

Source code in nautobot/utilities/testing/filters.py
def test_invalid_filter(self):
    """Verify that the filterset reports as invalid when initialized with an unsupported filter parameter."""
    params = {"ice_cream_flavor": ["chocolate"]}
    self.assertFalse(self.filterset(params, self.queryset).is_valid())

NameSlugFilterTestCase

Bases: FilterTestCase

Add simple tests for filtering by name and by slug.

Source code in nautobot/utilities/testing/filters.py
class NameSlugFilterTestCase(FilterTestCase):
    """Add simple tests for filtering by name and by slug."""

    def test_name(self):
        """Verify that the filterset supports filtering by name."""
        params = {"name": self.queryset.values_list("name", flat=True)[:2]}
        filterset = self.filterset(params, self.queryset)
        self.assertTrue(filterset.is_valid())
        self.assertEqual(filterset.qs.count(), 2)

    def test_slug(self):
        """Verify that the filterset supports filtering by slug."""
        params = {"slug": self.queryset.values_list("slug", flat=True)[:2]}
        filterset = self.filterset(params, self.queryset)
        self.assertTrue(filterset.is_valid())
        self.assertEqual(filterset.qs.count(), 2)

test_name()

Verify that the filterset supports filtering by name.

Source code in nautobot/utilities/testing/filters.py
def test_name(self):
    """Verify that the filterset supports filtering by name."""
    params = {"name": self.queryset.values_list("name", flat=True)[:2]}
    filterset = self.filterset(params, self.queryset)
    self.assertTrue(filterset.is_valid())
    self.assertEqual(filterset.qs.count(), 2)

test_slug()

Verify that the filterset supports filtering by slug.

Source code in nautobot/utilities/testing/filters.py
def test_slug(self):
    """Verify that the filterset supports filtering by slug."""
    params = {"slug": self.queryset.values_list("slug", flat=True)[:2]}
    filterset = self.filterset(params, self.queryset)
    self.assertTrue(filterset.is_valid())
    self.assertEqual(filterset.qs.count(), 2)

TenancyFilterTestCaseMixin

Bases: TestCase

Add test cases for tenant and tenant-group filters.

Source code in nautobot/utilities/testing/filters.py
class TenancyFilterTestCaseMixin(TestCase):
    """Add test cases for tenant and tenant-group filters."""

    tenancy_related_name = ""

    def test_tenant(self):
        tenants = list(Tenant.objects.filter(**{f"{self.tenancy_related_name}__isnull": False}))[:2]
        params = {"tenant_id": [tenants[0].pk, tenants[1].pk]}
        self.assertQuerysetEqual(
            self.filterset(params, self.queryset).qs, self.queryset.filter(tenant__in=tenants), ordered=False
        )
        params = {"tenant": [tenants[0].slug, tenants[1].slug]}
        self.assertQuerysetEqual(
            self.filterset(params, self.queryset).qs, self.queryset.filter(tenant__in=tenants), ordered=False
        )

    def test_tenant_group(self):
        tenant_groups = list(
            TenantGroup.objects.filter(
                tenants__isnull=False, **{f"tenants__{self.tenancy_related_name}__isnull": False}
            )
        )[:2]
        tenant_groups_including_children = []
        for tenant_group in tenant_groups:
            tenant_groups_including_children += tenant_group.get_descendants(include_self=True)

        params = {"tenant_group_id": [tenant_groups[0].pk, tenant_groups[1].pk]}
        self.assertQuerysetEqual(
            self.filterset(params, self.queryset).qs,
            self.queryset.filter(tenant__group__in=tenant_groups_including_children),
            ordered=False,
        )

        params = {"tenant_group": [tenant_groups[0].slug, tenant_groups[1].slug]}
        self.assertQuerysetEqual(
            self.filterset(params, self.queryset).qs,
            self.queryset.filter(tenant__group__in=tenant_groups_including_children),
            ordered=False,
        )

nautobot.apps.testing.ViewTestCases

We keep any TestCases with test_* methods inside a class to prevent unittest from trying to run them.

Source code in nautobot/utilities/testing/views.py
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
@tag("unit")
class ViewTestCases:
    """
    We keep any TestCases with test_* methods inside a class to prevent unittest from trying to run them.
    """

    class GetObjectViewTestCase(ModelViewTestCase):
        """
        Retrieve a single instance.
        """

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_get_object_anonymous(self):
            # Make the request as an unauthenticated user
            self.client.logout()
            response = self.client.get(self._get_queryset().first().get_absolute_url())
            self.assertHttpStatus(response, 200)
            response_body = response.content.decode(response.charset)
            self.assertIn(
                "/login/?next=" + self._get_queryset().first().get_absolute_url(), response_body, msg=response_body
            )

            # The "Change Log" tab should appear in the response since we have all exempt permissions
            if issubclass(self.model, ChangeLoggedModel):
                response_body = extract_page_body(response.content.decode(response.charset))
                self.assertIn("Change Log", response_body, msg=response_body)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_get_object_without_permission(self):
            instance = self._get_queryset().first()

            # Try GET without permission
            with disable_warnings("django.request"):
                response = self.client.get(instance.get_absolute_url())
                self.assertHttpStatus(response, [403, 404])
                response_body = response.content.decode(response.charset)
                self.assertNotIn("/login/", response_body, msg=response_body)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_get_object_with_permission(self):
            instance = self._get_queryset().first()

            # Add model-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["view"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET with model-level permission
            response = self.client.get(instance.get_absolute_url())
            self.assertHttpStatus(response, 200)

            response_body = extract_page_body(response.content.decode(response.charset))

            # The object's display name or string representation should appear in the response
            self.assertIn(getattr(instance, "display", str(instance)), response_body, msg=response_body)

            # If any Relationships are defined, they should appear in the response
            if self.relationships is not None:
                for relationship in self.relationships:  # false positive pylint: disable=not-an-iterable
                    content_type = ContentType.objects.get_for_model(instance)
                    if content_type == relationship.source_type:
                        self.assertIn(
                            relationship.get_label(RelationshipSideChoices.SIDE_SOURCE),
                            response_body,
                            msg=response_body,
                        )
                    if content_type == relationship.destination_type:
                        self.assertIn(
                            relationship.get_label(RelationshipSideChoices.SIDE_DESTINATION),
                            response_body,
                            msg=response_body,
                        )

            # If any Custom Fields are defined, they should appear in the response
            if self.custom_fields is not None:
                for custom_field in self.custom_fields:  # false positive pylint: disable=not-an-iterable
                    self.assertIn(str(custom_field), response_body, msg=response_body)
                    # 2.0 TODO: #824 custom_field.slug rather than custom_field.name
                    if custom_field.type == CustomFieldTypeChoices.TYPE_MULTISELECT:
                        for value in instance.cf.get(custom_field.name):
                            self.assertIn(str(value), response_body, msg=response_body)
                    else:
                        self.assertIn(str(instance.cf.get(custom_field.name) or ""), response_body, msg=response_body)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_get_object_with_constrained_permission(self):
            instance1, instance2 = self._get_queryset().all()[:2]

            # Add object-level permission
            obj_perm = ObjectPermission(
                name="Test permission",
                constraints={"pk": instance1.pk},
                # To get a different rendering flow than the `test_get_object_with_permission` test above,
                # enable additional permissions for this object so that add/edit/delete buttons are rendered.
                actions=["view", "add", "change", "delete"],
            )
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET to permitted object
            self.assertHttpStatus(self.client.get(instance1.get_absolute_url()), 200)

            # Try GET to non-permitted object
            self.assertHttpStatus(self.client.get(instance2.get_absolute_url()), 404)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_has_advanced_tab(self):
            instance = self._get_queryset().first()

            # Add model-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["view"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            response = self.client.get(instance.get_absolute_url())
            response_body = extract_page_body(response.content.decode(response.charset))
            advanced_tab_href = f"{instance.get_absolute_url()}#advanced"

            self.assertIn(advanced_tab_href, response_body)
            self.assertIn("Advanced", response_body)

    class GetObjectChangelogViewTestCase(ModelViewTestCase):
        """
        View the changelog for an instance.
        """

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_get_object_changelog(self):
            url = self._get_url("changelog", self._get_queryset().first())
            response = self.client.get(url)
            self.assertHttpStatus(response, 200)

    class GetObjectNotesViewTestCase(ModelViewTestCase):
        """
        View the notes for an instance.
        """

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_get_object_notes(self):
            if hasattr(self.model, "notes"):
                url = self._get_url("notes", self._get_queryset().first())
                response = self.client.get(url)
                self.assertHttpStatus(response, 200)

    class CreateObjectViewTestCase(ModelViewTestCase):
        """
        Create a single new instance.

        :form_data: Data to be used when creating a new object.
        """

        form_data = {}
        slug_source = None
        slugify_function = staticmethod(slugify)
        slug_test_object = ""

        def test_create_object_without_permission(self):

            # Try GET without permission
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.get(self._get_url("add")), 403)

            # Try POST without permission
            request = {
                "path": self._get_url("add"),
                "data": post_data(self.form_data),
            }
            response = self.client.post(**request)
            with disable_warnings("django.request"):
                self.assertHttpStatus(response, 403)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_create_object_with_permission(self):
            initial_count = self._get_queryset().count()

            # Assign unconstrained permission
            obj_perm = ObjectPermission(name="Test permission", actions=["add"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET with model-level permission
            self.assertHttpStatus(self.client.get(self._get_url("add")), 200)

            # Try POST with model-level permission
            request = {
                "path": self._get_url("add"),
                "data": post_data(self.form_data),
            }
            self.assertHttpStatus(self.client.post(**request), 302)
            self.assertEqual(initial_count + 1, self._get_queryset().count())
            # order_by() is no supported by django TreeNode,
            # So we directly retrieve the instance by "slug".
            if isinstance(self._get_queryset().first(), TreeNode):
                instance = self._get_queryset().get(slug=self.form_data.get("slug"))
                self.assertInstanceEqual(instance, self.form_data)
            else:
                if hasattr(self.model, "last_updated"):
                    instance = self._get_queryset().order_by("last_updated").last()
                    self.assertInstanceEqual(instance, self.form_data)
                else:
                    instance = self._get_queryset().last()
                    self.assertInstanceEqual(instance, self.form_data)

            if hasattr(self.model, "to_objectchange"):
                # Verify ObjectChange creation
                objectchanges = get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_CREATE)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_create_object_with_constrained_permission(self):
            initial_count = self._get_queryset().count()

            # Assign constrained permission
            obj_perm = ObjectPermission(
                name="Test permission",
                constraints={"pk": str(uuid.uuid4())},  # Match a non-existent pk (i.e., deny all)
                actions=["add"],
            )
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET with object-level permission
            self.assertHttpStatus(self.client.get(self._get_url("add")), 200)

            # Try to create an object (not permitted)
            request = {
                "path": self._get_url("add"),
                "data": post_data(self.form_data),
            }
            self.assertHttpStatus(self.client.post(**request), 200)
            self.assertEqual(initial_count, self._get_queryset().count())  # Check that no object was created

            # Update the ObjectPermission to allow creation
            obj_perm.constraints = {"pk__isnull": False}
            obj_perm.save()

            # Try to create an object (permitted)
            request = {
                "path": self._get_url("add"),
                "data": post_data(self.form_data),
            }
            self.assertHttpStatus(self.client.post(**request), 302)
            self.assertEqual(initial_count + 1, self._get_queryset().count())
            # order_by() is no supported by django TreeNode,
            # So we directly retrieve the instance by "slug".
            if isinstance(self._get_queryset().first(), TreeNode):
                instance = self._get_queryset().get(slug=self.form_data.get("slug"))
                self.assertInstanceEqual(instance, self.form_data)
            else:
                if hasattr(self.model, "last_updated"):
                    self.assertInstanceEqual(self._get_queryset().order_by("last_updated").last(), self.form_data)
                else:
                    self.assertInstanceEqual(self._get_queryset().last(), self.form_data)

        def test_slug_autocreation(self):
            """Test that slug is autocreated through ORM."""
            # This really should go on a models test page, but we don't have test structures for models.
            if self.slug_source is not None:
                obj = self.model.objects.get(**{self.slug_source: self.slug_test_object})
                expected_slug = self.slugify_function(getattr(obj, self.slug_source))
                self.assertEqual(obj.slug, expected_slug)

        def test_slug_not_modified(self):
            """Ensure save method does not modify slug that is passed in."""
            # This really should go on a models test page, but we don't have test structures for models.
            if self.slug_source is not None:
                new_slug_source_value = "kwyjibo"

                obj = self.model.objects.get(**{self.slug_source: self.slug_test_object})
                expected_slug = self.slugify_function(getattr(obj, self.slug_source))
                # Update slug source field str
                filter_ = self.slug_source + "__exact"
                self.model.objects.filter(**{filter_: self.slug_test_object}).update(
                    **{self.slug_source: new_slug_source_value}
                )

                obj.refresh_from_db()
                self.assertEqual(getattr(obj, self.slug_source), new_slug_source_value)
                self.assertEqual(obj.slug, expected_slug)

    class EditObjectViewTestCase(ModelViewTestCase):
        """
        Edit a single existing instance.

        :form_data: Data to be used when updating the first existing object.
        """

        form_data = {}

        def test_edit_object_without_permission(self):
            instance = self._get_queryset().first()

            # Try GET without permission
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.get(self._get_url("edit", instance)), [403, 404])

            # Try POST without permission
            request = {
                "path": self._get_url("edit", instance),
                "data": post_data(self.form_data),
            }
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.post(**request), [403, 404])

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_edit_object_with_permission(self):
            instance = self._get_queryset().first()

            # Assign model-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["change"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET with model-level permission
            self.assertHttpStatus(self.client.get(self._get_url("edit", instance)), 200)

            # Try POST with model-level permission
            request = {
                "path": self._get_url("edit", instance),
                "data": post_data(self.form_data),
            }
            self.assertHttpStatus(self.client.post(**request), 302)
            self.assertInstanceEqual(self._get_queryset().get(pk=instance.pk), self.form_data)

            if hasattr(self.model, "to_objectchange"):
                # Verify ObjectChange creation
                objectchanges = get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_UPDATE)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_edit_object_with_constrained_permission(self):
            instance1, instance2 = self._get_queryset().all()[:2]

            # Assign constrained permission
            obj_perm = ObjectPermission(
                name="Test permission",
                constraints={"pk": instance1.pk},
                actions=["change"],
            )
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET with a permitted object
            self.assertHttpStatus(self.client.get(self._get_url("edit", instance1)), 200)

            # Try GET with a non-permitted object
            self.assertHttpStatus(self.client.get(self._get_url("edit", instance2)), 404)

            # Try to edit a permitted object
            request = {
                "path": self._get_url("edit", instance1),
                "data": post_data(self.form_data),
            }
            self.assertHttpStatus(self.client.post(**request), 302)
            self.assertInstanceEqual(self._get_queryset().get(pk=instance1.pk), self.form_data)

            # Try to edit a non-permitted object
            request = {
                "path": self._get_url("edit", instance2),
                "data": post_data(self.form_data),
            }
            self.assertHttpStatus(self.client.post(**request), 404)

    class DeleteObjectViewTestCase(ModelViewTestCase):
        """
        Delete a single instance.
        """

        def get_deletable_object(self):
            """
            Get an instance that can be deleted.

            For some models this may just be any random object, but when we have FKs with `on_delete=models.PROTECT`
            (as is often the case) we need to find or create an instance that doesn't have such entanglements.
            """
            instance = get_deletable_objects(self.model, self._get_queryset()).first()
            if instance is None:
                self.fail("Couldn't find a single deletable object!")
            return instance

        def test_delete_object_without_permission(self):
            instance = self.get_deletable_object()

            # Try GET without permission
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.get(self._get_url("delete", instance)), [403, 404])

            # Try POST without permission
            request = {
                "path": self._get_url("delete", instance),
                "data": post_data({"confirm": True}),
            }
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.post(**request), [403, 404])

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_delete_object_with_permission(self):
            instance = self.get_deletable_object()

            # Assign model-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["delete"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET with model-level permission
            self.assertHttpStatus(self.client.get(self._get_url("delete", instance)), 200)

            # Try POST with model-level permission
            request = {
                "path": self._get_url("delete", instance),
                "data": post_data({"confirm": True}),
            }
            self.assertHttpStatus(self.client.post(**request), 302)
            with self.assertRaises(ObjectDoesNotExist):
                self._get_queryset().get(pk=instance.pk)

            if hasattr(self.model, "to_objectchange"):
                # Verify ObjectChange creation
                objectchanges = get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_DELETE)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_delete_object_with_permission_and_xwwwformurlencoded(self):
            instance = self.get_deletable_object()

            # Assign model-level permission
            obj_perm = ObjectPermission(name="Test permission", actions=["delete"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET with model-level permission
            self.assertHttpStatus(self.client.get(self._get_url("delete", instance)), 200)

            # Try POST with model-level permission
            request = {
                "path": self._get_url("delete", instance),
                "data": urlencode({"confirm": True}),
                "content_type": "application/x-www-form-urlencoded",
            }
            self.assertHttpStatus(self.client.post(**request), 302)
            with self.assertRaises(ObjectDoesNotExist):
                self._get_queryset().get(pk=instance.pk)

            if hasattr(self.model, "to_objectchange"):
                # Verify ObjectChange creation
                objectchanges = get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, ObjectChangeActionChoices.ACTION_DELETE)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_delete_object_with_constrained_permission(self):
            instance1 = self.get_deletable_object()
            instance2 = self._get_queryset().exclude(pk=instance1.pk)[0]

            # Assign object-level permission
            obj_perm = ObjectPermission(
                name="Test permission",
                constraints={"pk": instance1.pk},
                actions=["delete"],
            )
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Try GET with a permitted object
            self.assertHttpStatus(self.client.get(self._get_url("delete", instance1)), 200)

            # Try GET with a non-permitted object
            self.assertHttpStatus(self.client.get(self._get_url("delete", instance2)), 404)

            # Try to delete a permitted object
            request = {
                "path": self._get_url("delete", instance1),
                "data": post_data({"confirm": True}),
            }
            self.assertHttpStatus(self.client.post(**request), 302)
            with self.assertRaises(ObjectDoesNotExist):
                self._get_queryset().get(pk=instance1.pk)

            # Try to delete a non-permitted object
            # Note that in the case of tree models, deleting instance1 above may have cascade-deleted to instance2,
            # so to be safe, we need to get another object instance that definitely exists:
            instance3 = self._get_queryset().first()
            request = {
                "path": self._get_url("delete", instance3),
                "data": post_data({"confirm": True}),
            }
            self.assertHttpStatus(self.client.post(**request), 404)
            self.assertTrue(self._get_queryset().filter(pk=instance3.pk).exists())

    class ListObjectsViewTestCase(ModelViewTestCase):
        """
        Retrieve multiple instances.
        """

        filterset = None

        def get_filterset(self):
            return self.filterset or get_filterset_for_model(self.model)

        # Helper methods to be overriden by special cases.
        # See ConsoleConnectionsTestCase, InterfaceConnectionsTestCase and PowerConnectionsTestCase
        def get_list_url(self):
            return reverse(validated_viewname(self.model, "list"))

        def get_title(self):
            return bettertitle(self.model._meta.verbose_name_plural)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_list_objects_anonymous(self):
            # Make the request as an unauthenticated user
            self.client.logout()
            response = self.client.get(self._get_url("list"))
            self.assertHttpStatus(response, 200)
            response_body = response.content.decode(response.charset)
            self.assertIn("/login/?next=" + self._get_url("list"), response_body, msg=response_body)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_list_objects_filtered(self):
            instance1, instance2 = self._get_queryset().all()[:2]
            response = self.client.get(f"{self._get_url('list')}?id={instance1.pk}")
            self.assertHttpStatus(response, 200)
            content = extract_page_body(response.content.decode(response.charset))
            # TODO: it'd make test failures more readable if we strip the page headers/footers from the content
            if hasattr(self.model, "name"):
                # TODO: https://github.com/nautobot/nautobot/issues/2580
                #       This is fragile as we move toward more autogenerated test fixtures,
                #       as "instance.name" may appear coincidentally in other page text if we're not careful.
                self.assertIn(instance1.name, content, msg=content)
                self.assertNotIn(instance2.name, content, msg=content)
            try: