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`

    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    @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`

    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    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`

    53
    54
    55
    56
    57
    58
    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
    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
    @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.
                """
                self.maxDiff = None
                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))

                # Verify that an empty PATCH results in no change to the object.
                # This is to catch issues like https://github.com/nautobot/nautobot/issues/3533

                # Add object-level permission for GET
                obj_perm.actions = ["view"]
                obj_perm.save()
                # Get initial serialized object representation
                get_response = self.client.get(url, **self.header)
                self.assertHttpStatus(get_response, status.HTTP_200_OK)
                initial_serialized_object = get_response.json()
                # Work around for https://github.com/nautobot/nautobot/issues/3321
                initial_serialized_object.pop("last_updated", None)

                # Redefine object-level permission for PATCH
                obj_perm.actions = ["change"]
                obj_perm.save()
                # Send empty PATCH request
                response = self.client.patch(url, {}, format="json", **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                serialized_object = response.json()
                # Work around for https://github.com/nautobot/nautobot/issues/3321
                serialized_object.pop("last_updated", None)
                # PATCH response always includes "opt-in" fields, but GET response does not.
                serialized_object.pop("computed_fields", None)
                serialized_object.pop("relationships", None)
                self.assertEqual(initial_serialized_object, serialized_object)

                # Verify ObjectChange creation -- yes, even though nothing actually changed
                # This may change (hah) at some point -- see https://github.com/nautobot/nautobot/issues/3321
                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)
                    objectchanges.delete()

                # Verify that a PATCH with some data updates that data correctly.
                response = self.client.patch(url, update_data, format="json", **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                # Check for unexpected side effects on fields we DIDN'T intend to update
                for field in initial_serialized_object:
                    if field not in update_data:
                        self.assertEqual(initial_serialized_object[field], serialized_object[field])
                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`

    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
    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`

    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
    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`

    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
    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`

    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    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`

    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
    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`

    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    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`

    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    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`

    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    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`

    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    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`

    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    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`

     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
    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`

    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
    @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`

    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    @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`

    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    @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`

    179
    180
    181
    182
    183
    184
    185
    186
    @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`

    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
    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`

    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
    @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`

    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    @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`

    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    @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`

    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    @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`

    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    @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`

    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    @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`

    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    @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`

    331
    332
    333
    334
    335
    336
    337
    @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`

    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    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`

    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
    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.
            """
            self.maxDiff = None
            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))

            # Verify that an empty PATCH results in no change to the object.
            # This is to catch issues like https://github.com/nautobot/nautobot/issues/3533

            # Add object-level permission for GET
            obj_perm.actions = ["view"]
            obj_perm.save()
            # Get initial serialized object representation
            get_response = self.client.get(url, **self.header)
            self.assertHttpStatus(get_response, status.HTTP_200_OK)
            initial_serialized_object = get_response.json()
            # Work around for https://github.com/nautobot/nautobot/issues/3321
            initial_serialized_object.pop("last_updated", None)

            # Redefine object-level permission for PATCH
            obj_perm.actions = ["change"]
            obj_perm.save()
            # Send empty PATCH request
            response = self.client.patch(url, {}, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            serialized_object = response.json()
            # Work around for https://github.com/nautobot/nautobot/issues/3321
            serialized_object.pop("last_updated", None)
            # PATCH response always includes "opt-in" fields, but GET response does not.
            serialized_object.pop("computed_fields", None)
            serialized_object.pop("relationships", None)
            self.assertEqual(initial_serialized_object, serialized_object)

            # Verify ObjectChange creation -- yes, even though nothing actually changed
            # This may change (hah) at some point -- see https://github.com/nautobot/nautobot/issues/3321
            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)
                objectchanges.delete()

            # Verify that a PATCH with some data updates that data correctly.
            response = self.client.patch(url, update_data, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            # Check for unexpected side effects on fields we DIDN'T intend to update
            for field in initial_serialized_object:
                if field not in update_data:
                    self.assertEqual(initial_serialized_object[field], serialized_object[field])
            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`

    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
    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`

    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
    @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`

    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
    @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`

    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
    def test_update_object(self):
        """
        PATCH a single object identified by its ID.
        """
        self.maxDiff = None
        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))

        # Verify that an empty PATCH results in no change to the object.
        # This is to catch issues like https://github.com/nautobot/nautobot/issues/3533

        # Add object-level permission for GET
        obj_perm.actions = ["view"]
        obj_perm.save()
        # Get initial serialized object representation
        get_response = self.client.get(url, **self.header)
        self.assertHttpStatus(get_response, status.HTTP_200_OK)
        initial_serialized_object = get_response.json()
        # Work around for https://github.com/nautobot/nautobot/issues/3321
        initial_serialized_object.pop("last_updated", None)

        # Redefine object-level permission for PATCH
        obj_perm.actions = ["change"]
        obj_perm.save()
        # Send empty PATCH request
        response = self.client.patch(url, {}, format="json", **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        serialized_object = response.json()
        # Work around for https://github.com/nautobot/nautobot/issues/3321
        serialized_object.pop("last_updated", None)
        # PATCH response always includes "opt-in" fields, but GET response does not.
        serialized_object.pop("computed_fields", None)
        serialized_object.pop("relationships", None)
        self.assertEqual(initial_serialized_object, serialized_object)

        # Verify ObjectChange creation -- yes, even though nothing actually changed
        # This may change (hah) at some point -- see https://github.com/nautobot/nautobot/issues/3321
        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)
            objectchanges.delete()

        # Verify that a PATCH with some data updates that data correctly.
        response = self.client.patch(url, update_data, format="json", **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        # Check for unexpected side effects on fields we DIDN'T intend to update
        for field in initial_serialized_object:
            if field not in update_data:
                self.assertEqual(initial_serialized_object[field], serialized_object[field])
        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`

    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    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`

     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     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
    @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`

    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    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`

    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    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`

    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    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`

    58
    59
    60
    61
    62
    63
    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`

    65
    66
    67
    68
    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`

    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    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`

    73
    74
    75
    76
    77
    78
    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`

    80
    81
    82
    83
    84
    85
    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`

     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
    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`

     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
    1417
    1418
    1419
    1420
    1421
    1422
    1423
    1424
    1425
    1426
    1427
    1428
    1429
    1430
    1431
    1432
    1433
    1434
    1435
    1436
    1437
    1438
    1439
    1440
    1441
    1442
    1443
    1444
    1445
    1446
    1447
    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    1456
    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467
    1468
    1469
    1470
    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    @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(escape(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(
                                escape(relationship.get_label(RelationshipSideChoices.SIDE_SOURCE)),
                                response_body,
                                msg=response_body,
                            )
                        if content_type == relationship.destination_type:
                            self.assertIn(
                                escape(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(escape(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(escape(str(value)), response_body, msg=response_body)
                        else:
                            self.assertIn(
                                escape(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"):
                    self.assertRegex(content, r">\s*" + re.escape(escape(instance1.name)) + r"\s*<", msg=content)
                    self.assertNotRegex(content, r">\s*" + re.escape(escape(instance2.name)) + r"\s*<", msg=content)
                try:
                    self.assertIn(self._get_url("view", instance=instance1), content, msg=content)
                    self.assertNotIn(self._get_url("view", instance=instance2), content, msg=content)
                except NoReverseMatch:
                    pass

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"], STRICT_FILTERING=True)
            def test_list_objects_unknown_filter_strict_filtering(self):
                """Verify that with STRICT_FILTERING, an unknown filter results in an error message and no matches."""
                response = self.client.get(f"{self._get_url('list')}?ice_cream_flavor=chocolate")
                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
                self.assertIn("Unknown filter field", content, msg=content)
                # There should be no table rows displayed except for the empty results row
                self.assertIn(f"No {self.model._meta.verbose_name_plural} found", content, msg=content)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"], STRICT_FILTERING=False)
            def test_list_objects_unknown_filter_no_strict_filtering(self):
                """Verify that without STRICT_FILTERING, an unknown filter is ignored."""
                instance1, instance2 = self._get_queryset().all()[:2]
                with self.assertLogs("nautobot.utilities.filters") as cm:
                    response = self.client.get(f"{self._get_url('list')}?ice_cream_flavor=chocolate")
                filterset = self.get_filterset()
                if not filterset:
                    self.fail(
                        f"Couldn't find filterset for model {self.model}. The FilterSet class is expected to be in the "
                        "filters module within the application associated with the model and its name is expected to be "
                        f"{self.model.__name__}FilterSet."
                    )
                self.assertEqual(
                    cm.output,
                    [
                        f"WARNING:nautobot.utilities.filters:{filterset.__name__}: "
                        'Unknown filter field "ice_cream_flavor"',
                    ],
                )
                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
                self.assertNotIn("Unknown filter field", content, msg=content)
                self.assertNotIn(f"No {self.model._meta.verbose_name_plural} found", content, msg=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(escape(instance1.name), content, msg=content)
                    self.assertIn(escape(instance2.name), content, msg=content)
                try:
                    self.assertIn(self._get_url("view", instance=instance1), content, msg=content)
                    self.assertIn(self._get_url("view", instance=instance2), content, msg=content)
                except NoReverseMatch:
                    pass

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_list_objects_without_permission(self):
                # Try GET without permission
                with disable_warnings("django.request"):
                    response = self.client.get(self._get_url("list"))
                    self.assertHttpStatus(response, 403)
                    response_body = response.content.decode(response.charset)
                    self.assertNotIn("/login/", response_body, msg=response_body)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_list_objects_with_permission(self):
                # 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(self._get_url("list"))
                self.assertHttpStatus(response, 200)
                response_body = response.content.decode(response.charset)

                list_url = self.get_list_url()
                title = self.get_title()

                # Check if breadcrumb is rendered correctly
                self.assertIn(
                    f'<a href="{list_url}">{title}</a>',
                    response_body,
                )

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_list_objects_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},
                    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 object-level permission
                response = self.client.get(self._get_url("list"))
                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"):
                    self.assertIn(escape(instance1.name), content, msg=content)
                    self.assertNotIn(escape(instance2.name), content, msg=content)
                elif hasattr(self.model, "get_absolute_url"):
                    self.assertIn(instance1.get_absolute_url(), content, msg=content)
                    self.assertNotIn(instance2.get_absolute_url(), content, msg=content)

            @skipIf(
                "example_plugin" not in settings.PLUGINS,
                "example_plugin not in settings.PLUGINS",
            )
            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_list_view_plugin_banner(self):
                """
                If example plugin is installed, check if the plugin banner is rendered correctly in ObjectListView.
                """
                # 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(self._get_url("list"))
                self.assertHttpStatus(response, 200)
                response_body = response.content.decode(response.charset)

                # Check plugin banner is rendered correctly
                self.assertIn(
                    f"<div>You are viewing a table of {self.model._meta.verbose_name_plural}</div>", response_body
                )

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_queryset_to_csv(self):
                # Built-in CSV export
                if not hasattr(self.model, "csv_headers"):
                    self.skipTest(f"{self.model} has no csv_headers attribute?")
                response = self.client.get(f"{self._get_url('list')}?export")
                self.assertHttpStatus(response, 200)
                self.assertEqual(response.get("Content-Type"), "text/csv")
                instance1 = self._get_queryset().first()
                # With filtering
                response = self.client.get(f"{self._get_url('list')}?export&id={instance1.pk}")
                self.assertHttpStatus(response, 200)
                self.assertEqual(response.get("Content-Type"), "text/csv")
                response_body = response.content.decode(response.charset)
                reader = csv.DictReader(StringIO(response_body))
                # This line will make data a dictionary with csv headers as keys and corresponding csv values as values.
                # For example:
                # {'name': 'AFRINIC', 'slug': 'afrinic', 'is_private': '', 'description': ...'}
                data = [dict(row) for row in reader][0]

                # Get expected data
                instance1_unformatted_data = [
                    *instance1.to_csv(),
                    *instance1.get_custom_fields().values(),
                ]
                # Format expected data using `csv_format`, parse back with `csv` and get first row
                instance1_csv_data = next(iter(csv.reader([csv_format(instance1_unformatted_data)])))

                instance1_cf_headers = ["cf_" + str(cf.slug) for cf in instance1.get_custom_fields().keys()]
                instance1_csv_headers = list(self.model.csv_headers) + instance1_cf_headers
                self.assertEqual(instance1_csv_headers, list(data.keys()))
                self.assertEqual(instance1_csv_data, list(data.values()))

        class CreateMultipleObjectsViewTestCase(ModelViewTestCase):
            """
            Create multiple instances using a single form. Expects the creation of three new instances by default.

            :bulk_create_count: The number of objects expected to be created (default: 3).
            :bulk_create_data: A dictionary of data to be used for bulk object creation.
            """

            bulk_create_count = 3
            bulk_create_data = {}

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_create_multiple_objects_without_permission(self):
                request = {
                    "path": self._get_url("add"),
                    "data": post_data(self.bulk_create_data),
                }

                # Try POST without permission
                with disable_warnings("django.request"):
                    self.assertHttpStatus(self.client.post(**request), 403)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_create_multiple_objects_with_permission(self):
                initial_count = self._get_queryset().count()
                request = {
                    "path": self._get_url("add"),
                    "data": post_data(self.bulk_create_data),
                }

                # Assign non-constrained 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))

                # Bulk create objects
                response = self.client.post(**request)
                self.assertHttpStatus(response, 302)
                self.assertEqual(initial_count + self.bulk_create_count, self._get_queryset().count())
                matching_count = 0
                for instance in self._get_queryset().all():
                    try:
                        self.assertInstanceEqual(instance, self.bulk_create_data)
                        matching_count += 1
                    except AssertionError:
                        pass
                self.assertEqual(matching_count, self.bulk_create_count)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_create_multiple_objects_with_constrained_permission(self):
                initial_count = self._get_queryset().count()
                request = {
                    "path": self._get_url("add"),
                    "data": post_data(self.bulk_create_data),
                }

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

                # Attempt to make the request with unmet constraints
                self.assertHttpStatus(self.client.post(**request), 200)
                self.assertEqual(self._get_queryset().count(), initial_count)

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

                response = self.client.post(**request)
                self.assertHttpStatus(response, 302)
                self.assertEqual(initial_count + self.bulk_create_count, self._get_queryset().count())

                matching_count = 0
                for instance in self._get_queryset().all():
                    try:
                        self.assertInstanceEqual(instance, self.bulk_create_data)
                        matching_count += 1
                    except AssertionError:
                        pass
                self.assertEqual(matching_count, self.bulk_create_count)

        class BulkImportObjectsViewTestCase(ModelViewTestCase):
            """
            Create multiple instances from imported data.

            :csv_data: A list of CSV-formatted lines (starting with the headers) to be used for bulk object import.
            """

            csv_data = ()

            def _get_csv_data(self):
                return "\n".join(self.csv_data)

            def test_bulk_import_objects_without_permission(self):
                data = {
                    "csv_data": self._get_csv_data(),
                }

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

                # Try POST without permission
                response = self.client.post(self._get_url("import"), data)
                with disable_warnings("django.request"):
                    self.assertHttpStatus(response, 403)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_import_objects_with_permission(self):
                initial_count = self._get_queryset().count()
                data = {
                    "csv_data": self._get_csv_data(),
                }

                # Assign model-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))

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

                # Test POST with permission
                self.assertHttpStatus(self.client.post(self._get_url("import"), data), 200)
                self.assertEqual(self._get_queryset().count(), initial_count + len(self.csv_data) - 1)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_import_objects_with_permission_csv_file(self):
                initial_count = self._get_queryset().count()
                self.file_contents = bytes(self._get_csv_data(), "utf-8")
                self.bulk_import_file = SimpleUploadedFile(name="bulk_import_data.csv", content=self.file_contents)
                data = {
                    "csv_file": self.bulk_import_file,
                }

                # Assign model-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))

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

                # Test POST with permission
                self.assertHttpStatus(self.client.post(self._get_url("import"), data), 200)
                self.assertEqual(self._get_queryset().count(), initial_count + len(self.csv_data) - 1)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_import_objects_with_constrained_permission(self):
                initial_count = self._get_queryset().count()
                data = {
                    "csv_data": self._get_csv_data(),
                }

                # 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))

                # Attempt to import non-permitted objects
                self.assertHttpStatus(self.client.post(self._get_url("import"), data), 200)
                self.assertEqual(self._get_queryset().count(), initial_count)

                # Update permission constraints
                obj_perm.constraints = {"pk__isnull": False}  # Set permission to allow all
                obj_perm.save()

                # Import permitted objects
                self.assertHttpStatus(self.client.post(self._get_url("import"), data), 200)
                self.assertEqual(self._get_queryset().count(), initial_count + len(self.csv_data) - 1)

        class BulkEditObjectsViewTestCase(ModelViewTestCase):
            """
            Edit multiple instances.

            :bulk_edit_data: A dictionary of data to be used when bulk editing a set of objects. This data should differ
                             from that used for initial object creation within setUpTestData().
            """

            bulk_edit_data = {}

            def test_bulk_edit_objects_without_permission(self):
                pk_list = list(self._get_queryset().values_list("pk", flat=True)[:3])
                data = {
                    "pk": pk_list,
                    "_apply": True,  # Form button
                }

                # Try POST without permission
                with disable_warnings("django.request"):
                    self.assertHttpStatus(self.client.post(self._get_url("bulk_edit"), data), 403)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_edit_objects_with_permission(self):
                pk_list = list(self._get_queryset().values_list("pk", flat=True)[:3])
                data = {
                    "pk": pk_list,
                    "_apply": True,  # Form button
                }

                # Append the form data to the request
                data.update(post_data(self.bulk_edit_data))

                # 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 POST with model-level permission
                self.assertHttpStatus(self.client.post(self._get_url("bulk_edit"), data), 302)
                for instance in self._get_queryset().filter(pk__in=pk_list):
                    self.assertInstanceEqual(instance, self.bulk_edit_data)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_edit_form_contains_all_pks(self):
                # We are testing the intermediary step of bulk_edit with pagination applied.
                # i.e. "_all" passed in the form.
                pk_list = self._get_queryset().values_list("pk", flat=True)
                # We only pass in one pk to test the functionality of "_all"
                # which should grab all instance pks regardless of "pk"
                selected_data = {
                    "pk": pk_list[:1],
                    "_all": "on",
                }
                # 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 POST with model-level permission
                response = self.client.post(self._get_url("bulk_edit"), selected_data)
                # Expect a 200 status cause we are only rendering the bulk edit table.
                # after pressing Edit Selected button.
                self.assertHttpStatus(response, 200)
                response_body = extract_page_body(response.content.decode(response.charset))
                # Check if all the pks are passed into the BulkEditForm/BulkUpdateForm
                for pk in pk_list:
                    self.assertIn(f'<input type="hidden" name="pk" value="{pk}"', response_body)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_edit_objects_with_constrained_permission(self):
                # Select some objects that are *not* already set to match the first value in self.bulk_edit_data or null.
                # We have to exclude null cases because Django filter()/exclude() doesn't like `__in=[None]` as a case.
                attr_name = list(self.bulk_edit_data.keys())[0]
                objects = (
                    self._get_queryset()
                    .exclude(**{attr_name: self.bulk_edit_data[attr_name]})
                    .exclude(**{f"{attr_name}__isnull": True})
                )[:3]
                self.assertEqual(objects.count(), 3)
                pk_list = list(objects.values_list("pk", flat=True))

                # Define a permission that permits the above objects, but will not permit them after updating them.
                field = self.model._meta.get_field(attr_name)
                values = [field.value_from_object(obj) for obj in objects]
                obj_perm = ObjectPermission(
                    name="Test permission",
                    constraints={f"{attr_name}__in": values},
                    actions=["change"],
                )
                obj_perm.save()
                obj_perm.users.add(self.user)
                obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

                # Build form data
                data = {
                    "pk": pk_list,
                    "_apply": True,  # Form button
                }
                data.update(post_data(self.bulk_edit_data))

                # Attempt to bulk edit permitted objects into a non-permitted state
                response = self.client.post(self._get_url("bulk_edit"), data)
                # 200 because we're sent back to the edit form to try again; if the update were successful it'd be a 302
                self.assertHttpStatus(response, 200)
                # Assert that the objects are NOT updated
                for instance in self._get_queryset().filter(pk__in=pk_list):
                    self.assertIn(field.value_from_object(instance), values)
                    self.assertNotEqual(field.value_from_object(instance), self.bulk_edit_data[attr_name])

                # Update permission constraints to permit all objects
                obj_perm.constraints = {"pk__gt": 0}
                obj_perm.save()

                # Bulk edit permitted objects and expect a redirect back to the list view
                self.assertHttpStatus(self.client.post(self._get_url("bulk_edit"), data), 302)
                # Assert that the objects were all updated correctly
                for instance in self._get_queryset().filter(pk__in=pk_list):
                    self.assertInstanceEqual(instance, self.bulk_edit_data)

        class BulkDeleteObjectsViewTestCase(ModelViewTestCase):
            """
            Delete multiple instances.
            """

            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.
                """
                return get_deletable_objects(self.model, self._get_queryset()).values_list("pk", flat=True)[:3]

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_bulk_delete_objects_without_permission(self):
                pk_list = self.get_deletable_object_pks()
                data = {
                    "pk": pk_list,
                    "confirm": True,
                    "_confirm": True,  # Form button
                }

                # Try POST without permission
                with disable_warnings("django.request"):
                    self.assertHttpStatus(self.client.post(self._get_url("bulk_delete"), data), 403)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_bulk_delete_objects_with_permission(self):
                pk_list = self.get_deletable_object_pks()
                initial_count = self._get_queryset().count()
                data = {
                    "pk": pk_list,
                    "confirm": True,
                    "_confirm": True,  # Form button
                }

                # Assign unconstrained 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 POST with model-level permission
                self.assertHttpStatus(self.client.post(self._get_url("bulk_delete"), data), 302)
                self.assertEqual(self._get_queryset().count(), initial_count - len(pk_list))

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_bulk_delete_form_contains_all_pks(self):
                # We are testing the intermediary step of bulk_delete with pagination applied.
                # i.e. "_all" passed in the form.
                pk_list = self._get_queryset().values_list("pk", flat=True)
                # We only pass in one pk to test the functionality of "_all"
                # which should grab all instance pks regardless of "pks".
                selected_data = {
                    "pk": pk_list[:1],
                    "confirm": True,
                    "_all": "on",
                }

                # Assign unconstrained 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 POST with the selected data first. Emulating selecting all -> pressing Delete Selected button.
                response = self.client.post(self._get_url("bulk_delete"), selected_data)
                self.assertHttpStatus(response, 200)
                response_body = extract_page_body(response.content.decode(response.charset))
                # Check if all the pks are passed into the BulkDeleteForm/BulkDestroyForm
                for pk in pk_list:
                    self.assertIn(f'<input type="hidden" name="pk" value="{pk}"', response_body)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_bulk_delete_objects_with_constrained_permission(self):
                pk_list = self.get_deletable_object_pks()
                initial_count = self._get_queryset().count()
                data = {
                    "pk": pk_list,
                    "confirm": True,
                    "_confirm": True,  # Form button
                }

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

                # Attempt to bulk delete non-permitted objects
                self.assertHttpStatus(self.client.post(self._get_url("bulk_delete"), data), 302)
                self.assertEqual(self._get_queryset().count(), initial_count)

                # Update permission constraints
                obj_perm.constraints = {"pk__isnull": False}  # Match a non-existent pk (i.e., allow all)
                obj_perm.save()

                # Bulk delete permitted objects
                self.assertHttpStatus(self.client.post(self._get_url("bulk_delete"), data), 302)
                self.assertEqual(self._get_queryset().count(), initial_count - len(pk_list))

        class BulkRenameObjectsViewTestCase(ModelViewTestCase):
            """
            Rename multiple instances.
            """

            rename_data = {
                "find": "^(.*)$",
                "replace": "\\1X",  # Append an X to the original value
                "use_regex": True,
            }

            def test_bulk_rename_objects_without_permission(self):
                pk_list = list(self._get_queryset().values_list("pk", flat=True)[:3])
                data = {
                    "pk": pk_list,
                    "_apply": True,  # Form button
                }
                data.update(self.rename_data)

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

                # Try POST without permission
                with disable_warnings("django.request"):
                    self.assertHttpStatus(self.client.post(self._get_url("bulk_rename"), data), 403)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_rename_objects_with_permission(self):
                objects = list(self._get_queryset().all()[:3])
                pk_list = [obj.pk for obj in objects]
                data = {
                    "pk": pk_list,
                    "_apply": True,  # Form button
                }
                data.update(self.rename_data)

                # 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 POST with model-level permission
                self.assertHttpStatus(self.client.post(self._get_url("bulk_rename"), data), 302)
                for i, instance in enumerate(self._get_queryset().filter(pk__in=pk_list)):
                    self.assertEqual(instance.name, f"{objects[i].name}X")

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_rename_objects_with_constrained_permission(self):
                objects = list(self._get_queryset().all()[:3])
                pk_list = [obj.pk for obj in objects]
                data = {
                    "pk": pk_list,
                    "_apply": True,  # Form button
                }
                data.update(self.rename_data)

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

                # Attempt to bulk edit permitted objects into a non-permitted state
                response = self.client.post(self._get_url("bulk_rename"), data)
                self.assertHttpStatus(response, 200)

                # Update permission constraints
                obj_perm.constraints = {"pk__gt": 0}
                obj_perm.save()

                # Bulk rename permitted objects
                self.assertHttpStatus(self.client.post(self._get_url("bulk_rename"), data), 302)
                for i, instance in enumerate(self._get_queryset().filter(pk__in=pk_list)):
                    self.assertEqual(instance.name, f"{objects[i].name}X")

        class PrimaryObjectViewTestCase(
            GetObjectViewTestCase,
            GetObjectChangelogViewTestCase,
            GetObjectNotesViewTestCase,
            CreateObjectViewTestCase,
            EditObjectViewTestCase,
            DeleteObjectViewTestCase,
            ListObjectsViewTestCase,
            BulkImportObjectsViewTestCase,
            BulkEditObjectsViewTestCase,
            BulkDeleteObjectsViewTestCase,
        ):
            """
            TestCase suitable for testing all standard View functions for primary objects
            """

            maxDiff = None

        class OrganizationalObjectViewTestCase(
            GetObjectViewTestCase,
            GetObjectChangelogViewTestCase,
            GetObjectNotesViewTestCase,
            CreateObjectViewTestCase,
            EditObjectViewTestCase,
            DeleteObjectViewTestCase,
            ListObjectsViewTestCase,
            BulkImportObjectsViewTestCase,
            BulkDeleteObjectsViewTestCase,
        ):
            """
            TestCase suitable for all organizational objects
            """

            maxDiff = None

        class DeviceComponentTemplateViewTestCase(
            EditObjectViewTestCase,
            DeleteObjectViewTestCase,
            CreateMultipleObjectsViewTestCase,
            BulkEditObjectsViewTestCase,
            BulkRenameObjectsViewTestCase,
            BulkDeleteObjectsViewTestCase,
        ):
            """
            TestCase suitable for testing device component template models (ConsolePortTemplates, InterfaceTemplates, etc.)
            """

            maxDiff = None

        class DeviceComponentViewTestCase(
            GetObjectViewTestCase,
            GetObjectChangelogViewTestCase,
            GetObjectNotesViewTestCase,
            EditObjectViewTestCase,
            DeleteObjectViewTestCase,
            ListObjectsViewTestCase,
            CreateMultipleObjectsViewTestCase,
            BulkImportObjectsViewTestCase,
            BulkEditObjectsViewTestCase,
            BulkRenameObjectsViewTestCase,
            BulkDeleteObjectsViewTestCase,
        ):
            """
            TestCase suitable for testing device component models (ConsolePorts, Interfaces, etc.)
            """

            maxDiff = None
            bulk_add_data = None
            """Used for bulk-add (distinct from bulk-create) view testing; self.bulk_create_data will be used if unset."""

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_add_component(self):
                """Test bulk-adding this component to devices/virtual-machines."""
                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()

                data = (self.bulk_add_data or self.bulk_create_data).copy()

                # Load the device-bulk-add or virtualmachine-bulk-add form
                if "device" in data:
                    url = reverse(f"dcim:device_bulk_add_{self.model._meta.model_name}")
                    request = {
                        "path": url,
                        "data": post_data({"pk": data["device"]}),
                    }
                else:
                    url = reverse(f"virtualization:virtualmachine_bulk_add_{self.model._meta.model_name}")
                    request = {
                        "path": url,
                        "data": post_data({"pk": data["virtual_machine"]}),
                    }
                self.assertHttpStatus(self.client.post(**request), 200)

                # Post to the device-bulk-add or virtualmachine-bulk-add form to create records
                if "device" in data:
                    data["pk"] = data.pop("device")
                else:
                    data["pk"] = data.pop("virtual_machine")
                data["_create"] = ""
                request["data"] = post_data(data)
                self.assertHttpStatus(self.client.post(**request), 302)

                updated_count = self._get_queryset().count()
                self.assertEqual(updated_count, initial_count + self.bulk_create_count)

                matching_count = 0
                for instance in self._get_queryset().all():
                    try:
                        self.assertInstanceEqual(instance, (self.bulk_add_data or self.bulk_create_data))
                        matching_count += 1
                    except AssertionError:
                        pass
                self.assertEqual(matching_count, self.bulk_create_count)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
            def test_bulk_rename(self):
                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))

                objects = self.selected_objects
                pk_list = [obj.pk for obj in objects]
                # Apply button not yet clicked
                data = {"pk": pk_list}
                data.update(self.rename_data)
                verbose_name_plural = self.model._meta.verbose_name_plural

                with self.subTest("Assert device name in HTML"):
                    response = self.client.post(self._get_url("bulk_rename"), data)
                    message = (
                        f"Renaming {len(objects)} {bettertitle(verbose_name_plural)} on {self.selected_objects_parent_name}"
                    )
                    self.assertInHTML(message, response.content.decode(response.charset))

                with self.subTest("Assert update successfully"):
                    data["_apply"] = True  # Form Apply button
                    response = self.client.post(self._get_url("bulk_rename"), data)
                    self.assertHttpStatus(response, 302)
                    queryset = self._get_queryset().filter(pk__in=pk_list)
                    for instance in objects:
                        self.assertEqual(queryset.get(pk=instance.pk).name, f"{instance.name}X")

                with self.subTest("Assert if no valid objects selected return with error"):
                    for values in ([], [str(uuid.uuid4())]):
                        data["pk"] = values
                        response = self.client.post(self._get_url("bulk_rename"), data, follow=True)
                        expected_message = f"No valid {verbose_name_plural} were selected."
                        self.assertIn(expected_message, response.content.decode(response.charset))

### `BulkDeleteObjectsViewTestCase`

Bases: `ModelViewTestCase`

Delete multiple instances.

Source code in `nautobot/utilities/testing/views.py`

    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
    class BulkDeleteObjectsViewTestCase(ModelViewTestCase):
        """
        Delete multiple instances.
        """

        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.
            """
            return get_deletable_objects(self.model, self._get_queryset()).values_list("pk", flat=True)[:3]

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_bulk_delete_objects_without_permission(self):
            pk_list = self.get_deletable_object_pks()
            data = {
                "pk": pk_list,
                "confirm": True,
                "_confirm": True,  # Form button
            }

            # Try POST without permission
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.post(self._get_url("bulk_delete"), data), 403)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_bulk_delete_objects_with_permission(self):
            pk_list = self.get_deletable_object_pks()
            initial_count = self._get_queryset().count()
            data = {
                "pk": pk_list,
                "confirm": True,
                "_confirm": True,  # Form button
            }

            # Assign unconstrained 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 POST with model-level permission
            self.assertHttpStatus(self.client.post(self._get_url("bulk_delete"), data), 302)
            self.assertEqual(self._get_queryset().count(), initial_count - len(pk_list))

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_bulk_delete_form_contains_all_pks(self):
            # We are testing the intermediary step of bulk_delete with pagination applied.
            # i.e. "_all" passed in the form.
            pk_list = self._get_queryset().values_list("pk", flat=True)
            # We only pass in one pk to test the functionality of "_all"
            # which should grab all instance pks regardless of "pks".
            selected_data = {
                "pk": pk_list[:1],
                "confirm": True,
                "_all": "on",
            }

            # Assign unconstrained 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 POST with the selected data first. Emulating selecting all -> pressing Delete Selected button.
            response = self.client.post(self._get_url("bulk_delete"), selected_data)
            self.assertHttpStatus(response, 200)
            response_body = extract_page_body(response.content.decode(response.charset))
            # Check if all the pks are passed into the BulkDeleteForm/BulkDestroyForm
            for pk in pk_list:
                self.assertIn(f'<input type="hidden" name="pk" value="{pk}"', response_body)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_bulk_delete_objects_with_constrained_permission(self):
            pk_list = self.get_deletable_object_pks()
            initial_count = self._get_queryset().count()
            data = {
                "pk": pk_list,
                "confirm": True,
                "_confirm": True,  # Form button
            }

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

            # Attempt to bulk delete non-permitted objects
            self.assertHttpStatus(self.client.post(self._get_url("bulk_delete"), data), 302)
            self.assertEqual(self._get_queryset().count(), initial_count)

            # Update permission constraints
            obj_perm.constraints = {"pk__isnull": False}  # Match a non-existent pk (i.e., allow all)
            obj_perm.save()

            # Bulk delete permitted objects
            self.assertHttpStatus(self.client.post(self._get_url("bulk_delete"), data), 302)
            self.assertEqual(self._get_queryset().count(), initial_count - len(pk_list))

#### `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/views.py`

    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    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.
        """
        return get_deletable_objects(self.model, self._get_queryset()).values_list("pk", flat=True)[:3]

### `BulkEditObjectsViewTestCase`

Bases: `ModelViewTestCase`

Edit multiple instances.

:bulk_edit_data: A dictionary of data to be used when bulk editing a set of objects. This data should differ from that used for initial object creation within setUpTestData().

Source code in `nautobot/utilities/testing/views.py`

    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
    class BulkEditObjectsViewTestCase(ModelViewTestCase):
        """
        Edit multiple instances.

        :bulk_edit_data: A dictionary of data to be used when bulk editing a set of objects. This data should differ
                         from that used for initial object creation within setUpTestData().
        """

        bulk_edit_data = {}

        def test_bulk_edit_objects_without_permission(self):
            pk_list = list(self._get_queryset().values_list("pk", flat=True)[:3])
            data = {
                "pk": pk_list,
                "_apply": True,  # Form button
            }

            # Try POST without permission
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.post(self._get_url("bulk_edit"), data), 403)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_edit_objects_with_permission(self):
            pk_list = list(self._get_queryset().values_list("pk", flat=True)[:3])
            data = {
                "pk": pk_list,
                "_apply": True,  # Form button
            }

            # Append the form data to the request
            data.update(post_data(self.bulk_edit_data))

            # 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 POST with model-level permission
            self.assertHttpStatus(self.client.post(self._get_url("bulk_edit"), data), 302)
            for instance in self._get_queryset().filter(pk__in=pk_list):
                self.assertInstanceEqual(instance, self.bulk_edit_data)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_edit_form_contains_all_pks(self):
            # We are testing the intermediary step of bulk_edit with pagination applied.
            # i.e. "_all" passed in the form.
            pk_list = self._get_queryset().values_list("pk", flat=True)
            # We only pass in one pk to test the functionality of "_all"
            # which should grab all instance pks regardless of "pk"
            selected_data = {
                "pk": pk_list[:1],
                "_all": "on",
            }
            # 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 POST with model-level permission
            response = self.client.post(self._get_url("bulk_edit"), selected_data)
            # Expect a 200 status cause we are only rendering the bulk edit table.
            # after pressing Edit Selected button.
            self.assertHttpStatus(response, 200)
            response_body = extract_page_body(response.content.decode(response.charset))
            # Check if all the pks are passed into the BulkEditForm/BulkUpdateForm
            for pk in pk_list:
                self.assertIn(f'<input type="hidden" name="pk" value="{pk}"', response_body)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_edit_objects_with_constrained_permission(self):
            # Select some objects that are *not* already set to match the first value in self.bulk_edit_data or null.
            # We have to exclude null cases because Django filter()/exclude() doesn't like `__in=[None]` as a case.
            attr_name = list(self.bulk_edit_data.keys())[0]
            objects = (
                self._get_queryset()
                .exclude(**{attr_name: self.bulk_edit_data[attr_name]})
                .exclude(**{f"{attr_name}__isnull": True})
            )[:3]
            self.assertEqual(objects.count(), 3)
            pk_list = list(objects.values_list("pk", flat=True))

            # Define a permission that permits the above objects, but will not permit them after updating them.
            field = self.model._meta.get_field(attr_name)
            values = [field.value_from_object(obj) for obj in objects]
            obj_perm = ObjectPermission(
                name="Test permission",
                constraints={f"{attr_name}__in": values},
                actions=["change"],
            )
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            # Build form data
            data = {
                "pk": pk_list,
                "_apply": True,  # Form button
            }
            data.update(post_data(self.bulk_edit_data))

            # Attempt to bulk edit permitted objects into a non-permitted state
            response = self.client.post(self._get_url("bulk_edit"), data)
            # 200 because we're sent back to the edit form to try again; if the update were successful it'd be a 302
            self.assertHttpStatus(response, 200)
            # Assert that the objects are NOT updated
            for instance in self._get_queryset().filter(pk__in=pk_list):
                self.assertIn(field.value_from_object(instance), values)
                self.assertNotEqual(field.value_from_object(instance), self.bulk_edit_data[attr_name])

            # Update permission constraints to permit all objects
            obj_perm.constraints = {"pk__gt": 0}
            obj_perm.save()

            # Bulk edit permitted objects and expect a redirect back to the list view
            self.assertHttpStatus(self.client.post(self._get_url("bulk_edit"), data), 302)
            # Assert that the objects were all updated correctly
            for instance in self._get_queryset().filter(pk__in=pk_list):
                self.assertInstanceEqual(instance, self.bulk_edit_data)

### `BulkImportObjectsViewTestCase`

Bases: `ModelViewTestCase`

Create multiple instances from imported data.

:csv_data: A list of CSV-formatted lines (starting with the headers) to be used for bulk object import.

Source code in `nautobot/utilities/testing/views.py`

     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
    class BulkImportObjectsViewTestCase(ModelViewTestCase):
        """
        Create multiple instances from imported data.

        :csv_data: A list of CSV-formatted lines (starting with the headers) to be used for bulk object import.
        """

        csv_data = ()

        def _get_csv_data(self):
            return "\n".join(self.csv_data)

        def test_bulk_import_objects_without_permission(self):
            data = {
                "csv_data": self._get_csv_data(),
            }

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

            # Try POST without permission
            response = self.client.post(self._get_url("import"), data)
            with disable_warnings("django.request"):
                self.assertHttpStatus(response, 403)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_import_objects_with_permission(self):
            initial_count = self._get_queryset().count()
            data = {
                "csv_data": self._get_csv_data(),
            }

            # Assign model-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))

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

            # Test POST with permission
            self.assertHttpStatus(self.client.post(self._get_url("import"), data), 200)
            self.assertEqual(self._get_queryset().count(), initial_count + len(self.csv_data) - 1)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_import_objects_with_permission_csv_file(self):
            initial_count = self._get_queryset().count()
            self.file_contents = bytes(self._get_csv_data(), "utf-8")
            self.bulk_import_file = SimpleUploadedFile(name="bulk_import_data.csv", content=self.file_contents)
            data = {
                "csv_file": self.bulk_import_file,
            }

            # Assign model-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))

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

            # Test POST with permission
            self.assertHttpStatus(self.client.post(self._get_url("import"), data), 200)
            self.assertEqual(self._get_queryset().count(), initial_count + len(self.csv_data) - 1)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_import_objects_with_constrained_permission(self):
            initial_count = self._get_queryset().count()
            data = {
                "csv_data": self._get_csv_data(),
            }

            # 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))

            # Attempt to import non-permitted objects
            self.assertHttpStatus(self.client.post(self._get_url("import"), data), 200)
            self.assertEqual(self._get_queryset().count(), initial_count)

            # Update permission constraints
            obj_perm.constraints = {"pk__isnull": False}  # Set permission to allow all
            obj_perm.save()

            # Import permitted objects
            self.assertHttpStatus(self.client.post(self._get_url("import"), data), 200)
            self.assertEqual(self._get_queryset().count(), initial_count + len(self.csv_data) - 1)

### `BulkRenameObjectsViewTestCase`

Bases: `ModelViewTestCase`

Rename multiple instances.

Source code in `nautobot/utilities/testing/views.py`

    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
    class BulkRenameObjectsViewTestCase(ModelViewTestCase):
        """
        Rename multiple instances.
        """

        rename_data = {
            "find": "^(.*)$",
            "replace": "\\1X",  # Append an X to the original value
            "use_regex": True,
        }

        def test_bulk_rename_objects_without_permission(self):
            pk_list = list(self._get_queryset().values_list("pk", flat=True)[:3])
            data = {
                "pk": pk_list,
                "_apply": True,  # Form button
            }
            data.update(self.rename_data)

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

            # Try POST without permission
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.post(self._get_url("bulk_rename"), data), 403)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_rename_objects_with_permission(self):
            objects = list(self._get_queryset().all()[:3])
            pk_list = [obj.pk for obj in objects]
            data = {
                "pk": pk_list,
                "_apply": True,  # Form button
            }
            data.update(self.rename_data)

            # 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 POST with model-level permission
            self.assertHttpStatus(self.client.post(self._get_url("bulk_rename"), data), 302)
            for i, instance in enumerate(self._get_queryset().filter(pk__in=pk_list)):
                self.assertEqual(instance.name, f"{objects[i].name}X")

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_rename_objects_with_constrained_permission(self):
            objects = list(self._get_queryset().all()[:3])
            pk_list = [obj.pk for obj in objects]
            data = {
                "pk": pk_list,
                "_apply": True,  # Form button
            }
            data.update(self.rename_data)

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

            # Attempt to bulk edit permitted objects into a non-permitted state
            response = self.client.post(self._get_url("bulk_rename"), data)
            self.assertHttpStatus(response, 200)

            # Update permission constraints
            obj_perm.constraints = {"pk__gt": 0}
            obj_perm.save()

            # Bulk rename permitted objects
            self.assertHttpStatus(self.client.post(self._get_url("bulk_rename"), data), 302)
            for i, instance in enumerate(self._get_queryset().filter(pk__in=pk_list)):
                self.assertEqual(instance.name, f"{objects[i].name}X")

### `CreateMultipleObjectsViewTestCase`

Bases: `ModelViewTestCase`

Create multiple instances using a single form. Expects the creation of three new instances by default.

:bulk_create_count: The number of objects expected to be created (default: 3). :bulk_create_data: A dictionary of data to be used for bulk object creation.

Source code in `nautobot/utilities/testing/views.py`

    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
    class CreateMultipleObjectsViewTestCase(ModelViewTestCase):
        """
        Create multiple instances using a single form. Expects the creation of three new instances by default.

        :bulk_create_count: The number of objects expected to be created (default: 3).
        :bulk_create_data: A dictionary of data to be used for bulk object creation.
        """

        bulk_create_count = 3
        bulk_create_data = {}

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_create_multiple_objects_without_permission(self):
            request = {
                "path": self._get_url("add"),
                "data": post_data(self.bulk_create_data),
            }

            # Try POST without permission
            with disable_warnings("django.request"):
                self.assertHttpStatus(self.client.post(**request), 403)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_create_multiple_objects_with_permission(self):
            initial_count = self._get_queryset().count()
            request = {
                "path": self._get_url("add"),
                "data": post_data(self.bulk_create_data),
            }

            # Assign non-constrained 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))

            # Bulk create objects
            response = self.client.post(**request)
            self.assertHttpStatus(response, 302)
            self.assertEqual(initial_count + self.bulk_create_count, self._get_queryset().count())
            matching_count = 0
            for instance in self._get_queryset().all():
                try:
                    self.assertInstanceEqual(instance, self.bulk_create_data)
                    matching_count += 1
                except AssertionError:
                    pass
            self.assertEqual(matching_count, self.bulk_create_count)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_create_multiple_objects_with_constrained_permission(self):
            initial_count = self._get_queryset().count()
            request = {
                "path": self._get_url("add"),
                "data": post_data(self.bulk_create_data),
            }

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

            # Attempt to make the request with unmet constraints
            self.assertHttpStatus(self.client.post(**request), 200)
            self.assertEqual(self._get_queryset().count(), initial_count)

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

            response = self.client.post(**request)
            self.assertHttpStatus(response, 302)
            self.assertEqual(initial_count + self.bulk_create_count, self._get_queryset().count())

            matching_count = 0
            for instance in self._get_queryset().all():
                try:
                    self.assertInstanceEqual(instance, self.bulk_create_data)
                    matching_count += 1
                except AssertionError:
                    pass
            self.assertEqual(matching_count, self.bulk_create_count)

### `CreateObjectViewTestCase`

Bases: `ModelViewTestCase`

Create a single new instance.

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

Source code in `nautobot/utilities/testing/views.py`

    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
    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)

#### `test_slug_autocreation()`

Test that slug is autocreated through ORM.

Source code in `nautobot/utilities/testing/views.py`

    383
    384
    385
    386
    387
    388
    389
    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)

#### `test_slug_not_modified()`

Ensure save method does not modify slug that is passed in.

Source code in `nautobot/utilities/testing/views.py`

    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    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)

### `DeleteObjectViewTestCase`

Bases: `ModelViewTestCase`

Delete a single instance.

Source code in `nautobot/utilities/testing/views.py`

    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
    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())

#### `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/views.py`

    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    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

### `DeviceComponentTemplateViewTestCase`

Bases: `EditObjectViewTestCase`, `DeleteObjectViewTestCase`, `CreateMultipleObjectsViewTestCase`, `BulkEditObjectsViewTestCase`, `BulkRenameObjectsViewTestCase`, `BulkDeleteObjectsViewTestCase`

TestCase suitable for testing device component template models (ConsolePortTemplates, InterfaceTemplates, etc.)

Source code in `nautobot/utilities/testing/views.py`

    1362
    1363
    1364
    1365
    1366
    1367
    1368
    1369
    1370
    1371
    1372
    1373
    1374
    class DeviceComponentTemplateViewTestCase(
        EditObjectViewTestCase,
        DeleteObjectViewTestCase,
        CreateMultipleObjectsViewTestCase,
        BulkEditObjectsViewTestCase,
        BulkRenameObjectsViewTestCase,
        BulkDeleteObjectsViewTestCase,
    ):
        """
        TestCase suitable for testing device component template models (ConsolePortTemplates, InterfaceTemplates, etc.)
        """

        maxDiff = None

### `DeviceComponentViewTestCase`

Bases: `GetObjectViewTestCase`, `GetObjectChangelogViewTestCase`, `GetObjectNotesViewTestCase`, `EditObjectViewTestCase`, `DeleteObjectViewTestCase`, `ListObjectsViewTestCase`, `CreateMultipleObjectsViewTestCase`, `BulkImportObjectsViewTestCase`, `BulkEditObjectsViewTestCase`, `BulkRenameObjectsViewTestCase`, `BulkDeleteObjectsViewTestCase`

TestCase suitable for testing device component models (ConsolePorts, Interfaces, etc.)

Source code in `nautobot/utilities/testing/views.py`

    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
    1417
    1418
    1419
    1420
    1421
    1422
    1423
    1424
    1425
    1426
    1427
    1428
    1429
    1430
    1431
    1432
    1433
    1434
    1435
    1436
    1437
    1438
    1439
    1440
    1441
    1442
    1443
    1444
    1445
    1446
    1447
    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    1456
    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467
    1468
    1469
    1470
    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    class DeviceComponentViewTestCase(
        GetObjectViewTestCase,
        GetObjectChangelogViewTestCase,
        GetObjectNotesViewTestCase,
        EditObjectViewTestCase,
        DeleteObjectViewTestCase,
        ListObjectsViewTestCase,
        CreateMultipleObjectsViewTestCase,
        BulkImportObjectsViewTestCase,
        BulkEditObjectsViewTestCase,
        BulkRenameObjectsViewTestCase,
        BulkDeleteObjectsViewTestCase,
    ):
        """
        TestCase suitable for testing device component models (ConsolePorts, Interfaces, etc.)
        """

        maxDiff = None
        bulk_add_data = None
        """Used for bulk-add (distinct from bulk-create) view testing; self.bulk_create_data will be used if unset."""

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_add_component(self):
            """Test bulk-adding this component to devices/virtual-machines."""
            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()

            data = (self.bulk_add_data or self.bulk_create_data).copy()

            # Load the device-bulk-add or virtualmachine-bulk-add form
            if "device" in data:
                url = reverse(f"dcim:device_bulk_add_{self.model._meta.model_name}")
                request = {
                    "path": url,
                    "data": post_data({"pk": data["device"]}),
                }
            else:
                url = reverse(f"virtualization:virtualmachine_bulk_add_{self.model._meta.model_name}")
                request = {
                    "path": url,
                    "data": post_data({"pk": data["virtual_machine"]}),
                }
            self.assertHttpStatus(self.client.post(**request), 200)

            # Post to the device-bulk-add or virtualmachine-bulk-add form to create records
            if "device" in data:
                data["pk"] = data.pop("device")
            else:
                data["pk"] = data.pop("virtual_machine")
            data["_create"] = ""
            request["data"] = post_data(data)
            self.assertHttpStatus(self.client.post(**request), 302)

            updated_count = self._get_queryset().count()
            self.assertEqual(updated_count, initial_count + self.bulk_create_count)

            matching_count = 0
            for instance in self._get_queryset().all():
                try:
                    self.assertInstanceEqual(instance, (self.bulk_add_data or self.bulk_create_data))
                    matching_count += 1
                except AssertionError:
                    pass
            self.assertEqual(matching_count, self.bulk_create_count)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_bulk_rename(self):
            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))

            objects = self.selected_objects
            pk_list = [obj.pk for obj in objects]
            # Apply button not yet clicked
            data = {"pk": pk_list}
            data.update(self.rename_data)
            verbose_name_plural = self.model._meta.verbose_name_plural

            with self.subTest("Assert device name in HTML"):
                response = self.client.post(self._get_url("bulk_rename"), data)
                message = (
                    f"Renaming {len(objects)} {bettertitle(verbose_name_plural)} on {self.selected_objects_parent_name}"
                )
                self.assertInHTML(message, response.content.decode(response.charset))

            with self.subTest("Assert update successfully"):
                data["_apply"] = True  # Form Apply button
                response = self.client.post(self._get_url("bulk_rename"), data)
                self.assertHttpStatus(response, 302)
                queryset = self._get_queryset().filter(pk__in=pk_list)
                for instance in objects:
                    self.assertEqual(queryset.get(pk=instance.pk).name, f"{instance.name}X")

            with self.subTest("Assert if no valid objects selected return with error"):
                for values in ([], [str(uuid.uuid4())]):
                    data["pk"] = values
                    response = self.client.post(self._get_url("bulk_rename"), data, follow=True)
                    expected_message = f"No valid {verbose_name_plural} were selected."
                    self.assertIn(expected_message, response.content.decode(response.charset))

#### `bulk_add_data = None` `class-attribute` `instance-attribute`

Used for bulk-add (distinct from bulk-create) view testing; self.bulk_create_data will be used if unset.

#### `test_bulk_add_component()`

Test bulk-adding this component to devices/virtual-machines.

Source code in `nautobot/utilities/testing/views.py`

    1397
    1398
    1399
    1400
    1401
    1402
    1403
    1404
    1405
    1406
    1407
    1408
    1409
    1410
    1411
    1412
    1413
    1414
    1415
    1416
    1417
    1418
    1419
    1420
    1421
    1422
    1423
    1424
    1425
    1426
    1427
    1428
    1429
    1430
    1431
    1432
    1433
    1434
    1435
    1436
    1437
    1438
    1439
    1440
    1441
    1442
    1443
    @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
    def test_bulk_add_component(self):
        """Test bulk-adding this component to devices/virtual-machines."""
        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()

        data = (self.bulk_add_data or self.bulk_create_data).copy()

        # Load the device-bulk-add or virtualmachine-bulk-add form
        if "device" in data:
            url = reverse(f"dcim:device_bulk_add_{self.model._meta.model_name}")
            request = {
                "path": url,
                "data": post_data({"pk": data["device"]}),
            }
        else:
            url = reverse(f"virtualization:virtualmachine_bulk_add_{self.model._meta.model_name}")
            request = {
                "path": url,
                "data": post_data({"pk": data["virtual_machine"]}),
            }
        self.assertHttpStatus(self.client.post(**request), 200)

        # Post to the device-bulk-add or virtualmachine-bulk-add form to create records
        if "device" in data:
            data["pk"] = data.pop("device")
        else:
            data["pk"] = data.pop("virtual_machine")
        data["_create"] = ""
        request["data"] = post_data(data)
        self.assertHttpStatus(self.client.post(**request), 302)

        updated_count = self._get_queryset().count()
        self.assertEqual(updated_count, initial_count + self.bulk_create_count)

        matching_count = 0
        for instance in self._get_queryset().all():
            try:
                self.assertInstanceEqual(instance, (self.bulk_add_data or self.bulk_create_data))
                matching_count += 1
            except AssertionError:
                pass
        self.assertEqual(matching_count, self.bulk_create_count)

### `EditObjectViewTestCase`

Bases: `ModelViewTestCase`

Edit a single existing instance.

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

Source code in `nautobot/utilities/testing/views.py`

    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
    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)

### `GetObjectChangelogViewTestCase`

Bases: `ModelViewTestCase`

View the changelog for an instance.

Source code in `nautobot/utilities/testing/views.py`

    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    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)

### `GetObjectNotesViewTestCase`

Bases: `ModelViewTestCase`

View the notes for an instance.

Source code in `nautobot/utilities/testing/views.py`

    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    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)

### `GetObjectViewTestCase`

Bases: `ModelViewTestCase`

Retrieve a single instance.

Source code in `nautobot/utilities/testing/views.py`

    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
    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(escape(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(
                            escape(relationship.get_label(RelationshipSideChoices.SIDE_SOURCE)),
                            response_body,
                            msg=response_body,
                        )
                    if content_type == relationship.destination_type:
                        self.assertIn(
                            escape(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(escape(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(escape(str(value)), response_body, msg=response_body)
                    else:
                        self.assertIn(
                            escape(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)

### `ListObjectsViewTestCase`

Bases: `ModelViewTestCase`

Retrieve multiple instances.

Source code in `nautobot/utilities/testing/views.py`

    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
    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"):
                self.assertRegex(content, r">\s*" + re.escape(escape(instance1.name)) + r"\s*<", msg=content)
                self.assertNotRegex(content, r">\s*" + re.escape(escape(instance2.name)) + r"\s*<", msg=content)
            try:
                self.assertIn(self._get_url("view", instance=instance1), content, msg=content)
                self.assertNotIn(self._get_url("view", instance=instance2), content, msg=content)
            except NoReverseMatch:
                pass

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"], STRICT_FILTERING=True)
        def test_list_objects_unknown_filter_strict_filtering(self):
            """Verify that with STRICT_FILTERING, an unknown filter results in an error message and no matches."""
            response = self.client.get(f"{self._get_url('list')}?ice_cream_flavor=chocolate")
            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
            self.assertIn("Unknown filter field", content, msg=content)
            # There should be no table rows displayed except for the empty results row
            self.assertIn(f"No {self.model._meta.verbose_name_plural} found", content, msg=content)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"], STRICT_FILTERING=False)
        def test_list_objects_unknown_filter_no_strict_filtering(self):
            """Verify that without STRICT_FILTERING, an unknown filter is ignored."""
            instance1, instance2 = self._get_queryset().all()[:2]
            with self.assertLogs("nautobot.utilities.filters") as cm:
                response = self.client.get(f"{self._get_url('list')}?ice_cream_flavor=chocolate")
            filterset = self.get_filterset()
            if not filterset:
                self.fail(
                    f"Couldn't find filterset for model {self.model}. The FilterSet class is expected to be in the "
                    "filters module within the application associated with the model and its name is expected to be "
                    f"{self.model.__name__}FilterSet."
                )
            self.assertEqual(
                cm.output,
                [
                    f"WARNING:nautobot.utilities.filters:{filterset.__name__}: "
                    'Unknown filter field "ice_cream_flavor"',
                ],
            )
            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
            self.assertNotIn("Unknown filter field", content, msg=content)
            self.assertNotIn(f"No {self.model._meta.verbose_name_plural} found", content, msg=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(escape(instance1.name), content, msg=content)
                self.assertIn(escape(instance2.name), content, msg=content)
            try:
                self.assertIn(self._get_url("view", instance=instance1), content, msg=content)
                self.assertIn(self._get_url("view", instance=instance2), content, msg=content)
            except NoReverseMatch:
                pass

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_without_permission(self):
            # Try GET without permission
            with disable_warnings("django.request"):
                response = self.client.get(self._get_url("list"))
                self.assertHttpStatus(response, 403)
                response_body = response.content.decode(response.charset)
                self.assertNotIn("/login/", response_body, msg=response_body)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_with_permission(self):
            # 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(self._get_url("list"))
            self.assertHttpStatus(response, 200)
            response_body = response.content.decode(response.charset)

            list_url = self.get_list_url()
            title = self.get_title()

            # Check if breadcrumb is rendered correctly
            self.assertIn(
                f'<a href="{list_url}">{title}</a>',
                response_body,
            )

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_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},
                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 object-level permission
            response = self.client.get(self._get_url("list"))
            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"):
                self.assertIn(escape(instance1.name), content, msg=content)
                self.assertNotIn(escape(instance2.name), content, msg=content)
            elif hasattr(self.model, "get_absolute_url"):
                self.assertIn(instance1.get_absolute_url(), content, msg=content)
                self.assertNotIn(instance2.get_absolute_url(), content, msg=content)

        @skipIf(
            "example_plugin" not in settings.PLUGINS,
            "example_plugin not in settings.PLUGINS",
        )
        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_view_plugin_banner(self):
            """
            If example plugin is installed, check if the plugin banner is rendered correctly in ObjectListView.
            """
            # 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(self._get_url("list"))
            self.assertHttpStatus(response, 200)
            response_body = response.content.decode(response.charset)

            # Check plugin banner is rendered correctly
            self.assertIn(
                f"<div>You are viewing a table of {self.model._meta.verbose_name_plural}</div>", response_body
            )

        @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
        def test_queryset_to_csv(self):
            # Built-in CSV export
            if not hasattr(self.model, "csv_headers"):
                self.skipTest(f"{self.model} has no csv_headers attribute?")
            response = self.client.get(f"{self._get_url('list')}?export")
            self.assertHttpStatus(response, 200)
            self.assertEqual(response.get("Content-Type"), "text/csv")
            instance1 = self._get_queryset().first()
            # With filtering
            response = self.client.get(f"{self._get_url('list')}?export&id={instance1.pk}")
            self.assertHttpStatus(response, 200)
            self.assertEqual(response.get("Content-Type"), "text/csv")
            response_body = response.content.decode(response.charset)
            reader = csv.DictReader(StringIO(response_body))
            # This line will make data a dictionary with csv headers as keys and corresponding csv values as values.
            # For example:
            # {'name': 'AFRINIC', 'slug': 'afrinic', 'is_private': '', 'description': ...'}
            data = [dict(row) for row in reader][0]

            # Get expected data
            instance1_unformatted_data = [
                *instance1.to_csv(),
                *instance1.get_custom_fields().values(),
            ]
            # Format expected data using `csv_format`, parse back with `csv` and get first row
            instance1_csv_data = next(iter(csv.reader([csv_format(instance1_unformatted_data)])))

            instance1_cf_headers = ["cf_" + str(cf.slug) for cf in instance1.get_custom_fields().keys()]
            instance1_csv_headers = list(self.model.csv_headers) + instance1_cf_headers
            self.assertEqual(instance1_csv_headers, list(data.keys()))
            self.assertEqual(instance1_csv_data, list(data.values()))

#### `test_list_objects_unknown_filter_no_strict_filtering()`

Verify that without STRICT_FILTERING, an unknown filter is ignored.

Source code in `nautobot/utilities/testing/views.py`

    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
    @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"], STRICT_FILTERING=False)
    def test_list_objects_unknown_filter_no_strict_filtering(self):
        """Verify that without STRICT_FILTERING, an unknown filter is ignored."""
        instance1, instance2 = self._get_queryset().all()[:2]
        with self.assertLogs("nautobot.utilities.filters") as cm:
            response = self.client.get(f"{self._get_url('list')}?ice_cream_flavor=chocolate")
        filterset = self.get_filterset()
        if not filterset:
            self.fail(
                f"Couldn't find filterset for model {self.model}. The FilterSet class is expected to be in the "
                "filters module within the application associated with the model and its name is expected to be "
                f"{self.model.__name__}FilterSet."
            )
        self.assertEqual(
            cm.output,
            [
                f"WARNING:nautobot.utilities.filters:{filterset.__name__}: "
                'Unknown filter field "ice_cream_flavor"',
            ],
        )
        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
        self.assertNotIn("Unknown filter field", content, msg=content)
        self.assertNotIn(f"No {self.model._meta.verbose_name_plural} found", content, msg=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(escape(instance1.name), content, msg=content)
            self.assertIn(escape(instance2.name), content, msg=content)
        try:
            self.assertIn(self._get_url("view", instance=instance1), content, msg=content)
            self.assertIn(self._get_url("view", instance=instance2), content, msg=content)
        except NoReverseMatch:
            pass

#### `test_list_objects_unknown_filter_strict_filtering()`

Verify that with STRICT_FILTERING, an unknown filter results in an error message and no matches.

Source code in `nautobot/utilities/testing/views.py`

    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"], STRICT_FILTERING=True)
    def test_list_objects_unknown_filter_strict_filtering(self):
        """Verify that with STRICT_FILTERING, an unknown filter results in an error message and no matches."""
        response = self.client.get(f"{self._get_url('list')}?ice_cream_flavor=chocolate")
        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
        self.assertIn("Unknown filter field", content, msg=content)
        # There should be no table rows displayed except for the empty results row
        self.assertIn(f"No {self.model._meta.verbose_name_plural} found", content, msg=content)

#### `test_list_view_plugin_banner()`

If example plugin is installed, check if the plugin banner is rendered correctly in ObjectListView.

Source code in `nautobot/utilities/testing/views.py`

    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    @skipIf(
        "example_plugin" not in settings.PLUGINS,
        "example_plugin not in settings.PLUGINS",
    )
    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_list_view_plugin_banner(self):
        """
        If example plugin is installed, check if the plugin banner is rendered correctly in ObjectListView.
        """
        # 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(self._get_url("list"))
        self.assertHttpStatus(response, 200)
        response_body = response.content.decode(response.charset)

        # Check plugin banner is rendered correctly
        self.assertIn(
            f"<div>You are viewing a table of {self.model._meta.verbose_name_plural}</div>", response_body
        )

### `OrganizationalObjectViewTestCase`

Bases: `GetObjectViewTestCase`, `GetObjectChangelogViewTestCase`, `GetObjectNotesViewTestCase`, `CreateObjectViewTestCase`, `EditObjectViewTestCase`, `DeleteObjectViewTestCase`, `ListObjectsViewTestCase`, `BulkImportObjectsViewTestCase`, `BulkDeleteObjectsViewTestCase`

TestCase suitable for all organizational objects

Source code in `nautobot/utilities/testing/views.py`

    1345
    1346
    1347
    1348
    1349
    1350
    1351
    1352
    1353
    1354
    1355
    1356
    1357
    1358
    1359
    1360
    class OrganizationalObjectViewTestCase(
        GetObjectViewTestCase,
        GetObjectChangelogViewTestCase,
        GetObjectNotesViewTestCase,
        CreateObjectViewTestCase,
        EditObjectViewTestCase,
        DeleteObjectViewTestCase,
        ListObjectsViewTestCase,
        BulkImportObjectsViewTestCase,
        BulkDeleteObjectsViewTestCase,
    ):
        """
        TestCase suitable for all organizational objects
        """

        maxDiff = None

### `PrimaryObjectViewTestCase`

Bases: `GetObjectViewTestCase`, `GetObjectChangelogViewTestCase`, `GetObjectNotesViewTestCase`, `CreateObjectViewTestCase`, `EditObjectViewTestCase`, `DeleteObjectViewTestCase`, `ListObjectsViewTestCase`, `BulkImportObjectsViewTestCase`, `BulkEditObjectsViewTestCase`, `BulkDeleteObjectsViewTestCase`

TestCase suitable for testing all standard View functions for primary objects

Source code in `nautobot/utilities/testing/views.py`

    1327
    1328
    1329
    1330
    1331
    1332
    1333
    1334
    1335
    1336
    1337
    1338
    1339
    1340
    1341
    1342
    1343
    class PrimaryObjectViewTestCase(
        GetObjectViewTestCase,
        GetObjectChangelogViewTestCase,
        GetObjectNotesViewTestCase,
        CreateObjectViewTestCase,
        EditObjectViewTestCase,
        DeleteObjectViewTestCase,
        ListObjectsViewTestCase,
        BulkImportObjectsViewTestCase,
        BulkEditObjectsViewTestCase,
        BulkDeleteObjectsViewTestCase,
    ):
        """
        TestCase suitable for testing all standard View functions for primary objects
        """

        maxDiff = None