nautobot.apps.testing - Nautobot Documentation

Skip to content

# `nautobot.apps.testing`

Utilities for apps to implement test automation.

## `nautobot.apps.testing.APITestCase`

Bases: `views.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/core/testing/api.py`

    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
    @tag("api")
    class APITestCase(views.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 = users_models.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 = lookup.get_route_for_model(instance, "detail", api=True)
            return reverse(viewname, kwargs={"pk": instance.pk})

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

        VERBOTEN_STRINGS = (
            "password",
            # https://docs.djangoproject.com/en/3.2/topics/auth/passwords/#included-hashers
            "argon2",
            "bcrypt",
            "crypt",
            "md5",
            "pbkdf2",
            "scrypt",
            "sha1",
            "sha256",
            "sha512",
        )

        def assert_no_verboten_content(self, response):
            """
            Check an API response for content that should not be exposed in the API.

            If a specific API has a false failure here (maybe it has security-related strings as model flags or something?),
            its test case should overload self.VERBOTEN_STRINGS appropriately.
            """
            response_raw_content = response.content.decode(response.charset)
            for verboten in self.VERBOTEN_STRINGS:
                self.assertNotIn(verboten, response_raw_content)

### `assert_no_verboten_content(response)`

Check an API response for content that should not be exposed in the API.

If a specific API has a false failure here (maybe it has security-related strings as model flags or something?), its test case should overload self.VERBOTEN_STRINGS appropriately.

Source code in `nautobot/core/testing/api.py`

    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    def assert_no_verboten_content(self, response):
        """
        Check an API response for content that should not be exposed in the API.

        If a specific API has a false failure here (maybe it has security-related strings as model flags or something?),
        its test case should overload self.VERBOTEN_STRINGS appropriately.
        """
        response_raw_content = response.content.decode(response.charset)
        for verboten in self.VERBOTEN_STRINGS:
            self.assertNotIn(verboten, response_raw_content)

### `setUp()`

Create a token for API calls.

Source code in `nautobot/core/testing/api.py`

    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    def setUp(self):
        """
        Create a token for API calls.
        """
        super().setUp()
        self.client.logout()
        self.token = users_models.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/core/testing/api.py`

    59
    60
    61
    62
    63
    64
    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.APITransactionTestCase`

Bases: `_APITransactionTestCase`, `mixins.NautobotTestCaseMixin`

Source code in `nautobot/core/testing/api.py`

    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    @tag("unit")
    class APITransactionTestCase(_APITransactionTestCase, mixins.NautobotTestCaseMixin):
        def setUp(self):
            """
            Create a superuser and token for API calls.
            """
            super().setUpNautobot(populate_status=True)
            self.user.is_superuser = True
            self.user.save()
            self.token = users_models.Token.objects.create(user=self.user)
            self.header = {"HTTP_AUTHORIZATION": f"Token {self.token.key}"}

### `setUp()`

Create a superuser and token for API calls.

Source code in `nautobot/core/testing/api.py`

    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    def setUp(self):
        """
        Create a superuser and token for API calls.
        """
        super().setUpNautobot(populate_status=True)
        self.user.is_superuser = True
        self.user.save()
        self.token = users_models.Token.objects.create(user=self.user)
        self.header = {"HTTP_AUTHORIZATION": f"Token {self.token.key}"}

## `nautobot.apps.testing.APIViewTestCases`

Source code in `nautobot/core/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
     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
    @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 testing.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 testing.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 = users_models.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.assertIn("natural_slug", response.data)
                self.assertIsInstance(response.data["display"], str)
                # Fields that should be present in appropriate model serializers:
                if issubclass(self.model, extras_models.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)
                # Content that should never be present:
                self.assert_no_verboten_content(response)

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

                custom_fields_registry = 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.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)

                with self.subTest("Assert Detail View Config is generated well"):
                    # Namings Help
                    # 1. detail_view_config: This is the detail view config set in the serializer.Meta.detail_view_config
                    # 2. detail_view_schema: This is the retrieve schema generated from an OPTIONS request.
                    # 3. advanced_view_schema: This is the advanced tab schema generated from an OPTIONS request.
                    serializer = get_serializer_for_model(self._get_queryset().model)
                    advanced_view_schema = response.data["view_options"]["retrieve"]["tabs"]["Advanced"]

                    # Get default advanced tab fields
                    self.assertEqual(len(advanced_view_schema), 1)
                    self.assertIn("Object Details", advanced_view_schema[0])
                    advanced_tab_fields = advanced_view_schema[0].get("Object Details")["fields"]

                    if detail_view_config := getattr(serializer.Meta, "detail_view_config", None):
                        detail_view_schema = response.data["view_options"]["retrieve"]["tabs"][
                            bettertitle(self._get_queryset().model._meta.verbose_name)
                        ]
                        self.assertHttpStatus(response, status.HTTP_200_OK)

                        # According to convention, fields in the advanced tab fields should not exist in
                        # the `detail_view_schema`. Assert this is True.
                        with self.subTest("Assert advanced tab fields should not exist in the detail_view_schema."):
                            if detail_view_config.get("include_others"):
                                # Handle "Other Fields" section specially as "Other Field" is dynamically added
                                # by Nautobot and is not part of the serializer-defined detail_view_config
                                other_fields = detail_view_schema[0]["Other Fields"]["fields"]
                                for field in advanced_tab_fields:
                                    self.assertNotIn(field, other_fields)

                            for col_idx, col in enumerate(detail_view_schema):
                                for group_title, group in col.items():
                                    if group_title == "Other Fields":
                                        continue
                                    group_fields = group["fields"]
                                    # Config on the serializer
                                    if (
                                        col_idx < len(detail_view_config["layout"])
                                        and group_title in detail_view_config["layout"][col_idx]
                                    ):
                                        fields = detail_view_config["layout"][col_idx][group_title]["fields"]
                                    else:
                                        fields = []

                                    # Fields that are in the detail_view_schema must not be in the advanced tab as well
                                    for field in group_fields:
                                        self.assertNotIn(field, advanced_tab_fields)

                                    # Fields that are explicit in the detail_view_config must remain as such in the schema
                                    for field in fields:
                                        if field not in advanced_tab_fields:
                                            self.assertIn(field, group_fields)

        class ListObjectsViewTestCase(APITestCase):
            choices_fields = None
            filterset = None

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

            def get_depth_fields(self):
                """Get a list of model fields that could be tested with the ?depth query parameter"""
                depth_fields = []
                for field in self.model._meta.fields:
                    if not field.name.startswith("_"):
                        if isinstance(field, (ForeignKey, GenericForeignKey, ManyToManyField, core_fields.TagsField)) and (
                            # we represent content-types as "app_label.modelname" rather than as FKs
                            field.related_model != ContentType
                            # user is a model field on Token but not a field on TokenSerializer
                            and not (field.name == "user" and self.model == users_models.Token)
                        ):
                            depth_fields.append(field.name)
                return depth_fields

            @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 testing.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_depth_0(self):
                """
                GET a list of objects using the "?depth=0" parameter.
                """
                depth_fields = self.get_depth_fields()
                self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
                url = f"{self._get_list_url()}?depth=0"
                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.assert_no_verboten_content(response)

                for response_data in response.data["results"]:
                    for field in depth_fields:
                        self.assertIn(field, response_data)
                        if isinstance(response_data[field], list):
                            for entry in response_data[field]:
                                self.assertIsInstance(entry, dict)
                                self.assertTrue(is_uuid(entry["id"]))
                        else:
                            if response_data[field] is not None:
                                self.assertIsInstance(response_data[field], dict)
                                url = response_data[field]["url"]
                                pk = response_data[field]["id"]
                                object_type = response_data[field]["object_type"]
                                # The response should be a brief API object, containing an ID, object_type, and a
                                # URL ending in the UUID of the relevant object:
                                # http://nautobot.example.com/api/circuits/providers/<uuid>/
                                #                                                    ^^^^^^
                                self.assertTrue(is_uuid(url.split("/")[-2]))
                                self.assertTrue(is_uuid(pk))

                                with self.subTest(f"Assert object_type {object_type} is valid"):
                                    app_label, model_name = object_type.split(".")
                                    ContentType.objects.get(app_label=app_label, model=model_name)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_list_objects_depth_1(self):
                """
                GET a list of objects using the "?depth=1" parameter.
                """
                depth_fields = self.get_depth_fields()
                self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
                url = f"{self._get_list_url()}?depth=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.assert_no_verboten_content(response)

                for response_data in response.data["results"]:
                    for field in depth_fields:
                        self.assertIn(field, response_data)
                        if isinstance(response_data[field], list):
                            for entry in response_data[field]:
                                self.assertIsInstance(entry, dict)
                                self.assertTrue(is_uuid(entry["id"]))
                        else:
                            if response_data[field] is not None:
                                self.assertIsInstance(response_data[field], dict)
                                self.assertTrue(is_uuid(response_data[field]["id"]))

            @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 testing.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 = users_models.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)
                self.assert_no_verboten_content(response)

            @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=[])
            def test_list_objects_ascending_ordered(self):
                # Simple sorting check for models with a "name" field
                # TreeModels don't support sorting at this time (order_by is not supported by TreeQuerySet)
                #   They will pass api == queryset tests below but will fail the user expected sort test
                if hasattr(self.model, "name") and not issubclass(self.model, TreeModel):
                    self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
                    response = self.client.get(f"{self._get_list_url()}?sort=name&limit=3", **self.header)
                    self.assertHttpStatus(response, status.HTTP_200_OK)
                    result_list = list(map(lambda p: p["name"], response.data["results"]))
                    self.assertEqual(
                        result_list,
                        list(self._get_queryset().order_by("name").values_list("name", flat=True)[:3]),
                        "API sort not identical to QuerySet.order_by",
                    )

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_list_objects_descending_ordered(self):
                # Simple sorting check for models with a "name" field
                # TreeModels don't support sorting at this time (order_by is not supported by TreeQuerySet)
                #   They will pass api == queryset tests below but will fail the user expected sort test
                if hasattr(self.model, "name") and not issubclass(self.model, TreeModel):
                    self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
                    response = self.client.get(f"{self._get_list_url()}?sort=-name&limit=3", **self.header)
                    self.assertHttpStatus(response, status.HTTP_200_OK)
                    result_list = list(map(lambda p: p["name"], response.data["results"]))
                    self.assertEqual(
                        result_list,
                        list(self._get_queryset().order_by("-name").values_list("name", flat=True)[:3]),
                        "API sort not identical to QuerySet.order_by",
                    )

                    response_ascending = self.client.get(f"{self._get_list_url()}?sort=name&limit=3", **self.header)
                    self.assertHttpStatus(response, status.HTTP_200_OK)
                    result_list_ascending = list(map(lambda p: p["name"], response_ascending.data["results"]))

                    self.assertNotEqual(
                        result_list,
                        result_list_ascending,
                        "Same results obtained when sorting by name and by -name (QuerySet not ordering)",
                    )

            @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 testing.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.core.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.core.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_list_objects_csv(self):
                """
                GET a list of objects in CSV format as an authenticated user with permission to view some objects.
                """
                self.assertGreaterEqual(
                    self._get_queryset().count(),
                    3,
                    f"Test requires the creation of at least three {self.model} instances",
                )
                instance1, instance2, instance3 = self._get_queryset()[:3]

                # Add object-level permission
                obj_perm = users_models.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 filtered GET to objects specifying CSV format as a query parameter
                response_1 = self.client.get(
                    f"{self._get_list_url()}?format=csv&id={instance1.pk}&id={instance3.pk}", **self.header
                )
                self.assertHttpStatus(response_1, status.HTTP_200_OK)
                self.assertEqual(response_1.get("Content-Type"), "text/csv; charset=UTF-8")
                self.assertEqual(
                    response_1.get("Content-Disposition"),
                    f'attachment; filename="nautobot_{self.model.__name__.lower()}_data.csv"',
                )

                # Try same request specifying CSV format via the ACCEPT header
                response_2 = self.client.get(
                    f"{self._get_list_url()}?id={instance1.pk}&id={instance3.pk}", **self.header, HTTP_ACCEPT="text/csv"
                )
                self.assertHttpStatus(response_2, status.HTTP_200_OK)
                self.assertEqual(response_2.get("Content-Type"), "text/csv; charset=UTF-8")
                self.assertEqual(
                    response_2.get("Content-Disposition"),
                    f'attachment; filename="nautobot_{self.model.__name__.lower()}_data.csv"',
                )

                self.maxDiff = None
                # This check is more useful than it might seem. Any related object that wasn't CSV-converted correctly
                # will likely be rendered incorrectly as an API URL, and that API URL *will* differ between the
                # two responses based on the inclusion or omission of the "?format=csv" parameter. If
                # you run into this, make sure all serializers have `Meta.fields = "__all__"` set.
                self.assertEqual(
                    response_1.content.decode(response_1.charset), response_2.content.decode(response_2.charset)
                )

                # Load the csv data back into a list of object dicts
                reader = csv.DictReader(StringIO(response_1.content.decode(response_1.charset)))
                rows = list(reader)
                # Should only have one entry (instance1) since we filtered out instance2 and permissions block instance3
                self.assertEqual(1, len(rows))
                self.assertEqual(rows[0]["id"], str(instance1.pk))
                self.assertEqual(rows[0]["display"], getattr(instance1, "display", str(instance1)))
                if hasattr(self.model, "_custom_field_data"):
                    custom_fields = extras_models.CustomField.objects.get_for_model(self.model)
                    for cf in custom_fields:
                        self.assertIn(f"cf_{cf.key}", rows[0])
                        self.assertEqual(rows[0][f"cf_{cf.key}"], instance1._custom_field_data.get(cf.key) or "")
                # TODO what other generic tests should we run on the data?

        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 testing.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, "")
                if hasattr(obj, "slug"):
                    self.assertEqual(obj.slug, expected_slug)
                else:
                    self.assertEqual(obj.key, expected_slug)

            def test_create_object(self):
                """
                POST a single object with permission.
                """
                # Add object-level permission
                obj_perm = users_models.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):
                    if i == len(self.create_data) - 1:
                        # Test to see if depth parameter is ignored in POST request.
                        response = self.client.post(
                            self._get_list_url() + "?depth=3", create_data, format="json", **self.header
                        )
                    else:
                        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 = lookup.get_changes_for_model(instance)
                        self.assertEqual(len(objectchanges), 1)
                        self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_CREATE)

            def test_recreate_object_csv(self):
                """CSV export an object, delete it, and recreate it via CSV import."""
                if hasattr(self, "get_deletable_object"):
                    # provided by DeleteObjectViewTestCase mixin
                    instance = self.get_deletable_object()
                else:
                    # try to do it ourselves
                    instance = testing.get_deletable_objects(self.model, self._get_queryset()).first()
                if instance is None:
                    self.fail("Couldn't find a single deletable object!")

                # Add object-level permission
                obj_perm = users_models.ObjectPermission(name="Test permission", actions=["add", "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(self._get_detail_url(instance) + "?format=csv", **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                self.assertEqual(
                    response.get("Content-Disposition"),
                    f'attachment; filename="nautobot_{self.model.__name__.lower()}_data.csv"',
                )
                csv_data = response.content.decode(response.charset)

                serializer_class = get_serializer_for_model(self.model)
                old_serializer = serializer_class(instance, context={"request": None})
                old_data = old_serializer.data
                instance.delete()

                response = self.client.post(self._get_list_url(), csv_data, content_type="text/csv", **self.header)
                self.assertHttpStatus(response, status.HTTP_201_CREATED, csv_data)
                # Note that create via CSV is always treated as a bulk-create, and so the response is always a list of dicts
                new_instance = self._get_queryset().get(pk=response.data[0]["id"])
                self.assertNotEqual(new_instance.pk, instance.pk)

                new_serializer = serializer_class(new_instance, context={"request": None})
                new_data = new_serializer.data
                for field_name, field in new_serializer.fields.items():
                    # Skip M2M fields except for tags because M2M fields are not supported in CSV Export/Import;
                    if isinstance(field, ManyRelatedField) and field_name != "tags":
                        continue
                    if field.read_only or field.write_only:
                        continue
                    if field_name in ["created", "last_updated"]:
                        self.assertNotEqual(
                            old_data[field_name],
                            new_data[field_name],
                            f"{field_name} should have been updated on delete/recreate but it didn't change!",
                        )
                    else:
                        self.assertEqual(
                            old_data[field_name],
                            new_data[field_name],
                            f"{field_name} should have been unchanged on delete/recreate but it differs!",
                        )

            def test_bulk_create_objects(self):
                """
                POST a set of objects in a single request.
                """
                # Add object-level permission
                obj_perm = users_models.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 testing.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.
                """

                def strip_serialized_object(this_object):
                    """
                    Only here to work around acceptable differences in PATCH response vs GET response which are known bugs.
                    """
                    # Work around for https://github.com/nautobot/nautobot/issues/3321
                    this_object.pop("last_updated", None)
                    # PATCH response always includes "opt-in" fields, but GET response does not.
                    this_object.pop("computed_fields", None)
                    this_object.pop("config_context", None)
                    this_object.pop("relationships", None)

                    for value in this_object.values():
                        if isinstance(value, dict):
                            strip_serialized_object(value)
                        elif isinstance(value, list):
                            for list_dict in value:
                                if isinstance(list_dict, dict):
                                    strip_serialized_object(list_dict)

                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 = users_models.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()
                strip_serialized_object(initial_serialized_object)

                # 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()
                strip_serialized_object(serialized_object)
                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 = lookup.get_changes_for_model(instance)
                    self.assertEqual(len(objectchanges), 1)
                    self.assertEqual(objectchanges[0].action, extras_choices.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 = lookup.get_changes_for_model(instance)
                    self.assertEqual(len(objectchanges), 1)
                    self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_UPDATE)

            def test_get_put_round_trip(self):
                """GET and then PUT an object and verify that it's accepted and unchanged."""
                self.maxDiff = None
                # Add object-level permission
                obj_perm = users_models.ObjectPermission(name="Test permission", actions=["view", "change"])
                obj_perm.save()
                obj_perm.users.add(self.user)
                obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

                instance = self._get_queryset().first()
                url = self._get_detail_url(instance)

                # GET object representation
                opt_in_fields = getattr(get_serializer_for_model(self.model).Meta, "opt_in_fields", None)
                if opt_in_fields:
                    url += "?" + "&".join([f"include={field}" for field in opt_in_fields])
                get_response = self.client.get(url, **self.header)
                self.assertHttpStatus(get_response, status.HTTP_200_OK)
                initial_serialized_object = get_response.json()

                # PUT same object representation
                put_response = self.client.put(url, initial_serialized_object, format="json", **self.header)
                self.assertHttpStatus(put_response, status.HTTP_200_OK, initial_serialized_object)
                updated_serialized_object = put_response.json()

                # Work around for https://github.com/nautobot/nautobot/issues/3321
                initial_serialized_object.pop("last_updated", None)
                updated_serialized_object.pop("last_updated", None)
                self.assertEqual(initial_serialized_object, updated_serialized_object)

            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 = users_models.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_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 that has choices defined (fields with enums)
                if any(
                    [
                        "POST" in data["actions"],
                        "PUT" in data["actions"],
                    ]
                ):
                    schema = data["schema"]
                    props = schema["properties"]
                    fields = props.keys()
                    field_choices = set()
                    for field_name in fields:
                        obj = props[field_name]
                        if "enum" in obj and "enumNames" in obj:
                            enum = obj["enum"]
                            # Zipping to assert that the enum and the mapping have the same number of items.
                            model_field_choices = dict(zip(obj["enumNames"], enum))
                            self.assertEqual(len(enum), len(model_field_choices))
                            field_choices.add(field_name)
                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 = testing.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 = testing.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 testing.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 = users_models.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 = lookup.get_changes_for_model(instance)
                    self.assertEqual(len(objectchanges), 1)
                    self.assertEqual(objectchanges[0].action, extras_choices.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 = users_models.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 not hasattr(self.model, "notes"):
                    self.skipTest("Model doesn't appear to support Notes")
                instance = self._get_queryset().first()
                if not isinstance(instance.notes, QuerySet):
                    self.skipTest("Model has a notes field but it doesn't appear to be Notes")

                # Add object-level permission
                obj_perm = users_models.ObjectPermission(
                    name="Test permission",
                    constraints={"pk": instance.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(instance)
                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"]))
                self.assertIn(instance.get_notes_url(api=True), str(response.data["notes_url"]))

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_notes_url_functionality(self):
                if not hasattr(self.model, "notes"):
                    self.skipTest("Model doesn't appear to support Notes")
                instance = self._get_queryset().first()
                if not isinstance(instance.notes, QuerySet):
                    self.skipTest("Model has a notes field but it doesn't appear to be Notes")

                self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
                self.add_permissions("extras.add_note")

                # Add note via REST API
                notes_url = instance.get_notes_url(api=True)
                response = self.client.post(
                    notes_url,
                    {"note": f"This is a note for {instance}"},
                    format="json",
                    **self.header,
                )
                self.assertHttpStatus(response, status.HTTP_201_CREATED)
                self.assertIsInstance(response.data, dict)
                self.assertEqual(f"This is a note for {instance}", response.data["note"])
                self.assertEqual(str(self.user.pk), str(response.data["user"]["id"]))
                self.assertEqual(str(instance.pk), str(response.data["assigned_object_id"]))
                self.assertEqual(str(instance.pk), str(response.data["assigned_object"]["id"]))

                # Get note via REST API
                response = self.client.get(notes_url, format="json", **self.header)
                self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

                self.add_permissions("extras.view_note")
                response = self.client.get(notes_url, format="json", **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                self.assertEqual(f"This is a note for {instance}", response.data["results"][0]["note"])

        class TreeModelAPIViewTestCaseMixin:
            """Test `?depth=2` query parameter for TreeModel"""

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_list_objects_depth_2(self):
                """
                GET a list of objects using the "?depth=2" parameter.
                TreeModel Only
                """
                field = "parent"

                self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
                url = f"{self._get_list_url()}?depth=2"
                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())

                response_data = response.data["results"]
                for data in response_data:
                    # First Level Parent
                    self.assertEqual(field in data, True)
                    if data[field] is not None:
                        self.assertIsInstance(data[field], dict)
                        self.assertTrue(is_uuid(data[field]["id"]))
                        # Second Level Parent
                        self.assertIn(field, data[field])
                        if data[field][field] is not None:
                            self.assertIsInstance(data[field][field], dict)
                            self.assertTrue(is_uuid(data[field][field]["id"]))

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

### `CreateObjectViewTestCase`

Bases: `APITestCase`

Source code in `nautobot/core/testing/api.py`

    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
    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 testing.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, "")
            if hasattr(obj, "slug"):
                self.assertEqual(obj.slug, expected_slug)
            else:
                self.assertEqual(obj.key, expected_slug)

        def test_create_object(self):
            """
            POST a single object with permission.
            """
            # Add object-level permission
            obj_perm = users_models.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):
                if i == len(self.create_data) - 1:
                    # Test to see if depth parameter is ignored in POST request.
                    response = self.client.post(
                        self._get_list_url() + "?depth=3", create_data, format="json", **self.header
                    )
                else:
                    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 = lookup.get_changes_for_model(instance)
                    self.assertEqual(len(objectchanges), 1)
                    self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_CREATE)

        def test_recreate_object_csv(self):
            """CSV export an object, delete it, and recreate it via CSV import."""
            if hasattr(self, "get_deletable_object"):
                # provided by DeleteObjectViewTestCase mixin
                instance = self.get_deletable_object()
            else:
                # try to do it ourselves
                instance = testing.get_deletable_objects(self.model, self._get_queryset()).first()
            if instance is None:
                self.fail("Couldn't find a single deletable object!")

            # Add object-level permission
            obj_perm = users_models.ObjectPermission(name="Test permission", actions=["add", "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(self._get_detail_url(instance) + "?format=csv", **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertEqual(
                response.get("Content-Disposition"),
                f'attachment; filename="nautobot_{self.model.__name__.lower()}_data.csv"',
            )
            csv_data = response.content.decode(response.charset)

            serializer_class = get_serializer_for_model(self.model)
            old_serializer = serializer_class(instance, context={"request": None})
            old_data = old_serializer.data
            instance.delete()

            response = self.client.post(self._get_list_url(), csv_data, content_type="text/csv", **self.header)
            self.assertHttpStatus(response, status.HTTP_201_CREATED, csv_data)
            # Note that create via CSV is always treated as a bulk-create, and so the response is always a list of dicts
            new_instance = self._get_queryset().get(pk=response.data[0]["id"])
            self.assertNotEqual(new_instance.pk, instance.pk)

            new_serializer = serializer_class(new_instance, context={"request": None})
            new_data = new_serializer.data
            for field_name, field in new_serializer.fields.items():
                # Skip M2M fields except for tags because M2M fields are not supported in CSV Export/Import;
                if isinstance(field, ManyRelatedField) and field_name != "tags":
                    continue
                if field.read_only or field.write_only:
                    continue
                if field_name in ["created", "last_updated"]:
                    self.assertNotEqual(
                        old_data[field_name],
                        new_data[field_name],
                        f"{field_name} should have been updated on delete/recreate but it didn't change!",
                    )
                else:
                    self.assertEqual(
                        old_data[field_name],
                        new_data[field_name],
                        f"{field_name} should have been unchanged on delete/recreate but it differs!",
                    )

        def test_bulk_create_objects(self):
            """
            POST a set of objects in a single request.
            """
            # Add object-level permission
            obj_perm = users_models.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/core/testing/api.py`

    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
    def test_bulk_create_objects(self):
        """
        POST a set of objects in a single request.
        """
        # Add object-level permission
        obj_perm = users_models.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/core/testing/api.py`

    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
    def test_create_object(self):
        """
        POST a single object with permission.
        """
        # Add object-level permission
        obj_perm = users_models.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):
            if i == len(self.create_data) - 1:
                # Test to see if depth parameter is ignored in POST request.
                response = self.client.post(
                    self._get_list_url() + "?depth=3", create_data, format="json", **self.header
                )
            else:
                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 = lookup.get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_CREATE)

#### `test_create_object_without_permission()`

POST a single object without permission.

Source code in `nautobot/core/testing/api.py`

    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    def test_create_object_without_permission(self):
        """
        POST a single object without permission.
        """
        url = self._get_list_url()

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

#### `test_recreate_object_csv()`

CSV export an object, delete it, and recreate it via CSV import.

Source code in `nautobot/core/testing/api.py`

    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
    def test_recreate_object_csv(self):
        """CSV export an object, delete it, and recreate it via CSV import."""
        if hasattr(self, "get_deletable_object"):
            # provided by DeleteObjectViewTestCase mixin
            instance = self.get_deletable_object()
        else:
            # try to do it ourselves
            instance = testing.get_deletable_objects(self.model, self._get_queryset()).first()
        if instance is None:
            self.fail("Couldn't find a single deletable object!")

        # Add object-level permission
        obj_perm = users_models.ObjectPermission(name="Test permission", actions=["add", "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(self._get_detail_url(instance) + "?format=csv", **self.header)
        self.assertHttpStatus(response, status.HTTP_200_OK)
        self.assertEqual(
            response.get("Content-Disposition"),
            f'attachment; filename="nautobot_{self.model.__name__.lower()}_data.csv"',
        )
        csv_data = response.content.decode(response.charset)

        serializer_class = get_serializer_for_model(self.model)
        old_serializer = serializer_class(instance, context={"request": None})
        old_data = old_serializer.data
        instance.delete()

        response = self.client.post(self._get_list_url(), csv_data, content_type="text/csv", **self.header)
        self.assertHttpStatus(response, status.HTTP_201_CREATED, csv_data)
        # Note that create via CSV is always treated as a bulk-create, and so the response is always a list of dicts
        new_instance = self._get_queryset().get(pk=response.data[0]["id"])
        self.assertNotEqual(new_instance.pk, instance.pk)

        new_serializer = serializer_class(new_instance, context={"request": None})
        new_data = new_serializer.data
        for field_name, field in new_serializer.fields.items():
            # Skip M2M fields except for tags because M2M fields are not supported in CSV Export/Import;
            if isinstance(field, ManyRelatedField) and field_name != "tags":
                continue
            if field.read_only or field.write_only:
                continue
            if field_name in ["created", "last_updated"]:
                self.assertNotEqual(
                    old_data[field_name],
                    new_data[field_name],
                    f"{field_name} should have been updated on delete/recreate but it didn't change!",
                )
            else:
                self.assertEqual(
                    old_data[field_name],
                    new_data[field_name],
                    f"{field_name} should have been unchanged on delete/recreate but it differs!",
                )

### `DeleteObjectViewTestCase`

Bases: `APITestCase`

Source code in `nautobot/core/testing/api.py`

     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
    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 = testing.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 = testing.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 testing.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 = users_models.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 = lookup.get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, extras_choices.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 = users_models.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/core/testing/api.py`

    979
    980
    981
    982
    983
    984
    985
    986
    987
    988
    989
    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 = testing.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/core/testing/api.py`

     991
     992
     993
     994
     995
     996
     997
     998
     999
    1000
    1001
    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 = testing.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/core/testing/api.py`

    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    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 = users_models.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/core/testing/api.py`

    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    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 = users_models.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 = lookup.get_changes_for_model(instance)
            self.assertEqual(len(objectchanges), 1)
            self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_DELETE)

#### `test_delete_object_without_permission()`

DELETE a single object without permission.

Source code in `nautobot/core/testing/api.py`

    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    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 testing.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/core/testing/api.py`

    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
    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 testing.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 testing.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 = users_models.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.assertIn("natural_slug", response.data)
            self.assertIsInstance(response.data["display"], str)
            # Fields that should be present in appropriate model serializers:
            if issubclass(self.model, extras_models.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)
            # Content that should never be present:
            self.assert_no_verboten_content(response)

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

            custom_fields_registry = 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.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)

            with self.subTest("Assert Detail View Config is generated well"):
                # Namings Help
                # 1. detail_view_config: This is the detail view config set in the serializer.Meta.detail_view_config
                # 2. detail_view_schema: This is the retrieve schema generated from an OPTIONS request.
                # 3. advanced_view_schema: This is the advanced tab schema generated from an OPTIONS request.
                serializer = get_serializer_for_model(self._get_queryset().model)
                advanced_view_schema = response.data["view_options"]["retrieve"]["tabs"]["Advanced"]

                # Get default advanced tab fields
                self.assertEqual(len(advanced_view_schema), 1)
                self.assertIn("Object Details", advanced_view_schema[0])
                advanced_tab_fields = advanced_view_schema[0].get("Object Details")["fields"]

                if detail_view_config := getattr(serializer.Meta, "detail_view_config", None):
                    detail_view_schema = response.data["view_options"]["retrieve"]["tabs"][
                        bettertitle(self._get_queryset().model._meta.verbose_name)
                    ]
                    self.assertHttpStatus(response, status.HTTP_200_OK)

                    # According to convention, fields in the advanced tab fields should not exist in
                    # the `detail_view_schema`. Assert this is True.
                    with self.subTest("Assert advanced tab fields should not exist in the detail_view_schema."):
                        if detail_view_config.get("include_others"):
                            # Handle "Other Fields" section specially as "Other Field" is dynamically added
                            # by Nautobot and is not part of the serializer-defined detail_view_config
                            other_fields = detail_view_schema[0]["Other Fields"]["fields"]
                            for field in advanced_tab_fields:
                                self.assertNotIn(field, other_fields)

                        for col_idx, col in enumerate(detail_view_schema):
                            for group_title, group in col.items():
                                if group_title == "Other Fields":
                                    continue
                                group_fields = group["fields"]
                                # Config on the serializer
                                if (
                                    col_idx < len(detail_view_config["layout"])
                                    and group_title in detail_view_config["layout"][col_idx]
                                ):
                                    fields = detail_view_config["layout"][col_idx][group_title]["fields"]
                                else:
                                    fields = []

                                # Fields that are in the detail_view_schema must not be in the advanced tab as well
                                for field in group_fields:
                                    self.assertNotIn(field, advanced_tab_fields)

                                # Fields that are explicit in the detail_view_config must remain as such in the schema
                                for field in fields:
                                    if field not in advanced_tab_fields:
                                        self.assertIn(field, group_fields)

#### `test_get_object()`

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

Source code in `nautobot/core/testing/api.py`

    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
    @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 = users_models.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.assertIn("natural_slug", response.data)
        self.assertIsInstance(response.data["display"], str)
        # Fields that should be present in appropriate model serializers:
        if issubclass(self.model, extras_models.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)
        # Content that should never be present:
        self.assert_no_verboten_content(response)

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

        custom_fields_registry = 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.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/core/testing/api.py`

    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    @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 testing.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/core/testing/api.py`

    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    @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 testing.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/core/testing/api.py`

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

        with self.subTest("Assert Detail View Config is generated well"):
            # Namings Help
            # 1. detail_view_config: This is the detail view config set in the serializer.Meta.detail_view_config
            # 2. detail_view_schema: This is the retrieve schema generated from an OPTIONS request.
            # 3. advanced_view_schema: This is the advanced tab schema generated from an OPTIONS request.
            serializer = get_serializer_for_model(self._get_queryset().model)
            advanced_view_schema = response.data["view_options"]["retrieve"]["tabs"]["Advanced"]

            # Get default advanced tab fields
            self.assertEqual(len(advanced_view_schema), 1)
            self.assertIn("Object Details", advanced_view_schema[0])
            advanced_tab_fields = advanced_view_schema[0].get("Object Details")["fields"]

            if detail_view_config := getattr(serializer.Meta, "detail_view_config", None):
                detail_view_schema = response.data["view_options"]["retrieve"]["tabs"][
                    bettertitle(self._get_queryset().model._meta.verbose_name)
                ]
                self.assertHttpStatus(response, status.HTTP_200_OK)

                # According to convention, fields in the advanced tab fields should not exist in
                # the `detail_view_schema`. Assert this is True.
                with self.subTest("Assert advanced tab fields should not exist in the detail_view_schema."):
                    if detail_view_config.get("include_others"):
                        # Handle "Other Fields" section specially as "Other Field" is dynamically added
                        # by Nautobot and is not part of the serializer-defined detail_view_config
                        other_fields = detail_view_schema[0]["Other Fields"]["fields"]
                        for field in advanced_tab_fields:
                            self.assertNotIn(field, other_fields)

                    for col_idx, col in enumerate(detail_view_schema):
                        for group_title, group in col.items():
                            if group_title == "Other Fields":
                                continue
                            group_fields = group["fields"]
                            # Config on the serializer
                            if (
                                col_idx < len(detail_view_config["layout"])
                                and group_title in detail_view_config["layout"][col_idx]
                            ):
                                fields = detail_view_config["layout"][col_idx][group_title]["fields"]
                            else:
                                fields = []

                            # Fields that are in the detail_view_schema must not be in the advanced tab as well
                            for field in group_fields:
                                self.assertNotIn(field, advanced_tab_fields)

                            # Fields that are explicit in the detail_view_config must remain as such in the schema
                            for field in fields:
                                if field not in advanced_tab_fields:
                                    self.assertIn(field, group_fields)

### `ListObjectsViewTestCase`

Bases: `APITestCase`

Source code in `nautobot/core/testing/api.py`

    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
    class ListObjectsViewTestCase(APITestCase):
        choices_fields = None
        filterset = None

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

        def get_depth_fields(self):
            """Get a list of model fields that could be tested with the ?depth query parameter"""
            depth_fields = []
            for field in self.model._meta.fields:
                if not field.name.startswith("_"):
                    if isinstance(field, (ForeignKey, GenericForeignKey, ManyToManyField, core_fields.TagsField)) and (
                        # we represent content-types as "app_label.modelname" rather than as FKs
                        field.related_model != ContentType
                        # user is a model field on Token but not a field on TokenSerializer
                        and not (field.name == "user" and self.model == users_models.Token)
                    ):
                        depth_fields.append(field.name)
            return depth_fields

        @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 testing.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_depth_0(self):
            """
            GET a list of objects using the "?depth=0" parameter.
            """
            depth_fields = self.get_depth_fields()
            self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
            url = f"{self._get_list_url()}?depth=0"
            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.assert_no_verboten_content(response)

            for response_data in response.data["results"]:
                for field in depth_fields:
                    self.assertIn(field, response_data)
                    if isinstance(response_data[field], list):
                        for entry in response_data[field]:
                            self.assertIsInstance(entry, dict)
                            self.assertTrue(is_uuid(entry["id"]))
                    else:
                        if response_data[field] is not None:
                            self.assertIsInstance(response_data[field], dict)
                            url = response_data[field]["url"]
                            pk = response_data[field]["id"]
                            object_type = response_data[field]["object_type"]
                            # The response should be a brief API object, containing an ID, object_type, and a
                            # URL ending in the UUID of the relevant object:
                            # http://nautobot.example.com/api/circuits/providers/<uuid>/
                            #                                                    ^^^^^^
                            self.assertTrue(is_uuid(url.split("/")[-2]))
                            self.assertTrue(is_uuid(pk))

                            with self.subTest(f"Assert object_type {object_type} is valid"):
                                app_label, model_name = object_type.split(".")
                                ContentType.objects.get(app_label=app_label, model=model_name)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_depth_1(self):
            """
            GET a list of objects using the "?depth=1" parameter.
            """
            depth_fields = self.get_depth_fields()
            self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
            url = f"{self._get_list_url()}?depth=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.assert_no_verboten_content(response)

            for response_data in response.data["results"]:
                for field in depth_fields:
                    self.assertIn(field, response_data)
                    if isinstance(response_data[field], list):
                        for entry in response_data[field]:
                            self.assertIsInstance(entry, dict)
                            self.assertTrue(is_uuid(entry["id"]))
                    else:
                        if response_data[field] is not None:
                            self.assertIsInstance(response_data[field], dict)
                            self.assertTrue(is_uuid(response_data[field]["id"]))

        @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 testing.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 = users_models.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)
            self.assert_no_verboten_content(response)

        @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=[])
        def test_list_objects_ascending_ordered(self):
            # Simple sorting check for models with a "name" field
            # TreeModels don't support sorting at this time (order_by is not supported by TreeQuerySet)
            #   They will pass api == queryset tests below but will fail the user expected sort test
            if hasattr(self.model, "name") and not issubclass(self.model, TreeModel):
                self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
                response = self.client.get(f"{self._get_list_url()}?sort=name&limit=3", **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                result_list = list(map(lambda p: p["name"], response.data["results"]))
                self.assertEqual(
                    result_list,
                    list(self._get_queryset().order_by("name").values_list("name", flat=True)[:3]),
                    "API sort not identical to QuerySet.order_by",
                )

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_descending_ordered(self):
            # Simple sorting check for models with a "name" field
            # TreeModels don't support sorting at this time (order_by is not supported by TreeQuerySet)
            #   They will pass api == queryset tests below but will fail the user expected sort test
            if hasattr(self.model, "name") and not issubclass(self.model, TreeModel):
                self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
                response = self.client.get(f"{self._get_list_url()}?sort=-name&limit=3", **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                result_list = list(map(lambda p: p["name"], response.data["results"]))
                self.assertEqual(
                    result_list,
                    list(self._get_queryset().order_by("-name").values_list("name", flat=True)[:3]),
                    "API sort not identical to QuerySet.order_by",
                )

                response_ascending = self.client.get(f"{self._get_list_url()}?sort=name&limit=3", **self.header)
                self.assertHttpStatus(response, status.HTTP_200_OK)
                result_list_ascending = list(map(lambda p: p["name"], response_ascending.data["results"]))

                self.assertNotEqual(
                    result_list,
                    result_list_ascending,
                    "Same results obtained when sorting by name and by -name (QuerySet not ordering)",
                )

        @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 testing.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.core.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.core.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_list_objects_csv(self):
            """
            GET a list of objects in CSV format as an authenticated user with permission to view some objects.
            """
            self.assertGreaterEqual(
                self._get_queryset().count(),
                3,
                f"Test requires the creation of at least three {self.model} instances",
            )
            instance1, instance2, instance3 = self._get_queryset()[:3]

            # Add object-level permission
            obj_perm = users_models.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 filtered GET to objects specifying CSV format as a query parameter
            response_1 = self.client.get(
                f"{self._get_list_url()}?format=csv&id={instance1.pk}&id={instance3.pk}", **self.header
            )
            self.assertHttpStatus(response_1, status.HTTP_200_OK)
            self.assertEqual(response_1.get("Content-Type"), "text/csv; charset=UTF-8")
            self.assertEqual(
                response_1.get("Content-Disposition"),
                f'attachment; filename="nautobot_{self.model.__name__.lower()}_data.csv"',
            )

            # Try same request specifying CSV format via the ACCEPT header
            response_2 = self.client.get(
                f"{self._get_list_url()}?id={instance1.pk}&id={instance3.pk}", **self.header, HTTP_ACCEPT="text/csv"
            )
            self.assertHttpStatus(response_2, status.HTTP_200_OK)
            self.assertEqual(response_2.get("Content-Type"), "text/csv; charset=UTF-8")
            self.assertEqual(
                response_2.get("Content-Disposition"),
                f'attachment; filename="nautobot_{self.model.__name__.lower()}_data.csv"',
            )

            self.maxDiff = None
            # This check is more useful than it might seem. Any related object that wasn't CSV-converted correctly
            # will likely be rendered incorrectly as an API URL, and that API URL *will* differ between the
            # two responses based on the inclusion or omission of the "?format=csv" parameter. If
            # you run into this, make sure all serializers have `Meta.fields = "__all__"` set.
            self.assertEqual(
                response_1.content.decode(response_1.charset), response_2.content.decode(response_2.charset)
            )

            # Load the csv data back into a list of object dicts
            reader = csv.DictReader(StringIO(response_1.content.decode(response_1.charset)))
            rows = list(reader)
            # Should only have one entry (instance1) since we filtered out instance2 and permissions block instance3
            self.assertEqual(1, len(rows))
            self.assertEqual(rows[0]["id"], str(instance1.pk))
            self.assertEqual(rows[0]["display"], getattr(instance1, "display", str(instance1)))
            if hasattr(self.model, "_custom_field_data"):
                custom_fields = extras_models.CustomField.objects.get_for_model(self.model)
                for cf in custom_fields:
                    self.assertIn(f"cf_{cf.key}", rows[0])
                    self.assertEqual(rows[0][f"cf_{cf.key}"], instance1._custom_field_data.get(cf.key) or "")

#### `get_depth_fields()`

Get a list of model fields that could be tested with the ?depth query parameter

Source code in `nautobot/core/testing/api.py`

    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    def get_depth_fields(self):
        """Get a list of model fields that could be tested with the ?depth query parameter"""
        depth_fields = []
        for field in self.model._meta.fields:
            if not field.name.startswith("_"):
                if isinstance(field, (ForeignKey, GenericForeignKey, ManyToManyField, core_fields.TagsField)) and (
                    # we represent content-types as "app_label.modelname" rather than as FKs
                    field.related_model != ContentType
                    # user is a model field on Token but not a field on TokenSerializer
                    and not (field.name == "user" and self.model == users_models.Token)
                ):
                    depth_fields.append(field.name)
        return depth_fields

#### `test_list_objects()`

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

Source code in `nautobot/core/testing/api.py`

    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
    @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 = users_models.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)
        self.assert_no_verboten_content(response)

#### `test_list_objects_anonymous()`

GET a list of objects as an unauthenticated user.

Source code in `nautobot/core/testing/api.py`

    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    @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 testing.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_csv()`

GET a list of objects in CSV format as an authenticated user with permission to view some objects.

Source code in `nautobot/core/testing/api.py`

    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
    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_list_objects_csv(self):
        """
        GET a list of objects in CSV format as an authenticated user with permission to view some objects.
        """
        self.assertGreaterEqual(
            self._get_queryset().count(),
            3,
            f"Test requires the creation of at least three {self.model} instances",
        )
        instance1, instance2, instance3 = self._get_queryset()[:3]

        # Add object-level permission
        obj_perm = users_models.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 filtered GET to objects specifying CSV format as a query parameter
        response_1 = self.client.get(
            f"{self._get_list_url()}?format=csv&id={instance1.pk}&id={instance3.pk}", **self.header
        )
        self.assertHttpStatus(response_1, status.HTTP_200_OK)
        self.assertEqual(response_1.get("Content-Type"), "text/csv; charset=UTF-8")
        self.assertEqual(
            response_1.get("Content-Disposition"),
            f'attachment; filename="nautobot_{self.model.__name__.lower()}_data.csv"',
        )

        # Try same request specifying CSV format via the ACCEPT header
        response_2 = self.client.get(
            f"{self._get_list_url()}?id={instance1.pk}&id={instance3.pk}", **self.header, HTTP_ACCEPT="text/csv"
        )
        self.assertHttpStatus(response_2, status.HTTP_200_OK)
        self.assertEqual(response_2.get("Content-Type"), "text/csv; charset=UTF-8")
        self.assertEqual(
            response_2.get("Content-Disposition"),
            f'attachment; filename="nautobot_{self.model.__name__.lower()}_data.csv"',
        )

        self.maxDiff = None
        # This check is more useful than it might seem. Any related object that wasn't CSV-converted correctly
        # will likely be rendered incorrectly as an API URL, and that API URL *will* differ between the
        # two responses based on the inclusion or omission of the "?format=csv" parameter. If
        # you run into this, make sure all serializers have `Meta.fields = "__all__"` set.
        self.assertEqual(
            response_1.content.decode(response_1.charset), response_2.content.decode(response_2.charset)
        )

        # Load the csv data back into a list of object dicts
        reader = csv.DictReader(StringIO(response_1.content.decode(response_1.charset)))
        rows = list(reader)
        # Should only have one entry (instance1) since we filtered out instance2 and permissions block instance3
        self.assertEqual(1, len(rows))
        self.assertEqual(rows[0]["id"], str(instance1.pk))
        self.assertEqual(rows[0]["display"], getattr(instance1, "display", str(instance1)))
        if hasattr(self.model, "_custom_field_data"):
            custom_fields = extras_models.CustomField.objects.get_for_model(self.model)
            for cf in custom_fields:
                self.assertIn(f"cf_{cf.key}", rows[0])
                self.assertEqual(rows[0][f"cf_{cf.key}"], instance1._custom_field_data.get(cf.key) or "")

#### `test_list_objects_depth_0()`

GET a list of objects using the "?depth=0" parameter.

Source code in `nautobot/core/testing/api.py`

    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
    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_list_objects_depth_0(self):
        """
        GET a list of objects using the "?depth=0" parameter.
        """
        depth_fields = self.get_depth_fields()
        self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
        url = f"{self._get_list_url()}?depth=0"
        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.assert_no_verboten_content(response)

        for response_data in response.data["results"]:
            for field in depth_fields:
                self.assertIn(field, response_data)
                if isinstance(response_data[field], list):
                    for entry in response_data[field]:
                        self.assertIsInstance(entry, dict)
                        self.assertTrue(is_uuid(entry["id"]))
                else:
                    if response_data[field] is not None:
                        self.assertIsInstance(response_data[field], dict)
                        url = response_data[field]["url"]
                        pk = response_data[field]["id"]
                        object_type = response_data[field]["object_type"]
                        # The response should be a brief API object, containing an ID, object_type, and a
                        # URL ending in the UUID of the relevant object:
                        # http://nautobot.example.com/api/circuits/providers/<uuid>/
                        #                                                    ^^^^^^
                        self.assertTrue(is_uuid(url.split("/")[-2]))
                        self.assertTrue(is_uuid(pk))

                        with self.subTest(f"Assert object_type {object_type} is valid"):
                            app_label, model_name = object_type.split(".")
                            ContentType.objects.get(app_label=app_label, model=model_name)

#### `test_list_objects_depth_1()`

GET a list of objects using the "?depth=1" parameter.

Source code in `nautobot/core/testing/api.py`

    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
    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_list_objects_depth_1(self):
        """
        GET a list of objects using the "?depth=1" parameter.
        """
        depth_fields = self.get_depth_fields()
        self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
        url = f"{self._get_list_url()}?depth=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.assert_no_verboten_content(response)

        for response_data in response.data["results"]:
            for field in depth_fields:
                self.assertIn(field, response_data)
                if isinstance(response_data[field], list):
                    for entry in response_data[field]:
                        self.assertIsInstance(entry, dict)
                        self.assertTrue(is_uuid(entry["id"]))
                else:
                    if response_data[field] is not None:
                        self.assertIsInstance(response_data[field], dict)
                        self.assertTrue(is_uuid(response_data[field]["id"]))

#### `test_list_objects_filtered()`

GET a list of objects filtered by ID.

Source code in `nautobot/core/testing/api.py`

    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    @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/core/testing/api.py`

    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    @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.core.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.core.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/core/testing/api.py`

    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    @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 testing.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/core/testing/api.py`

    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    @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 testing.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/core/testing/api.py`

    521
    522
    523
    524
    525
    526
    527
    @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/core/testing/api.py`

    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
    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 not hasattr(self.model, "notes"):
                self.skipTest("Model doesn't appear to support Notes")
            instance = self._get_queryset().first()
            if not isinstance(instance.notes, QuerySet):
                self.skipTest("Model has a notes field but it doesn't appear to be Notes")

            # Add object-level permission
            obj_perm = users_models.ObjectPermission(
                name="Test permission",
                constraints={"pk": instance.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(instance)
            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"]))
            self.assertIn(instance.get_notes_url(api=True), str(response.data["notes_url"]))

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_notes_url_functionality(self):
            if not hasattr(self.model, "notes"):
                self.skipTest("Model doesn't appear to support Notes")
            instance = self._get_queryset().first()
            if not isinstance(instance.notes, QuerySet):
                self.skipTest("Model has a notes field but it doesn't appear to be Notes")

            self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
            self.add_permissions("extras.add_note")

            # Add note via REST API
            notes_url = instance.get_notes_url(api=True)
            response = self.client.post(
                notes_url,
                {"note": f"This is a note for {instance}"},
                format="json",
                **self.header,
            )
            self.assertHttpStatus(response, status.HTTP_201_CREATED)
            self.assertIsInstance(response.data, dict)
            self.assertEqual(f"This is a note for {instance}", response.data["note"])
            self.assertEqual(str(self.user.pk), str(response.data["user"]["id"]))
            self.assertEqual(str(instance.pk), str(response.data["assigned_object_id"]))
            self.assertEqual(str(instance.pk), str(response.data["assigned_object"]["id"]))

            # Get note via REST API
            response = self.client.get(notes_url, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_403_FORBIDDEN)

            self.add_permissions("extras.view_note")
            response = self.client.get(notes_url, format="json", **self.header)
            self.assertHttpStatus(response, status.HTTP_200_OK)
            self.assertEqual(f"This is a note for {instance}", response.data["results"][0]["note"])

### `TreeModelAPIViewTestCaseMixin`

Test `?depth=2` query parameter for TreeModel

Source code in `nautobot/core/testing/api.py`

    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
    class TreeModelAPIViewTestCaseMixin:
        """Test `?depth=2` query parameter for TreeModel"""

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_depth_2(self):
            """
            GET a list of objects using the "?depth=2" parameter.
            TreeModel Only
            """
            field = "parent"

            self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
            url = f"{self._get_list_url()}?depth=2"
            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())

            response_data = response.data["results"]
            for data in response_data:
                # First Level Parent
                self.assertEqual(field in data, True)
                if data[field] is not None:
                    self.assertIsInstance(data[field], dict)
                    self.assertTrue(is_uuid(data[field]["id"]))
                    # Second Level Parent
                    self.assertIn(field, data[field])
                    if data[field][field] is not None:
                        self.assertIsInstance(data[field][field], dict)
                        self.assertTrue(is_uuid(data[field][field]["id"]))

#### `test_list_objects_depth_2()`

GET a list of objects using the "?depth=2" parameter. TreeModel Only

Source code in `nautobot/core/testing/api.py`

    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
    @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
    def test_list_objects_depth_2(self):
        """
        GET a list of objects using the "?depth=2" parameter.
        TreeModel Only
        """
        field = "parent"

        self.add_permissions(f"{self.model._meta.app_label}.view_{self.model._meta.model_name}")
        url = f"{self._get_list_url()}?depth=2"
        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())

        response_data = response.data["results"]
        for data in response_data:
            # First Level Parent
            self.assertEqual(field in data, True)
            if data[field] is not None:
                self.assertIsInstance(data[field], dict)
                self.assertTrue(is_uuid(data[field]["id"]))
                # Second Level Parent
                self.assertIn(field, data[field])
                if data[field][field] is not None:
                    self.assertIsInstance(data[field][field], dict)
                    self.assertTrue(is_uuid(data[field][field]["id"]))

### `UpdateObjectViewTestCase`

Bases: `APITestCase`

Source code in `nautobot/core/testing/api.py`

    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
    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 testing.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.
            """

            def strip_serialized_object(this_object):
                """
                Only here to work around acceptable differences in PATCH response vs GET response which are known bugs.
                """
                # Work around for https://github.com/nautobot/nautobot/issues/3321
                this_object.pop("last_updated", None)
                # PATCH response always includes "opt-in" fields, but GET response does not.
                this_object.pop("computed_fields", None)
                this_object.pop("config_context", None)
                this_object.pop("relationships", None)

                for value in this_object.values():
                    if isinstance(value, dict):
                        strip_serialized_object(value)
                    elif isinstance(value, list):
                        for list_dict in value:
                            if isinstance(list_dict, dict):
                                strip_serialized_object(list_dict)

            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 = users_models.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()
            strip_serialized_object(initial_serialized_object)

            # 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()
            strip_serialized_object(serialized_object)
            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 = lookup.get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, extras_choices.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 = lookup.get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_UPDATE)

        def test_get_put_round_trip(self):
            """GET and then PUT an object and verify that it's accepted and unchanged."""
            self.maxDiff = None
            # Add object-level permission
            obj_perm = users_models.ObjectPermission(name="Test permission", actions=["view", "change"])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

            instance = self._get_queryset().first()
            url = self._get_detail_url(instance)

            # GET object representation
            opt_in_fields = getattr(get_serializer_for_model(self.model).Meta, "opt_in_fields", None)
            if opt_in_fields:
                url += "?" + "&".join([f"include={field}" for field in opt_in_fields])
            get_response = self.client.get(url, **self.header)
            self.assertHttpStatus(get_response, status.HTTP_200_OK)
            initial_serialized_object = get_response.json()

            # PUT same object representation
            put_response = self.client.put(url, initial_serialized_object, format="json", **self.header)
            self.assertHttpStatus(put_response, status.HTTP_200_OK, initial_serialized_object)
            updated_serialized_object = put_response.json()

            # Work around for https://github.com/nautobot/nautobot/issues/3321
            initial_serialized_object.pop("last_updated", None)
            updated_serialized_object.pop("last_updated", None)
            self.assertEqual(initial_serialized_object, updated_serialized_object)

        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 = users_models.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_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 that has choices defined (fields with enums)
            if any(
                [
                    "POST" in data["actions"],
                    "PUT" in data["actions"],
                ]
            ):
                schema = data["schema"]
                props = schema["properties"]
                fields = props.keys()
                field_choices = set()
                for field_name in fields:
                    obj = props[field_name]
                    if "enum" in obj and "enumNames" in obj:
                        enum = obj["enum"]
                        # Zipping to assert that the enum and the mapping have the same number of items.
                        model_field_choices = dict(zip(obj["enumNames"], enum))
                        self.assertEqual(len(enum), len(model_field_choices))
                        field_choices.add(field_name)
            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/core/testing/api.py`

    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
    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 = users_models.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_get_put_round_trip()`

GET and then PUT an object and verify that it's accepted and unchanged.

Source code in `nautobot/core/testing/api.py`

    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
    def test_get_put_round_trip(self):
        """GET and then PUT an object and verify that it's accepted and unchanged."""
        self.maxDiff = None
        # Add object-level permission
        obj_perm = users_models.ObjectPermission(name="Test permission", actions=["view", "change"])
        obj_perm.save()
        obj_perm.users.add(self.user)
        obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))

        instance = self._get_queryset().first()
        url = self._get_detail_url(instance)

        # GET object representation
        opt_in_fields = getattr(get_serializer_for_model(self.model).Meta, "opt_in_fields", None)
        if opt_in_fields:
            url += "?" + "&".join([f"include={field}" for field in opt_in_fields])
        get_response = self.client.get(url, **self.header)
        self.assertHttpStatus(get_response, status.HTTP_200_OK)
        initial_serialized_object = get_response.json()

        # PUT same object representation
        put_response = self.client.put(url, initial_serialized_object, format="json", **self.header)
        self.assertHttpStatus(put_response, status.HTTP_200_OK, initial_serialized_object)
        updated_serialized_object = put_response.json()

        # Work around for https://github.com/nautobot/nautobot/issues/3321
        initial_serialized_object.pop("last_updated", None)
        updated_serialized_object.pop("last_updated", None)
        self.assertEqual(initial_serialized_object, updated_serialized_object)

#### `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/core/testing/api.py`

    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
    @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 that has choices defined (fields with enums)
        if any(
            [
                "POST" in data["actions"],
                "PUT" in data["actions"],
            ]
        ):
            schema = data["schema"]
            props = schema["properties"]
            fields = props.keys()
            field_choices = set()
            for field_name in fields:
                obj = props[field_name]
                if "enum" in obj and "enumNames" in obj:
                    enum = obj["enum"]
                    # Zipping to assert that the enum and the mapping have the same number of items.
                    model_field_choices = dict(zip(obj["enumNames"], enum))
                    self.assertEqual(len(enum), len(model_field_choices))
                    field_choices.add(field_name)
        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/core/testing/api.py`

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

        def strip_serialized_object(this_object):
            """
            Only here to work around acceptable differences in PATCH response vs GET response which are known bugs.
            """
            # Work around for https://github.com/nautobot/nautobot/issues/3321
            this_object.pop("last_updated", None)
            # PATCH response always includes "opt-in" fields, but GET response does not.
            this_object.pop("computed_fields", None)
            this_object.pop("config_context", None)
            this_object.pop("relationships", None)

            for value in this_object.values():
                if isinstance(value, dict):
                    strip_serialized_object(value)
                elif isinstance(value, list):
                    for list_dict in value:
                        if isinstance(list_dict, dict):
                            strip_serialized_object(list_dict)

        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 = users_models.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()
        strip_serialized_object(initial_serialized_object)

        # 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()
        strip_serialized_object(serialized_object)
        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 = lookup.get_changes_for_model(instance)
            self.assertEqual(len(objectchanges), 1)
            self.assertEqual(objectchanges[0].action, extras_choices.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 = lookup.get_changes_for_model(instance)
            self.assertEqual(len(objectchanges), 1)
            self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_UPDATE)

#### `test_update_object_without_permission()`

PATCH a single object without permission.

Source code in `nautobot/core/testing/api.py`

    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    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 testing.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/core/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
     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
    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
    @tag("unit")
    class FilterTestCases:
        class BaseFilterTestCase(views.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]):  # noqa: S311  # suspicious-non-cryptographic-random-usage
                        break
                    if value[field_name] and value["count"] < qs_count:
                        qs_count -= value["count"]
                        test_values.append(str(value[field_name]))

                if len(test_values) < 2:
                    raise ValueError(
                        f"Cannot find enough valid test data for {queryset.model._meta.object_name} field {field_name} "
                        f"(found {len(test_values)} option(s): {test_values}) but need at least 2 of them"
                    )
                return test_values

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

            queryset = None
            filterset = None

            # list of filters to be tested by `test_filters_generic`
            # list of iterables with filter name and optional field name
            # example:
            #   generic_filter_tests = [
            #       ["filter1"],
            #       ["filter2", "field2__name"],
            #   ]
            generic_filter_tests = []

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

            def test_filters_generic(self):
                """Test all multiple choice filters declared in `self.generic_filter_tests`.

                This test uses `get_filterset_test_values()` to retrieve a valid set of test data and asserts
                that the filterset filter output matches the corresponding queryset filter.
                The majority of Nautobot filters use conjoined=False, so the extra logic to support conjoined=True has not
                been implemented here. TagFilter and similar "AND" filters are not supported.

                Examples:
                    Multiple tests can be performed for the same filter by adding multiple entries in
                    `generic_filter_tests` with explicit field names.
                    For example, to test a NaturalKeyOrPKMultipleChoiceFilter, use:
                        generic_filter_tests = (
                            ["filter_name", "field_name__name"],
                            ["filter_name", "field_name__id"],
                        )

                    If a field name is not declared, the filter name will be used for the field name:
                        generic_filter_tests = (
                            ["devices"],
                        )
                    This expects a field named `devices` on the model and a filter named `devices` on the filterset.
                """
                if not self.generic_filter_tests:
                    self.skipTest("No generic_filter_tests defined?")

                for test in self.generic_filter_tests:
                    filter_name = test[0]
                    field_name = test[-1]  # default to filter_name if a second list item was not supplied
                    with self.subTest(f"{self.filterset.__name__} filter {filter_name} ({field_name})"):
                        test_data = self.get_filterset_test_values(field_name)
                        params = {filter_name: test_data}
                        filterset_result = self.filterset(params, self.queryset).qs
                        qs_result = self.queryset.filter(**{f"{field_name}__in": test_data}).distinct()
                        self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result, ordered=False)

            def test_boolean_filters_generic(self):
                """Test all `RelatedMembershipBooleanFilter` filters found in `self.filterset.get_filters()`
                except for the ones with custom filter logic defined in its `method` attribute.

                This test asserts that `filter=True` matches `self.queryset.filter(field__isnull=False)` and
                that `filter=False` matches `self.queryset.filter(field__isnull=True)`.
                """
                for filter_name, filter_object in self.filterset.get_filters().items():
                    if not isinstance(filter_object, RelatedMembershipBooleanFilter):
                        continue
                    if filter_object.method is not None:
                        continue
                    field_name = filter_object.field_name
                    with self.subTest(f"{self.filterset.__name__} RelatedMembershipBooleanFilter {filter_name} (True)"):
                        filterset_result = self.filterset({filter_name: True}, self.queryset).qs
                        qs_result = self.queryset.filter(**{f"{field_name}__isnull": False}).distinct()
                        self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result)
                    with self.subTest(f"{self.filterset.__name__} RelatedMembershipBooleanFilter {filter_name} (False)"):
                        filterset_result = self.filterset({filter_name: False}, self.queryset).qs
                        qs_result = self.queryset.filter(**{f"{field_name}__isnull": True}).distinct()
                        self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result)

            def test_tags_filter(self):
                """Test the `tags` filter which should be present on all PrimaryModel filtersets."""
                if not issubclass(self.queryset.model, PrimaryModel):
                    self.skipTest("Not a PrimaryModel")

                # Find an instance with at least two tags (should be common given our factory design)
                for instance in list(self.queryset):
                    if len(instance.tags.all()) >= 2:
                        tags = list(instance.tags.all()[:2])
                        break
                else:
                    self.fail(f"Couldn't find any {self.queryset.model._meta.object_name} with at least two Tags.")
                params = {"tags": [tags[0].name, tags[1].pk]}
                filterset_result = self.filterset(params, self.queryset).qs
                # Tags is an AND filter not an OR filter
                qs_result = self.queryset.filter(tags=tags[0]).filter(tags=tags[1]).distinct()
                self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result)

        class NameOnlyFilterTestCase(FilterTestCase):
            """Add simple tests for filtering by name."""

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

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

            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(views.TestCase):
            """Add test cases for tenant and tenant-group filters."""

            tenancy_related_name = ""

            def test_tenant(self):
                tenants = list(models.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].name, tenants[1].name]}
                self.assertQuerysetEqual(
                    self.filterset(params, self.queryset).qs, self.queryset.filter(tenant__in=tenants), ordered=False
                )

            def test_tenant_group(self):
                tenant_groups = list(
                    models.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.descendants(include_self=True)

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

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

### `BaseFilterTestCase`

Bases: `views.TestCase`

Base class for testing of FilterSets.

Source code in `nautobot/core/testing/filters.py`

    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
    class BaseFilterTestCase(views.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]):  # noqa: S311  # suspicious-non-cryptographic-random-usage
                    break
                if value[field_name] and value["count"] < qs_count:
                    qs_count -= value["count"]
                    test_values.append(str(value[field_name]))

            if len(test_values) < 2:
                raise ValueError(
                    f"Cannot find enough valid test data for {queryset.model._meta.object_name} field {field_name} "
                    f"(found {len(test_values)} option(s): {test_values}) but need at least 2 of them"
                )
            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/core/testing/filters.py`

    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
    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]):  # noqa: S311  # suspicious-non-cryptographic-random-usage
                break
            if value[field_name] and value["count"] < qs_count:
                qs_count -= value["count"]
                test_values.append(str(value[field_name]))

        if len(test_values) < 2:
            raise ValueError(
                f"Cannot find enough valid test data for {queryset.model._meta.object_name} field {field_name} "
                f"(found {len(test_values)} option(s): {test_values}) but need at least 2 of them"
            )
        return test_values

### `FilterTestCase`

Bases: `BaseFilterTestCase`

Add common tests for all FilterSets.

Source code in `nautobot/core/testing/filters.py`

     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
    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
    class FilterTestCase(BaseFilterTestCase):
        """Add common tests for all FilterSets."""

        queryset = None
        filterset = None

        # list of filters to be tested by `test_filters_generic`
        # list of iterables with filter name and optional field name
        # example:
        #   generic_filter_tests = [
        #       ["filter1"],
        #       ["filter2", "field2__name"],
        #   ]
        generic_filter_tests = []

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

        def test_filters_generic(self):
            """Test all multiple choice filters declared in `self.generic_filter_tests`.

            This test uses `get_filterset_test_values()` to retrieve a valid set of test data and asserts
            that the filterset filter output matches the corresponding queryset filter.
            The majority of Nautobot filters use conjoined=False, so the extra logic to support conjoined=True has not
            been implemented here. TagFilter and similar "AND" filters are not supported.

            Examples:
                Multiple tests can be performed for the same filter by adding multiple entries in
                `generic_filter_tests` with explicit field names.
                For example, to test a NaturalKeyOrPKMultipleChoiceFilter, use:
                    generic_filter_tests = (
                        ["filter_name", "field_name__name"],
                        ["filter_name", "field_name__id"],
                    )

                If a field name is not declared, the filter name will be used for the field name:
                    generic_filter_tests = (
                        ["devices"],
                    )
                This expects a field named `devices` on the model and a filter named `devices` on the filterset.
            """
            if not self.generic_filter_tests:
                self.skipTest("No generic_filter_tests defined?")

            for test in self.generic_filter_tests:
                filter_name = test[0]
                field_name = test[-1]  # default to filter_name if a second list item was not supplied
                with self.subTest(f"{self.filterset.__name__} filter {filter_name} ({field_name})"):
                    test_data = self.get_filterset_test_values(field_name)
                    params = {filter_name: test_data}
                    filterset_result = self.filterset(params, self.queryset).qs
                    qs_result = self.queryset.filter(**{f"{field_name}__in": test_data}).distinct()
                    self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result, ordered=False)

        def test_boolean_filters_generic(self):
            """Test all `RelatedMembershipBooleanFilter` filters found in `self.filterset.get_filters()`
            except for the ones with custom filter logic defined in its `method` attribute.

            This test asserts that `filter=True` matches `self.queryset.filter(field__isnull=False)` and
            that `filter=False` matches `self.queryset.filter(field__isnull=True)`.
            """
            for filter_name, filter_object in self.filterset.get_filters().items():
                if not isinstance(filter_object, RelatedMembershipBooleanFilter):
                    continue
                if filter_object.method is not None:
                    continue
                field_name = filter_object.field_name
                with self.subTest(f"{self.filterset.__name__} RelatedMembershipBooleanFilter {filter_name} (True)"):
                    filterset_result = self.filterset({filter_name: True}, self.queryset).qs
                    qs_result = self.queryset.filter(**{f"{field_name}__isnull": False}).distinct()
                    self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result)
                with self.subTest(f"{self.filterset.__name__} RelatedMembershipBooleanFilter {filter_name} (False)"):
                    filterset_result = self.filterset({filter_name: False}, self.queryset).qs
                    qs_result = self.queryset.filter(**{f"{field_name}__isnull": True}).distinct()
                    self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result)

        def test_tags_filter(self):
            """Test the `tags` filter which should be present on all PrimaryModel filtersets."""
            if not issubclass(self.queryset.model, PrimaryModel):
                self.skipTest("Not a PrimaryModel")

            # Find an instance with at least two tags (should be common given our factory design)
            for instance in list(self.queryset):
                if len(instance.tags.all()) >= 2:
                    tags = list(instance.tags.all()[:2])
                    break
            else:
                self.fail(f"Couldn't find any {self.queryset.model._meta.object_name} with at least two Tags.")
            params = {"tags": [tags[0].name, tags[1].pk]}
            filterset_result = self.filterset(params, self.queryset).qs
            # Tags is an AND filter not an OR filter
            qs_result = self.queryset.filter(tags=tags[0]).filter(tags=tags[1]).distinct()
            self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result)

#### `test_boolean_filters_generic()`

Test all `RelatedMembershipBooleanFilter` filters found in `self.filterset.get_filters()` except for the ones with custom filter logic defined in its `method` attribute.

This test asserts that `filter=True` matches `self.queryset.filter(field__isnull=False)` and that `filter=False` matches `self.queryset.filter(field__isnull=True)`.

Source code in `nautobot/core/testing/filters.py`

    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    def test_boolean_filters_generic(self):
        """Test all `RelatedMembershipBooleanFilter` filters found in `self.filterset.get_filters()`
        except for the ones with custom filter logic defined in its `method` attribute.

        This test asserts that `filter=True` matches `self.queryset.filter(field__isnull=False)` and
        that `filter=False` matches `self.queryset.filter(field__isnull=True)`.
        """
        for filter_name, filter_object in self.filterset.get_filters().items():
            if not isinstance(filter_object, RelatedMembershipBooleanFilter):
                continue
            if filter_object.method is not None:
                continue
            field_name = filter_object.field_name
            with self.subTest(f"{self.filterset.__name__} RelatedMembershipBooleanFilter {filter_name} (True)"):
                filterset_result = self.filterset({filter_name: True}, self.queryset).qs
                qs_result = self.queryset.filter(**{f"{field_name}__isnull": False}).distinct()
                self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result)
            with self.subTest(f"{self.filterset.__name__} RelatedMembershipBooleanFilter {filter_name} (False)"):
                filterset_result = self.filterset({filter_name: False}, self.queryset).qs
                qs_result = self.queryset.filter(**{f"{field_name}__isnull": True}).distinct()
                self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result)

#### `test_filters_generic()`

Test all multiple choice filters declared in `self.generic_filter_tests`.

This test uses `get_filterset_test_values()` to retrieve a valid set of test data and asserts that the filterset filter output matches the corresponding queryset filter. The majority of Nautobot filters use conjoined=False, so the extra logic to support conjoined=True has not been implemented here. TagFilter and similar "AND" filters are not supported.

Examples:

Multiple tests can be performed for the same filter by adding multiple entries in `generic_filter_tests` with explicit field names. For example, to test a NaturalKeyOrPKMultipleChoiceFilter, use: generic_filter_tests = ( ["filter_name", "field_name__name"], ["filter_name", "field_name__id"], )

If a field name is not declared, the filter name will be used for the field name: generic_filter_tests = ( ["devices"], ) This expects a field named `devices` on the model and a filter named `devices` on the filterset.

Source code in `nautobot/core/testing/filters.py`

     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
    def test_filters_generic(self):
        """Test all multiple choice filters declared in `self.generic_filter_tests`.

        This test uses `get_filterset_test_values()` to retrieve a valid set of test data and asserts
        that the filterset filter output matches the corresponding queryset filter.
        The majority of Nautobot filters use conjoined=False, so the extra logic to support conjoined=True has not
        been implemented here. TagFilter and similar "AND" filters are not supported.

        Examples:
            Multiple tests can be performed for the same filter by adding multiple entries in
            `generic_filter_tests` with explicit field names.
            For example, to test a NaturalKeyOrPKMultipleChoiceFilter, use:
                generic_filter_tests = (
                    ["filter_name", "field_name__name"],
                    ["filter_name", "field_name__id"],
                )

            If a field name is not declared, the filter name will be used for the field name:
                generic_filter_tests = (
                    ["devices"],
                )
            This expects a field named `devices` on the model and a filter named `devices` on the filterset.
        """
        if not self.generic_filter_tests:
            self.skipTest("No generic_filter_tests defined?")

        for test in self.generic_filter_tests:
            filter_name = test[0]
            field_name = test[-1]  # default to filter_name if a second list item was not supplied
            with self.subTest(f"{self.filterset.__name__} filter {filter_name} ({field_name})"):
                test_data = self.get_filterset_test_values(field_name)
                params = {filter_name: test_data}
                filterset_result = self.filterset(params, self.queryset).qs
                qs_result = self.queryset.filter(**{f"{field_name}__in": test_data}).distinct()
                self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result, ordered=False)

#### `test_id()`

Verify that the filterset supports filtering by id.

Source code in `nautobot/core/testing/filters.py`

    70
    71
    72
    73
    74
    75
    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/core/testing/filters.py`

    77
    78
    79
    80
    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_tags_filter()`

Test the `tags` filter which should be present on all PrimaryModel filtersets.

Source code in `nautobot/core/testing/filters.py`

    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    def test_tags_filter(self):
        """Test the `tags` filter which should be present on all PrimaryModel filtersets."""
        if not issubclass(self.queryset.model, PrimaryModel):
            self.skipTest("Not a PrimaryModel")

        # Find an instance with at least two tags (should be common given our factory design)
        for instance in list(self.queryset):
            if len(instance.tags.all()) >= 2:
                tags = list(instance.tags.all()[:2])
                break
        else:
            self.fail(f"Couldn't find any {self.queryset.model._meta.object_name} with at least two Tags.")
        params = {"tags": [tags[0].name, tags[1].pk]}
        filterset_result = self.filterset(params, self.queryset).qs
        # Tags is an AND filter not an OR filter
        qs_result = self.queryset.filter(tags=tags[0]).filter(tags=tags[1]).distinct()
        self.assertQuerysetEqualAndNotEmpty(filterset_result, qs_result)

### `NameOnlyFilterTestCase`

Bases: `FilterTestCase`

Add simple tests for filtering by name.

Source code in `nautobot/core/testing/filters.py`

    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    class NameOnlyFilterTestCase(FilterTestCase):
        """Add simple tests for filtering by name."""

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

#### `test_name()`

Verify that the filterset supports filtering by name.

Source code in `nautobot/core/testing/filters.py`

    161
    162
    163
    164
    165
    166
    167
    168
    def test_name(self):
        """Verify that the filterset supports filtering by name."""
        params = {"name": list(self.queryset.values_list("name", flat=True)[:2])}
        filterset = self.filterset(params, self.queryset)
        self.assertTrue(filterset.is_valid())
        self.assertQuerysetEqualAndNotEmpty(
            filterset.qs.order_by("name"), self.queryset.filter(name__in=params["name"]).order_by("name")
        )

### `NameSlugFilterTestCase`

Bases: `NameOnlyFilterTestCase`

Add simple tests for filtering by name and by slug.

Source code in `nautobot/core/testing/filters.py`

    170
    171
    172
    173
    174
    175
    176
    177
    178
    class NameSlugFilterTestCase(NameOnlyFilterTestCase):
        """Add simple tests for filtering by name and by slug."""

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

Verify that the filterset supports filtering by slug.

Source code in `nautobot/core/testing/filters.py`

    173
    174
    175
    176
    177
    178
    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: `views.TestCase`

Add test cases for tenant and tenant-group filters.

Source code in `nautobot/core/testing/filters.py`

    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
    class TenancyFilterTestCaseMixin(views.TestCase):
        """Add test cases for tenant and tenant-group filters."""

        tenancy_related_name = ""

        def test_tenant(self):
            tenants = list(models.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].name, tenants[1].name]}
            self.assertQuerysetEqual(
                self.filterset(params, self.queryset).qs, self.queryset.filter(tenant__in=tenants), ordered=False
            )

        def test_tenant_group(self):
            tenant_groups = list(
                models.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.descendants(include_self=True)

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

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

## `nautobot.apps.testing.ModelTestCase`

Bases: `TestCase`

Parent class for TestCases which deal with models.

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

    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    class ModelTestCase(TestCase):
        """
        Parent class for TestCases which deal with models.
        """

        model = None
        # Optional, list of Relationships populated in setUpTestData for testing with this model
        # Be sure to also create RelationshipAssociations using these Relationships!
        relationships: Optional[Sequence[extras_models.Relationship]] = None
        # Optional, list of CustomFields populated in setUpTestData for testing with this model
        # Be sure to also populate these fields on your test data!
        custom_fields: Optional[Sequence[extras_models.CustomField]] = None

        def _get_queryset(self):
            """
            Return a base queryset suitable for use in test methods.
            """
            return self.model.objects.all()

## `nautobot.apps.testing.ModelTestCases`

Source code in `nautobot/core/testing/models.py`

     6
     7
     8
     9
    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
    @tag("unit")
    class ModelTestCases:
        class BaseModelTestCase(TestCase):
            """Base class for generic model tests."""

            model = None

            def test_natural_key_symmetry(self):
                """Check that `natural_key()` and `get_by_natural_key()` work reciprocally."""
                instance = self.model.objects.first()
                self.assertIsNotNone(instance)
                if not hasattr(instance, "natural_key"):
                    self.skipTest("No natural_key on this model.")
                self.assertIsNotNone(instance.natural_key())
                self.assertEqual(self.model.objects.get_by_natural_key(*instance.natural_key()), instance)

            def test_composite_key(self):
                """Check that `composite_key` and filtering by `composite_key` both work."""
                instance = self.model.objects.first()
                self.assertIsNotNone(instance)
                if not hasattr(instance, "composite_key"):
                    self.skipTest("No composite_key on this model.")
                self.assertIsNotNone(instance.composite_key)
                # get()
                self.assertEqual(self.model.objects.get(composite_key=instance.composite_key), instance)
                # filter()
                match = self.model.objects.filter(composite_key=instance.composite_key)
                self.assertEqual(1, len(match))
                self.assertEqual(match[0], instance)
                # exclude()
                match = self.model.objects.exclude(composite_key=instance.composite_key)
                self.assertEqual(self.model.objects.count() - 1, match.count())
                self.assertNotIn(instance, match)

            def test_get_docs_url(self):
                """Check that `get_docs_url()` returns a valid static file path for this model."""
                self.assertIsNotNone(get_docs_url(self.model))

### `BaseModelTestCase`

Bases: `TestCase`

Base class for generic model tests.

Source code in `nautobot/core/testing/models.py`

     8
     9
    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
    class BaseModelTestCase(TestCase):
        """Base class for generic model tests."""

        model = None

        def test_natural_key_symmetry(self):
            """Check that `natural_key()` and `get_by_natural_key()` work reciprocally."""
            instance = self.model.objects.first()
            self.assertIsNotNone(instance)
            if not hasattr(instance, "natural_key"):
                self.skipTest("No natural_key on this model.")
            self.assertIsNotNone(instance.natural_key())
            self.assertEqual(self.model.objects.get_by_natural_key(*instance.natural_key()), instance)

        def test_composite_key(self):
            """Check that `composite_key` and filtering by `composite_key` both work."""
            instance = self.model.objects.first()
            self.assertIsNotNone(instance)
            if not hasattr(instance, "composite_key"):
                self.skipTest("No composite_key on this model.")
            self.assertIsNotNone(instance.composite_key)
            # get()
            self.assertEqual(self.model.objects.get(composite_key=instance.composite_key), instance)
            # filter()
            match = self.model.objects.filter(composite_key=instance.composite_key)
            self.assertEqual(1, len(match))
            self.assertEqual(match[0], instance)
            # exclude()
            match = self.model.objects.exclude(composite_key=instance.composite_key)
            self.assertEqual(self.model.objects.count() - 1, match.count())
            self.assertNotIn(instance, match)

        def test_get_docs_url(self):
            """Check that `get_docs_url()` returns a valid static file path for this model."""
            self.assertIsNotNone(get_docs_url(self.model))

#### `test_composite_key()`

Check that `composite_key` and filtering by `composite_key` both work.

Source code in `nautobot/core/testing/models.py`

    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    def test_composite_key(self):
        """Check that `composite_key` and filtering by `composite_key` both work."""
        instance = self.model.objects.first()
        self.assertIsNotNone(instance)
        if not hasattr(instance, "composite_key"):
            self.skipTest("No composite_key on this model.")
        self.assertIsNotNone(instance.composite_key)
        # get()
        self.assertEqual(self.model.objects.get(composite_key=instance.composite_key), instance)
        # filter()
        match = self.model.objects.filter(composite_key=instance.composite_key)
        self.assertEqual(1, len(match))
        self.assertEqual(match[0], instance)
        # exclude()
        match = self.model.objects.exclude(composite_key=instance.composite_key)
        self.assertEqual(self.model.objects.count() - 1, match.count())
        self.assertNotIn(instance, match)

#### `test_get_docs_url()`

Check that `get_docs_url()` returns a valid static file path for this model.

Source code in `nautobot/core/testing/models.py`

    40
    41
    42
    def test_get_docs_url(self):
        """Check that `get_docs_url()` returns a valid static file path for this model."""
        self.assertIsNotNone(get_docs_url(self.model))

#### `test_natural_key_symmetry()`

Check that `natural_key()` and `get_by_natural_key()` work reciprocally.

Source code in `nautobot/core/testing/models.py`

    13
    14
    15
    16
    17
    18
    19
    20
    def test_natural_key_symmetry(self):
        """Check that `natural_key()` and `get_by_natural_key()` work reciprocally."""
        instance = self.model.objects.first()
        self.assertIsNotNone(instance)
        if not hasattr(instance, "natural_key"):
            self.skipTest("No natural_key on this model.")
        self.assertIsNotNone(instance.natural_key())
        self.assertEqual(self.model.objects.get_by_natural_key(*instance.natural_key()), instance)

## `nautobot.apps.testing.ModelViewTestCase`

Bases: `ModelTestCase`

Base TestCase for model views. Subclass to test individual views.

Source code in `nautobot/core/testing/views.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
    @tag("performance")
    class ModelViewTestCase(ModelTestCase):
        """
        Base TestCase for model views. Subclass to test individual views.
        """

        reverse_url_attribute = None
        """
        Name of instance field to pass as a kwarg when looking up URLs for creating/editing/deleting a model instance.

        If unspecified, "pk" and "slug" will be tried, in that order.
        """

        def _get_base_url(self):
            """
            Return the base format string for a view URL for the test.

            Examples: "dcim:device_{}", "plugins:example_plugin:example_model_{}"

            Override this if needed for testing of views that don't correspond directly to self.model,
            for example the DCIM "interface-connections" and "console-connections" view tests.
            """
            app_name = apps.get_app_config(app_label=self.model._meta.app_label).name
            # AppConfig.name accounts for NautobotApps that are not built at the root of the package
            if app_name in settings.PLUGINS:
                return f"plugins:{self.model._meta.app_label}:{self.model._meta.model_name}_{{}}"
            return f"{self.model._meta.app_label}:{self.model._meta.model_name}_{{}}"

        def _get_url(self, action, instance=None):
            """
            Return the URL string for a specific action and optionally a specific model instance.

            Override this if needed for testing of views whose names don't follow
            the [plugins]:<app_label>:<model_name>_<action> naming convention.
            """
            url_format = self._get_base_url()

            # If no instance was provided, assume we don't need a unique identifier
            if instance is None:
                return reverse(url_format.format(action))

            if self.reverse_url_attribute:
                return reverse(
                    url_format.format(action),
                    kwargs={self.reverse_url_attribute: getattr(instance, self.reverse_url_attribute)},
                )

            try:
                # Default to using the PK to retrieve the URL for an object
                return reverse(url_format.format(action), kwargs={"pk": instance.pk})
            except NoReverseMatch:
                # Attempt to resolve using slug as the unique identifier if one exists
                if hasattr(self.model, "slug"):
                    return reverse(url_format.format(action), kwargs={"slug": instance.slug})
                raise

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

Name of instance field to pass as a kwarg when looking up URLs for creating/editing/deleting a model instance.

If unspecified, "pk" and "slug" will be tried, in that order.

## `nautobot.apps.testing.NautobotDataMigrationTest`

Bases: `TestCase`

Source code in `nautobot/core/testing/migrations.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
    @skip("TODO: Havoc has been wreaked on migrations in 2.0, so this test is currently broken.")
    class NautobotDataMigrationTest(TestCase):
        @property
        def app(self):
            return apps.get_containing_app_config(type(self).__module__).name

        migrate_from = None
        migrate_to = None

        def setUp(self):
            # Remove factory data beforehand
            call_command("flush", "--no-input")

            error_message = f"DataMigrationTest '{type(self).__name__}' must define migrate_from and migrate_to properties"
            self.assertNotEqual(self.migrate_from, None, error_message)
            self.assertNotEqual(self.migrate_to, None, error_message)

            # migrate nautobot to the previous migration state
            executor = MigrationExecutor(connection)
            old_apps = executor.loader.project_state(self.migrate_from).apps
            executor.migrate(self.migrate_from)

            self.populateDataBeforeMigration(old_apps)

            # migrate nautobot to the migration you want to test against
            executor = MigrationExecutor(connection)
            executor.loader.build_graph()  # reload

            executor.migrate(self.migrate_to)

            self.apps = executor.loader.project_state(self.migrate_to).apps

        def populateDataBeforeMigration(self, installed_apps):
            """Populate your Nautobot data before migrating from the first migration to the second"""

### `populateDataBeforeMigration(installed_apps)`

Populate your Nautobot data before migrating from the first migration to the second

Source code in `nautobot/core/testing/migrations.py`

    42
    43
    def populateDataBeforeMigration(self, installed_apps):
        """Populate your Nautobot data before migrating from the first migration to the second"""

## `nautobot.apps.testing.NautobotTestCaseMixin`

Base class for all Nautobot-specific unit tests.

Source code in `nautobot/core/testing/mixins.py`

     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
    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
    class NautobotTestCaseMixin:
        """Base class for all Nautobot-specific unit tests."""

        user_permissions = ()
        client_class = NautobotTestClient

        def setUpNautobot(self, client=True, populate_status=False):
            """Setup shared testuser, statuses and client."""
            # Re-populate status choices after database truncation by TransactionTestCase
            if populate_status:
                management.populate_status_choices(apps, None)

            # Create the test user and assign permissions
            self.user = User.objects.create_user(username="nautobotuser")
            self.add_permissions(*self.user_permissions)

            if client:
                # Initialize the test client
                if not hasattr(self, "client") or self.client is None:
                    self.client = self.client_class()

                # Force login explicitly with the first-available backend
                self.client.force_login(self.user)

        def tearDown(self):
            """Clear lru_cache data to avoid leakage of information between test cases when running in parallel."""
            extras_signals.invalidate_lru_cache(extras_models.CustomField)
            extras_signals.invalidate_lru_cache(extras_models.ComputedField)
            extras_signals.invalidate_lru_cache(extras_models.Relationship)
            super().tearDown()

        def prepare_instance(self, instance):
            """
            Test cases can override this method to perform any necessary manipulation of an instance prior to its evaluation
            against test data. For example, it can be used to decrypt a Secret's plaintext attribute.
            """
            return instance

        def model_to_dict(self, instance, fields, api=False):
            """
            Return a dictionary representation of an instance.
            """
            # Prepare the instance and call Django's model_to_dict() to extract all fields
            model_dict = model_to_dict(self.prepare_instance(instance), fields=fields)

            # Map any additional (non-field) instance attributes that were specified
            for attr in fields:
                if hasattr(instance, attr) and attr not in model_dict:
                    model_dict[attr] = getattr(instance, attr)

            for key, value in list(model_dict.items()):
                try:
                    field = instance._meta.get_field(key)
                except FieldDoesNotExist:
                    # Attribute is not a model field, but may be a computed field,
                    # so allow `field` checks to pass through.
                    field = None

                # Handle ManyToManyFields
                if value and isinstance(field, (ManyToManyField, core_fields.TagsField)):
                    # Only convert ContentType to <app_label>.<model> for API serializers/views
                    if api and field.related_model is ContentType:
                        model_dict[key] = sorted([f"{ct.app_label}.{ct.model}" for ct in value])
                    # Otherwise always convert object instances to pk
                    else:
                        model_dict[key] = sorted([obj.pk for obj in value])

                if api:
                    # Replace ContentType primary keys with <app_label>.<model>
                    if isinstance(getattr(instance, key), ContentType):
                        ct = ContentType.objects.get(pk=value)
                        model_dict[key] = f"{ct.app_label}.{ct.model}"

                    # Convert IPNetwork instances to strings
                    elif isinstance(value, IPNetwork):
                        model_dict[key] = str(value)

                else:
                    # Convert ArrayFields to CSV strings
                    if isinstance(field, core_fields.JSONArrayField):
                        model_dict[key] = ",".join([str(v) for v in value])

                    # Convert JSONField dict values to JSON strings
                    if isinstance(field, JSONField) and isinstance(value, dict):
                        model_dict[key] = json.dumps(value)

            return model_dict

        #
        # Permissions management
        #

        def add_permissions(self, *names):
            """
            Assign a set of permissions to the test user. Accepts permission names in the form <app>.<action>_<model>.
            """
            for name in names:
                ct, action = permissions.resolve_permission_ct(name)
                obj_perm = users_models.ObjectPermission(name=name, actions=[action])
                obj_perm.save()
                obj_perm.users.add(self.user)
                obj_perm.object_types.add(ct)

        #
        # Custom assertions
        #

        def assertHttpStatus(self, response, expected_status, msg=None):
            """
            TestCase method. Provide more detail in the event of an unexpected HTTP response.
            """
            err_message = None
            # Construct an error message only if we know the test is going to fail
            if isinstance(expected_status, int):
                expected_status = [expected_status]
            if response.status_code not in expected_status:
                err_message = f"Expected HTTP status(es) {expected_status}; received {response.status_code}:"
                if hasattr(response, "data"):
                    # REST API response; pass the response data through directly
                    err_message += f"\n{response.data}"
                # Attempt to extract form validation errors from the response HTML
                form_errors = testing.extract_form_failures(response.content.decode(response.charset))
                err_message += "\n" + str(form_errors or response.content.decode(response.charset) or "No data")
                if msg:
                    err_message = f"{msg}\n{err_message}"
            self.assertIn(response.status_code, expected_status, err_message)

        def assertInstanceEqual(self, instance, data, exclude=None, api=False):
            """
            Compare a model instance to a dictionary, checking that its attribute values match those specified
            in the dictionary.

            :param instance: Python object instance
            :param data: Dictionary of test data used to define the instance
            :param exclude: List of fields to exclude from comparison (e.g. passwords, which get hashed)
            :param api: Set to True is the data is a JSON representation of the instance
            """
            if exclude is None:
                exclude = []

            fields = [k for k in data.keys() if k not in exclude]
            model_dict = self.model_to_dict(instance, fields=fields, api=api)

            new_model_dict = {}
            for k, v in model_dict.items():
                if isinstance(v, list):
                    # Sort lists of values. This includes items like tags, or other M2M fields
                    new_model_dict[k] = sorted(v)
                elif k == "data_schema" and isinstance(v, str):
                    # Standardize the data_schema JSON, since the column is JSON and MySQL/dolt do not guarantee order
                    new_model_dict[k] = self.standardize_json(v)
                else:
                    new_model_dict[k] = v

            # Omit any dictionary keys which are not instance attributes or have been excluded
            relevant_data = {}
            for k, v in data.items():
                if hasattr(instance, k) and k not in exclude:
                    if isinstance(v, list):
                        # Sort lists of values. This includes items like tags, or other M2M fields
                        relevant_data[k] = sorted(v)
                    elif k == "data_schema" and isinstance(v, str):
                        # Standardize the data_schema JSON, since the column is JSON and MySQL/dolt do not guarantee order
                        relevant_data[k] = self.standardize_json(v)
                    else:
                        relevant_data[k] = v

            self.assertEqual(new_model_dict, relevant_data)

        def assertQuerysetEqualAndNotEmpty(self, qs, values, *args, **kwargs):
            """Wrapper for assertQuerysetEqual with additional logic to assert input queryset and values are not empty"""

            self.assertNotEqual(len(qs), 0, "Queryset cannot be empty")
            self.assertNotEqual(len(values), 0, "Values cannot be empty")

            return self.assertQuerysetEqual(qs, values, *args, **kwargs)

        #
        # Convenience methods
        #

        def absolute_api_url(self, obj):
            """Get the absolute API URL ("http://nautobot.example.com/api/...") for a given object."""
            request = APIRequestFactory(SERVER_NAME="nautobot.example.com").get("")
            return request.build_absolute_uri(obj.get_absolute_url(api=True))

        def standardize_json(self, data):
            obj = json.loads(data)
            return json.dumps(obj, sort_keys=True)

        @classmethod
        def create_tags(cls, *names):
            """
            Create and return a Tag instance for each name given.

            DEPRECATED: use TagFactory instead.
            """
            warnings.warn(
                "create_tags() is deprecated and will be removed in a future Nautobot release. "
                "Use nautobot.extras.factory.TagFactory (provided in Nautobot 1.5 and later) instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            return [extras_models.Tag.objects.create(name=name) for name in names]

### `absolute_api_url(obj)`

Get the absolute API URL ("http://nautobot.example.com/api/...") for a given object.

Source code in `nautobot/core/testing/mixins.py`

    222
    223
    224
    225
    def absolute_api_url(self, obj):
        """Get the absolute API URL ("http://nautobot.example.com/api/...") for a given object."""
        request = APIRequestFactory(SERVER_NAME="nautobot.example.com").get("")
        return request.build_absolute_uri(obj.get_absolute_url(api=True))

### `add_permissions(*names)`

Assign a set of permissions to the test user. Accepts permission names in the form ._.

Source code in `nautobot/core/testing/mixins.py`

    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    def add_permissions(self, *names):
        """
        Assign a set of permissions to the test user. Accepts permission names in the form <app>.<action>_<model>.
        """
        for name in names:
            ct, action = permissions.resolve_permission_ct(name)
            obj_perm = users_models.ObjectPermission(name=name, actions=[action])
            obj_perm.save()
            obj_perm.users.add(self.user)
            obj_perm.object_types.add(ct)

### `assertHttpStatus(response, expected_status, msg=None)`

TestCase method. Provide more detail in the event of an unexpected HTTP response.

Source code in `nautobot/core/testing/mixins.py`

    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    def assertHttpStatus(self, response, expected_status, msg=None):
        """
        TestCase method. Provide more detail in the event of an unexpected HTTP response.
        """
        err_message = None
        # Construct an error message only if we know the test is going to fail
        if isinstance(expected_status, int):
            expected_status = [expected_status]
        if response.status_code not in expected_status:
            err_message = f"Expected HTTP status(es) {expected_status}; received {response.status_code}:"
            if hasattr(response, "data"):
                # REST API response; pass the response data through directly
                err_message += f"\n{response.data}"
            # Attempt to extract form validation errors from the response HTML
            form_errors = testing.extract_form_failures(response.content.decode(response.charset))
            err_message += "\n" + str(form_errors or response.content.decode(response.charset) or "No data")
            if msg:
                err_message = f"{msg}\n{err_message}"
        self.assertIn(response.status_code, expected_status, err_message)

### `assertInstanceEqual(instance, data, exclude=None, api=False)`

Compare a model instance to a dictionary, checking that its attribute values match those specified in the dictionary.

:param instance: Python object instance :param data: Dictionary of test data used to define the instance :param exclude: List of fields to exclude from comparison (e.g. passwords, which get hashed) :param api: Set to True is the data is a JSON representation of the instance

Source code in `nautobot/core/testing/mixins.py`

    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
    def assertInstanceEqual(self, instance, data, exclude=None, api=False):
        """
        Compare a model instance to a dictionary, checking that its attribute values match those specified
        in the dictionary.

        :param instance: Python object instance
        :param data: Dictionary of test data used to define the instance
        :param exclude: List of fields to exclude from comparison (e.g. passwords, which get hashed)
        :param api: Set to True is the data is a JSON representation of the instance
        """
        if exclude is None:
            exclude = []

        fields = [k for k in data.keys() if k not in exclude]
        model_dict = self.model_to_dict(instance, fields=fields, api=api)

        new_model_dict = {}
        for k, v in model_dict.items():
            if isinstance(v, list):
                # Sort lists of values. This includes items like tags, or other M2M fields
                new_model_dict[k] = sorted(v)
            elif k == "data_schema" and isinstance(v, str):
                # Standardize the data_schema JSON, since the column is JSON and MySQL/dolt do not guarantee order
                new_model_dict[k] = self.standardize_json(v)
            else:
                new_model_dict[k] = v

        # Omit any dictionary keys which are not instance attributes or have been excluded
        relevant_data = {}
        for k, v in data.items():
            if hasattr(instance, k) and k not in exclude:
                if isinstance(v, list):
                    # Sort lists of values. This includes items like tags, or other M2M fields
                    relevant_data[k] = sorted(v)
                elif k == "data_schema" and isinstance(v, str):
                    # Standardize the data_schema JSON, since the column is JSON and MySQL/dolt do not guarantee order
                    relevant_data[k] = self.standardize_json(v)
                else:
                    relevant_data[k] = v

        self.assertEqual(new_model_dict, relevant_data)

### `assertQuerysetEqualAndNotEmpty(qs, values, *args, **kwargs)`

Wrapper for assertQuerysetEqual with additional logic to assert input queryset and values are not empty

Source code in `nautobot/core/testing/mixins.py`

    210
    211
    212
    213
    214
    215
    216
    def assertQuerysetEqualAndNotEmpty(self, qs, values, *args, **kwargs):
        """Wrapper for assertQuerysetEqual with additional logic to assert input queryset and values are not empty"""

        self.assertNotEqual(len(qs), 0, "Queryset cannot be empty")
        self.assertNotEqual(len(values), 0, "Values cannot be empty")

        return self.assertQuerysetEqual(qs, values, *args, **kwargs)

### `create_tags(*names)` `classmethod`

Create and return a Tag instance for each name given.

DEPRECATED: use TagFactory instead.

Source code in `nautobot/core/testing/mixins.py`

    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    @classmethod
    def create_tags(cls, *names):
        """
        Create and return a Tag instance for each name given.

        DEPRECATED: use TagFactory instead.
        """
        warnings.warn(
            "create_tags() is deprecated and will be removed in a future Nautobot release. "
            "Use nautobot.extras.factory.TagFactory (provided in Nautobot 1.5 and later) instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        return [extras_models.Tag.objects.create(name=name) for name in names]

### `model_to_dict(instance, fields, api=False)`

Return a dictionary representation of an instance.

Source code in `nautobot/core/testing/mixins.py`

     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
    def model_to_dict(self, instance, fields, api=False):
        """
        Return a dictionary representation of an instance.
        """
        # Prepare the instance and call Django's model_to_dict() to extract all fields
        model_dict = model_to_dict(self.prepare_instance(instance), fields=fields)

        # Map any additional (non-field) instance attributes that were specified
        for attr in fields:
            if hasattr(instance, attr) and attr not in model_dict:
                model_dict[attr] = getattr(instance, attr)

        for key, value in list(model_dict.items()):
            try:
                field = instance._meta.get_field(key)
            except FieldDoesNotExist:
                # Attribute is not a model field, but may be a computed field,
                # so allow `field` checks to pass through.
                field = None

            # Handle ManyToManyFields
            if value and isinstance(field, (ManyToManyField, core_fields.TagsField)):
                # Only convert ContentType to <app_label>.<model> for API serializers/views
                if api and field.related_model is ContentType:
                    model_dict[key] = sorted([f"{ct.app_label}.{ct.model}" for ct in value])
                # Otherwise always convert object instances to pk
                else:
                    model_dict[key] = sorted([obj.pk for obj in value])

            if api:
                # Replace ContentType primary keys with <app_label>.<model>
                if isinstance(getattr(instance, key), ContentType):
                    ct = ContentType.objects.get(pk=value)
                    model_dict[key] = f"{ct.app_label}.{ct.model}"

                # Convert IPNetwork instances to strings
                elif isinstance(value, IPNetwork):
                    model_dict[key] = str(value)

            else:
                # Convert ArrayFields to CSV strings
                if isinstance(field, core_fields.JSONArrayField):
                    model_dict[key] = ",".join([str(v) for v in value])

                # Convert JSONField dict values to JSON strings
                if isinstance(field, JSONField) and isinstance(value, dict):
                    model_dict[key] = json.dumps(value)

        return model_dict

### `prepare_instance(instance)`

Test cases can override this method to perform any necessary manipulation of an instance prior to its evaluation against test data. For example, it can be used to decrypt a Secret's plaintext attribute.

Source code in `nautobot/core/testing/mixins.py`

    72
    73
    74
    75
    76
    77
    def prepare_instance(self, instance):
        """
        Test cases can override this method to perform any necessary manipulation of an instance prior to its evaluation
        against test data. For example, it can be used to decrypt a Secret's plaintext attribute.
        """
        return instance

### `setUpNautobot(client=True, populate_status=False)`

Setup shared testuser, statuses and client.

Source code in `nautobot/core/testing/mixins.py`

    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    def setUpNautobot(self, client=True, populate_status=False):
        """Setup shared testuser, statuses and client."""
        # Re-populate status choices after database truncation by TransactionTestCase
        if populate_status:
            management.populate_status_choices(apps, None)

        # Create the test user and assign permissions
        self.user = User.objects.create_user(username="nautobotuser")
        self.add_permissions(*self.user_permissions)

        if client:
            # Initialize the test client
            if not hasattr(self, "client") or self.client is None:
                self.client = self.client_class()

            # Force login explicitly with the first-available backend
            self.client.force_login(self.user)

### `tearDown()`

Clear lru_cache data to avoid leakage of information between test cases when running in parallel.

Source code in `nautobot/core/testing/mixins.py`

    65
    66
    67
    68
    69
    70
    def tearDown(self):
        """Clear lru_cache data to avoid leakage of information between test cases when running in parallel."""
        extras_signals.invalidate_lru_cache(extras_models.CustomField)
        extras_signals.invalidate_lru_cache(extras_models.ComputedField)
        extras_signals.invalidate_lru_cache(extras_models.Relationship)
        super().tearDown()

## `nautobot.apps.testing.NautobotTestClient`

Bases: `APIClient`

Base client class for Nautobot testing.

DO NOT USE THIS IN PRODUCTION NAUTOBOT CODE.

Source code in `nautobot/core/testing/mixins.py`

    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    class NautobotTestClient(APIClient):
        """
        Base client class for Nautobot testing.

        DO NOT USE THIS IN PRODUCTION NAUTOBOT CODE.
        """

        def __init__(self, *args, **kwargs):
            """
            Default the SERVER_NAME to "nautobot.example.com" rather than Django's default "testserver".

            This matches the ALLOWED_HOSTS set in nautobot/core/tests/nautobot_config.py and
            helps to protect us against issues like https://github.com/nautobot/nautobot/issues/3065.
            """
            kwargs.setdefault("SERVER_NAME", "nautobot.example.com")
            super().__init__(*args, **kwargs)

### `__init__(*args, **kwargs)`

Default the SERVER_NAME to "nautobot.example.com" rather than Django's default "testserver".

This matches the ALLOWED_HOSTS set in nautobot/core/tests/nautobot_config.py and helps to protect us against issues like https://github.com/nautobot/nautobot/issues/3065.

Source code in `nautobot/core/testing/mixins.py`

    30
    31
    32
    33
    34
    35
    36
    37
    38
    def __init__(self, *args, **kwargs):
        """
        Default the SERVER_NAME to "nautobot.example.com" rather than Django's default "testserver".

        This matches the ALLOWED_HOSTS set in nautobot/core/tests/nautobot_config.py and
        helps to protect us against issues like https://github.com/nautobot/nautobot/issues/3065.
        """
        kwargs.setdefault("SERVER_NAME", "nautobot.example.com")
        super().__init__(*args, **kwargs)

## `nautobot.apps.testing.OpenAPISchemaTestCases`

Source code in `nautobot/core/testing/schema.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
     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
    126
    127
    128
    129
    130
    131
    132
    @tag("unit")
    class OpenAPISchemaTestCases:
        class BaseSchemaTestCase(views.TestCase):
            """Base class for testing of the OpenAPI schema."""

            @classmethod
            def setUpTestData(cls):
                # We could load the schema from the /api/swagger.yaml endpoint in setUp(self) via self.client,
                # but it's fairly expensive to do so. Better to do so only once per class.
                cls.schemas = {}
                for api_version in api_settings.ALLOWED_VERSIONS:
                    out = StringIO()
                    err = StringIO()
                    call_command("spectacular", "--api-version", api_version, stdout=out, stderr=err)
                    cls.schemas[api_version] = yaml.safe_load(out.getvalue())

            def get_component_schema(self, component_name, api_version=None):
                """Helper method to pull a specific component schema from the larger OpenAPI schema already loaded."""
                if api_version is None:
                    api_version = settings.REST_FRAMEWORK_VERSION
                self.assertIn(component_name, self.schemas[api_version]["components"]["schemas"])
                return self.schemas[api_version]["components"]["schemas"][component_name]

            def assert_component_mapped_by_object_type(self, schema, models):
                """Test method to assert that this polymorphic component has the expected permitted types."""
                # For all polymorphic nested serializers, we should be using the "object_type" field to discriminate them.
                self.assertEqual(schema["discriminator"]["propertyName"], "object_type")
                if models is None:
                    models = []
                # We don't care what the schema calls the individual serializers in discriminator.mapping,
                # but we do want to assert that they're the correct set of model content-types as keys
                self.assertEqual(
                    set(schema["discriminator"]["mapping"].keys()),
                    {f"{model._meta.app_label}.{model._meta.model_name}" for model in models},
                )

            def get_schema_property(self, component_schema, property_name):
                """Helper method to pull a specific property schema from a larger component schema already extracted."""
                self.assertIn(property_name, component_schema["properties"])
                return component_schema["properties"][property_name]

            def get_property_ref_component_name(self, component_schema, property_name):
                """Helper method to identify a component referenced by the given property of the current component."""
                property_schema = self.get_schema_property(component_schema, property_name)
                if "allOf" in property_schema:
                    # "allOf":
                    # - "$ref": "#/components/schemas/ComponentName"
                    self.assertEqual(len(property_schema["allOf"]), 1)
                    self.assertIn("$ref", property_schema["allOf"][0])
                    return property_schema["allOf"][0]["$ref"].split("/")[-1]
                if property_schema.get("type") == "array":
                    # "type": "array"
                    # "items":
                    #   "$ref": "#/components/schemas/ComponentName"
                    self.assertIn("items", property_schema)
                    self.assertIn("$ref", property_schema["items"])
                    return property_schema["items"]["$ref"].split("/")[-1]
                # TODO: extend to handle other cases as needed?
                self.fail(f"Property schema not as expected: {property_schema}")
                return None

            def assert_nullable_property(self, component_schema, property_name):
                """Test method to assert that the given component property is marked as nullable."""
                self.assertTrue(self.get_schema_property(component_schema, property_name).get("nullable", False))

            def assert_not_nullable_property(self, component_schema, property_name):
                """Test method to assert that the given component property is marked as non-nullable."""
                self.assertFalse(self.get_schema_property(component_schema, property_name).get("nullable", False))

            def assert_read_only_property(self, component_schema, property_name):
                """Test method to assert that the given component property is marked as read-only."""
                self.assertTrue(self.get_schema_property(component_schema, property_name).get("readOnly", False))

            def assert_not_read_only_property(self, component_schema, property_name):
                """Test method to assert that the given component property is not marked as read-only."""
                self.assertFalse(self.get_schema_property(component_schema, property_name).get("readOnly", False))

            def validate_polymorphic_property(
                self,
                component_name,
                property_name,
                models=None,
                nullable=False,
                read_only=True,
                many=False,
            ):
                """
                Bringing it all together.

                This validates the schema to show that:
                - The component exists and has such a property
                - The property has the correct `nullable` and `readOnly` values
                - The property has the correct multiplicity
                - The property is a reference to another component
                - The property's referenced component is polymorphic and has the expected set of model content-types.

                Returns:
                    (Tuple[ref_component_name, ref_component_schema]): The referenced component's name and schema.
                """
                component_schema = self.get_component_schema(component_name)

                if nullable:
                    self.assert_nullable_property(component_schema, property_name)
                else:
                    self.assert_not_nullable_property(component_schema, property_name)

                if read_only:
                    self.assert_read_only_property(component_schema, property_name)
                else:
                    self.assert_not_read_only_property(component_schema, property_name)

                if many:
                    self.assertEqual("array", self.get_schema_property(component_schema, property_name).get("type"))
                else:
                    self.assertNotEqual("array", self.get_schema_property(component_schema, property_name).get("type"))

                ref_component_name = self.get_property_ref_component_name(component_schema, property_name)
                ref_component_schema = self.get_component_schema(ref_component_name)
                self.assert_component_mapped_by_object_type(ref_component_schema, models=models)

                return (ref_component_name, ref_component_schema)

### `BaseSchemaTestCase`

Bases: `views.TestCase`

Base class for testing of the OpenAPI schema.

Source code in `nautobot/core/testing/schema.py`

     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
    126
    127
    128
    129
    130
    131
    132
    class BaseSchemaTestCase(views.TestCase):
        """Base class for testing of the OpenAPI schema."""

        @classmethod
        def setUpTestData(cls):
            # We could load the schema from the /api/swagger.yaml endpoint in setUp(self) via self.client,
            # but it's fairly expensive to do so. Better to do so only once per class.
            cls.schemas = {}
            for api_version in api_settings.ALLOWED_VERSIONS:
                out = StringIO()
                err = StringIO()
                call_command("spectacular", "--api-version", api_version, stdout=out, stderr=err)
                cls.schemas[api_version] = yaml.safe_load(out.getvalue())

        def get_component_schema(self, component_name, api_version=None):
            """Helper method to pull a specific component schema from the larger OpenAPI schema already loaded."""
            if api_version is None:
                api_version = settings.REST_FRAMEWORK_VERSION
            self.assertIn(component_name, self.schemas[api_version]["components"]["schemas"])
            return self.schemas[api_version]["components"]["schemas"][component_name]

        def assert_component_mapped_by_object_type(self, schema, models):
            """Test method to assert that this polymorphic component has the expected permitted types."""
            # For all polymorphic nested serializers, we should be using the "object_type" field to discriminate them.
            self.assertEqual(schema["discriminator"]["propertyName"], "object_type")
            if models is None:
                models = []
            # We don't care what the schema calls the individual serializers in discriminator.mapping,
            # but we do want to assert that they're the correct set of model content-types as keys
            self.assertEqual(
                set(schema["discriminator"]["mapping"].keys()),
                {f"{model._meta.app_label}.{model._meta.model_name}" for model in models},
            )

        def get_schema_property(self, component_schema, property_name):
            """Helper method to pull a specific property schema from a larger component schema already extracted."""
            self.assertIn(property_name, component_schema["properties"])
            return component_schema["properties"][property_name]

        def get_property_ref_component_name(self, component_schema, property_name):
            """Helper method to identify a component referenced by the given property of the current component."""
            property_schema = self.get_schema_property(component_schema, property_name)
            if "allOf" in property_schema:
                # "allOf":
                # - "$ref": "#/components/schemas/ComponentName"
                self.assertEqual(len(property_schema["allOf"]), 1)
                self.assertIn("$ref", property_schema["allOf"][0])
                return property_schema["allOf"][0]["$ref"].split("/")[-1]
            if property_schema.get("type") == "array":
                # "type": "array"
                # "items":
                #   "$ref": "#/components/schemas/ComponentName"
                self.assertIn("items", property_schema)
                self.assertIn("$ref", property_schema["items"])
                return property_schema["items"]["$ref"].split("/")[-1]
            # TODO: extend to handle other cases as needed?
            self.fail(f"Property schema not as expected: {property_schema}")
            return None

        def assert_nullable_property(self, component_schema, property_name):
            """Test method to assert that the given component property is marked as nullable."""
            self.assertTrue(self.get_schema_property(component_schema, property_name).get("nullable", False))

        def assert_not_nullable_property(self, component_schema, property_name):
            """Test method to assert that the given component property is marked as non-nullable."""
            self.assertFalse(self.get_schema_property(component_schema, property_name).get("nullable", False))

        def assert_read_only_property(self, component_schema, property_name):
            """Test method to assert that the given component property is marked as read-only."""
            self.assertTrue(self.get_schema_property(component_schema, property_name).get("readOnly", False))

        def assert_not_read_only_property(self, component_schema, property_name):
            """Test method to assert that the given component property is not marked as read-only."""
            self.assertFalse(self.get_schema_property(component_schema, property_name).get("readOnly", False))

        def validate_polymorphic_property(
            self,
            component_name,
            property_name,
            models=None,
            nullable=False,
            read_only=True,
            many=False,
        ):
            """
            Bringing it all together.

            This validates the schema to show that:
            - The component exists and has such a property
            - The property has the correct `nullable` and `readOnly` values
            - The property has the correct multiplicity
            - The property is a reference to another component
            - The property's referenced component is polymorphic and has the expected set of model content-types.

            Returns:
                (Tuple[ref_component_name, ref_component_schema]): The referenced component's name and schema.
            """
            component_schema = self.get_component_schema(component_name)

            if nullable:
                self.assert_nullable_property(component_schema, property_name)
            else:
                self.assert_not_nullable_property(component_schema, property_name)

            if read_only:
                self.assert_read_only_property(component_schema, property_name)
            else:
                self.assert_not_read_only_property(component_schema, property_name)

            if many:
                self.assertEqual("array", self.get_schema_property(component_schema, property_name).get("type"))
            else:
                self.assertNotEqual("array", self.get_schema_property(component_schema, property_name).get("type"))

            ref_component_name = self.get_property_ref_component_name(component_schema, property_name)
            ref_component_schema = self.get_component_schema(ref_component_name)
            self.assert_component_mapped_by_object_type(ref_component_schema, models=models)

            return (ref_component_name, ref_component_schema)

#### `assert_component_mapped_by_object_type(schema, models)`

Test method to assert that this polymorphic component has the expected permitted types.

Source code in `nautobot/core/testing/schema.py`

    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    def assert_component_mapped_by_object_type(self, schema, models):
        """Test method to assert that this polymorphic component has the expected permitted types."""
        # For all polymorphic nested serializers, we should be using the "object_type" field to discriminate them.
        self.assertEqual(schema["discriminator"]["propertyName"], "object_type")
        if models is None:
            models = []
        # We don't care what the schema calls the individual serializers in discriminator.mapping,
        # but we do want to assert that they're the correct set of model content-types as keys
        self.assertEqual(
            set(schema["discriminator"]["mapping"].keys()),
            {f"{model._meta.app_label}.{model._meta.model_name}" for model in models},
        )

#### `assert_not_nullable_property(component_schema, property_name)`

Test method to assert that the given component property is marked as non-nullable.

Source code in `nautobot/core/testing/schema.py`

    77
    78
    79
    def assert_not_nullable_property(self, component_schema, property_name):
        """Test method to assert that the given component property is marked as non-nullable."""
        self.assertFalse(self.get_schema_property(component_schema, property_name).get("nullable", False))

#### `assert_not_read_only_property(component_schema, property_name)`

Test method to assert that the given component property is not marked as read-only.

Source code in `nautobot/core/testing/schema.py`

    85
    86
    87
    def assert_not_read_only_property(self, component_schema, property_name):
        """Test method to assert that the given component property is not marked as read-only."""
        self.assertFalse(self.get_schema_property(component_schema, property_name).get("readOnly", False))

#### `assert_nullable_property(component_schema, property_name)`

Test method to assert that the given component property is marked as nullable.

Source code in `nautobot/core/testing/schema.py`

    73
    74
    75
    def assert_nullable_property(self, component_schema, property_name):
        """Test method to assert that the given component property is marked as nullable."""
        self.assertTrue(self.get_schema_property(component_schema, property_name).get("nullable", False))

#### `assert_read_only_property(component_schema, property_name)`

Test method to assert that the given component property is marked as read-only.

Source code in `nautobot/core/testing/schema.py`

    81
    82
    83
    def assert_read_only_property(self, component_schema, property_name):
        """Test method to assert that the given component property is marked as read-only."""
        self.assertTrue(self.get_schema_property(component_schema, property_name).get("readOnly", False))

#### `get_component_schema(component_name, api_version=None)`

Helper method to pull a specific component schema from the larger OpenAPI schema already loaded.

Source code in `nautobot/core/testing/schema.py`

    28
    29
    30
    31
    32
    33
    def get_component_schema(self, component_name, api_version=None):
        """Helper method to pull a specific component schema from the larger OpenAPI schema already loaded."""
        if api_version is None:
            api_version = settings.REST_FRAMEWORK_VERSION
        self.assertIn(component_name, self.schemas[api_version]["components"]["schemas"])
        return self.schemas[api_version]["components"]["schemas"][component_name]

#### `get_property_ref_component_name(component_schema, property_name)`

Helper method to identify a component referenced by the given property of the current component.

Source code in `nautobot/core/testing/schema.py`

    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    def get_property_ref_component_name(self, component_schema, property_name):
        """Helper method to identify a component referenced by the given property of the current component."""
        property_schema = self.get_schema_property(component_schema, property_name)
        if "allOf" in property_schema:
            # "allOf":
            # - "$ref": "#/components/schemas/ComponentName"
            self.assertEqual(len(property_schema["allOf"]), 1)
            self.assertIn("$ref", property_schema["allOf"][0])
            return property_schema["allOf"][0]["$ref"].split("/")[-1]
        if property_schema.get("type") == "array":
            # "type": "array"
            # "items":
            #   "$ref": "#/components/schemas/ComponentName"
            self.assertIn("items", property_schema)
            self.assertIn("$ref", property_schema["items"])
            return property_schema["items"]["$ref"].split("/")[-1]
        # TODO: extend to handle other cases as needed?
        self.fail(f"Property schema not as expected: {property_schema}")
        return None

#### `get_schema_property(component_schema, property_name)`

Helper method to pull a specific property schema from a larger component schema already extracted.

Source code in `nautobot/core/testing/schema.py`

    48
    49
    50
    51
    def get_schema_property(self, component_schema, property_name):
        """Helper method to pull a specific property schema from a larger component schema already extracted."""
        self.assertIn(property_name, component_schema["properties"])
        return component_schema["properties"][property_name]

#### `validate_polymorphic_property(component_name, property_name, models=None, nullable=False, read_only=True, many=False)`

Bringing it all together.

This validates the schema to show that: - The component exists and has such a property - The property has the correct `nullable` and `readOnly` values - The property has the correct multiplicity - The property is a reference to another component - The property's referenced component is polymorphic and has the expected set of model content-types.

Returns:

Type | Description
--- | ---
`Tuple[ref_component_name, ref_component_schema]` | The referenced component's name and schema.

Source code in `nautobot/core/testing/schema.py`

     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
    def validate_polymorphic_property(
        self,
        component_name,
        property_name,
        models=None,
        nullable=False,
        read_only=True,
        many=False,
    ):
        """
        Bringing it all together.

        This validates the schema to show that:
        - The component exists and has such a property
        - The property has the correct `nullable` and `readOnly` values
        - The property has the correct multiplicity
        - The property is a reference to another component
        - The property's referenced component is polymorphic and has the expected set of model content-types.

        Returns:
            (Tuple[ref_component_name, ref_component_schema]): The referenced component's name and schema.
        """
        component_schema = self.get_component_schema(component_name)

        if nullable:
            self.assert_nullable_property(component_schema, property_name)
        else:
            self.assert_not_nullable_property(component_schema, property_name)

        if read_only:
            self.assert_read_only_property(component_schema, property_name)
        else:
            self.assert_not_read_only_property(component_schema, property_name)

        if many:
            self.assertEqual("array", self.get_schema_property(component_schema, property_name).get("type"))
        else:
            self.assertNotEqual("array", self.get_schema_property(component_schema, property_name).get("type"))

        ref_component_name = self.get_property_ref_component_name(component_schema, property_name)
        ref_component_schema = self.get_component_schema(ref_component_name)
        self.assert_component_mapped_by_object_type(ref_component_schema, models=models)

        return (ref_component_name, ref_component_schema)

## `nautobot.apps.testing.SeleniumTestCase`

Bases: `StaticLiveServerTestCase`, `testing.NautobotTestCaseMixin`

Base test case for Splinter Selenium integration testing with custom helper methods.

This extends `django.contrib.staticfiles.testing.StaticLiveServerTestCase` so there is no need to run `collectstatic` prior to running tests.

Source code in `nautobot/core/testing/integration.py`

     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
    126
    127
    128
    129
    130
    @override_settings(ALLOWED_HOSTS=["nautobot.example.com", SELENIUM_HOST, SELENIUM_HOST.split(".")[0]])
    @tag("integration")
    class SeleniumTestCase(StaticLiveServerTestCase, testing.NautobotTestCaseMixin):
        """
        Base test case for Splinter Selenium integration testing with custom helper methods.

        This extends `django.contrib.staticfiles.testing.StaticLiveServerTestCase`
        so there is no need to run `collectstatic` prior to running tests.
        """

        host = "0.0.0.0"  # noqa: S104  # hardcoded-bind-all-interfaces -- false positive
        selenium_host = SELENIUM_HOST  # Docker: `nautobot`; else `host.docker.internal`

        @classmethod
        def setUpClass(cls):
            super().setUpClass()
            # Instantiate the browser object.
            profile = cls._create_firefox_profile()
            cls.browser = Browser(
                "remote",
                command_executor=SELENIUM_URL,
                browser_profile=profile,
                # See: https://developer.mozilla.org/en-US/docs/Web/WebDriver/Timeouts
                # desired_capabilities={"timeouts": {"implicit": 60 * 60 * 1000 }},  # 1 hour timeout
            )

        def setUp(self):
            super().setUpNautobot(populate_status=True)

            self.password = "testpassword"  # noqa: S105  # hardcoded-password-string
            self.user.set_password(self.password)
            self.user.save()

        @classproperty  # https://github.com/PyCQA/pylint-django/issues/240
        def live_server_url(cls):  # pylint: disable=no-self-argument
            return f"http://{cls.selenium_host}:{cls.server_thread.port}"

        @classmethod
        def tearDownClass(cls):
            """Close down the browser after tests are ran."""
            cls.browser.quit()

        def login(self, username, password, login_url=LOGIN_URL, button_text="Log In"):
            """
            Navigate to `login_url` and perform a login w/ the provided `username` and `password`.
            """
            self.browser.visit(f"{self.live_server_url}{login_url}")
            self.browser.fill("username", username)
            self.browser.fill("password", password)
            self.browser.find_by_xpath(f"//button[text()='{button_text}']").first.click()

            if self.browser.is_text_present("Please enter a correct username and password."):
                self.fail(f"Unable to login in with username {username}")

        def logout(self):
            self.browser.visit(f"{self.live_server_url}/logout")

        @classmethod
        def _create_firefox_profile(cls):
            """
            Return a `FirefoxProfile` with speed-optimized preferences such as disabling image loading,
            enabling HTTP pipelining, among others.

            Credit: https://bit.ly/2TuHa9D
            """

            profile = webdriver.FirefoxProfile()
            for key, value in FIREFOX_PROFILE_PREFERENCES.items():
                profile.set_preference(key, value)

            return profile

### `login(username, password, login_url=LOGIN_URL, button_text='Log In')`

Navigate to `login_url` and perform a login w/ the provided `username` and `password`.

Source code in `nautobot/core/testing/integration.py`

    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    def login(self, username, password, login_url=LOGIN_URL, button_text="Log In"):
        """
        Navigate to `login_url` and perform a login w/ the provided `username` and `password`.
        """
        self.browser.visit(f"{self.live_server_url}{login_url}")
        self.browser.fill("username", username)
        self.browser.fill("password", password)
        self.browser.find_by_xpath(f"//button[text()='{button_text}']").first.click()

        if self.browser.is_text_present("Please enter a correct username and password."):
            self.fail(f"Unable to login in with username {username}")

### `tearDownClass()` `classmethod`

Close down the browser after tests are ran.

Source code in `nautobot/core/testing/integration.py`

     97
     98
     99
    100
    @classmethod
    def tearDownClass(cls):
        """Close down the browser after tests are ran."""
        cls.browser.quit()

## `nautobot.apps.testing.TestCase`

Bases: `mixins.NautobotTestCaseMixin`, `_TestCase`

Base class for all Nautobot-specific unit tests.

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

    34
    35
    36
    37
    38
    39
    40
    41
    @tag("unit")
    @override_settings(PAGINATE_COUNT=65000)
    class TestCase(mixins.NautobotTestCaseMixin, _TestCase):
        """Base class for all Nautobot-specific unit tests."""

        def setUp(self):
            """Initialize user and client."""
            super().setUpNautobot()

### `setUp()`

Initialize user and client.

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

    39
    40
    41
    def setUp(self):
        """Initialize user and client."""
        super().setUpNautobot()

## `nautobot.apps.testing.TransactionTestCase`

Bases: `_TransactionTestCase`, `NautobotTestCaseMixin`

Base test case class using the TransactionTestCase for unit testing

Source code in `nautobot/core/testing/__init__.py`

    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    @tag("unit")
    class TransactionTestCase(_TransactionTestCase, NautobotTestCaseMixin):
        """
        Base test case class using the TransactionTestCase for unit testing
        """

        # 'job_logs' is a proxy connection to the same (default) database that's used exclusively for Job logging
        databases = ("default", "job_logs")

        def setUp(self):
            """Provide a clean, post-migration state before each test case.

            django.test.TransactionTestCase truncates the database after each test runs. We need at least the default
            statuses present in the database in order to run tests."""
            super().setUp()
            self.setUpNautobot(client=True, populate_status=True)

### `setUp()`

Provide a clean, post-migration state before each test case.

django.test.TransactionTestCase truncates the database after each test runs. We need at least the default statuses present in the database in order to run tests.

Source code in `nautobot/core/testing/__init__.py`

    120
    121
    122
    123
    124
    125
    126
    def setUp(self):
        """Provide a clean, post-migration state before each test case.

        django.test.TransactionTestCase truncates the database after each test runs. We need at least the default
        statuses present in the database in order to run tests."""
        super().setUp()
        self.setUpNautobot(client=True, populate_status=True)

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

     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
    1480
    1481
    1482
    1483
    1484
    1485
    1486
    1487
    1488
    1489
    1490
    1491
    1492
    1493
    1494
    1495
    1496
    1497
    1498
    1499
    1500
    1501
    1502
    1503
    1504
    1505
    1506
    1507
    1508
    1509
    1510
    1511
    1512
    1513
    1514
    1515
    1516
    1517
    1518
    1519
    1520
    1521
    1522
    1523
    1524
    1525
    1526
    1527
    1528
    1529
    1530
    1531
    1532
    1533
    1534
    1535
    1536
    1537
    1538
    1539
    1540
    1541
    1542
    1543
    1544
    1545
    1546
    1547
    1548
    1549
    1550
    1551
    1552
    1553
    1554
    1555
    1556
    1557
    1558
    1559
    1560
    1561
    1562
    1563
    1564
    1565
    1566
    1567
    1568
    1569
    1570
    1571
    1572
    1573
    1574
    1575
    @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, extras_models.ChangeLoggedModel):
                    response_body = testing.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 testing.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 = users_models.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 = testing.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(extras_choices.RelationshipSideChoices.SIDE_SOURCE)),
                                response_body,
                                msg=response_body,
                            )
                        if content_type == relationship.destination_type:
                            self.assertIn(
                                escape(relationship.get_label(extras_choices.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)
                        if custom_field.type == extras_choices.CustomFieldTypeChoices.TYPE_MULTISELECT:
                            for value in instance.cf.get(custom_field.key):
                                self.assertIn(escape(str(value)), response_body, msg=response_body)
                        else:
                            self.assertIn(
                                escape(str(instance.cf.get(custom_field.key) 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 = users_models.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 = users_models.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 = testing.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 testing.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": testing.post_data(self.form_data),
                }
                response = self.client.post(**request)
                with testing.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 = users_models.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": testing.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" or "name".
                if isinstance(self._get_queryset().first(), TreeNode):
                    filter_by = self.slug_source if getattr(self, "slug_source", None) else "name"
                    instance = self._get_queryset().get(**{filter_by: self.form_data.get(filter_by)})
                    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 = lookup.get_changes_for_model(instance)
                    self.assertEqual(len(objectchanges), 1)
                    # Assert that Created By table row is updated with the user that created the object
                    self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_CREATE)
                    # Validate if detail view exists
                    validate = URLValidator()
                    detail_url = instance.get_absolute_url()
                    try:
                        validate(detail_url)
                        response = self.client.get(detail_url)
                        response_body = testing.extract_page_body(response.content.decode(response.charset))
                        advanced_tab_href = f"{detail_url}#advanced"
                        self.assertIn(advanced_tab_href, response_body)
                        self.assertIn("<td>Created By</td>", response_body)
                        self.assertIn("<td>nautobotuser</td>", response_body)
                    except ValidationError:
                        # Instance does not have a valid detail view, do nothing here.
                        pass

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

                # Assign constrained permission
                obj_perm = users_models.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": testing.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": testing.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):
                    filter_by = self.slug_source if getattr(self, "slug_source", None) else "name"
                    instance = self._get_queryset().get(**{filter_by: self.form_data.get(filter_by)})
                    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 getattr(self.model, "slug_source", None) 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 getattr(self.model, "slug_source", None) 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 testing.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": testing.post_data(self.form_data),
                }
                with testing.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 = users_models.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": testing.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 = lookup.get_changes_for_model(instance)
                    self.assertEqual(len(objectchanges), 1)
                    self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_UPDATE)
                    # Validate if detail view exists
                    validate = URLValidator()
                    detail_url = instance.get_absolute_url()
                    try:
                        validate(detail_url)
                        response = self.client.get(detail_url)
                        response_body = testing.extract_page_body(response.content.decode(response.charset))
                        advanced_tab_href = f"{detail_url}#advanced"
                        self.assertIn(advanced_tab_href, response_body)
                        self.assertIn("<td>Last Updated By</td>", response_body)
                        self.assertIn("<td>nautobotuser</td>", response_body)
                    except ValidationError:
                        # Instance does not have a valid detail view, do nothing here.
                        pass

            @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 = users_models.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": testing.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": testing.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 = testing.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 testing.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": testing.post_data({"confirm": True}),
                }
                with testing.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()
                instance_note_pk_list = []
                assigned_object_type = ContentType.objects.get_for_model(self.model)
                if hasattr(self.model, "notes") and isinstance(instance.notes, extras_querysets.NotesQuerySet):
                    notes = (
                        extras_models.Note(
                            assigned_object_type=assigned_object_type, assigned_object_id=instance.id, note="hello 1"
                        ),
                        extras_models.Note(
                            assigned_object_type=assigned_object_type, assigned_object_id=instance.id, note="hello 2"
                        ),
                        extras_models.Note(
                            assigned_object_type=assigned_object_type, assigned_object_id=instance.id, note="hello 3"
                        ),
                    )
                    for note in notes:
                        note.validated_save()
                        instance_note_pk_list.append(note.pk)

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

                # 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": testing.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 = lookup.get_changes_for_model(instance)
                    self.assertEqual(len(objectchanges), 1)
                    self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_DELETE)

                if hasattr(self.model, "notes") and isinstance(instance.notes, extras_querysets.NotesQuerySet):
                    # Verify Notes deletion
                    with self.assertRaises(ObjectDoesNotExist):
                        extras_models.Note.objects.get(assigned_object_id=instance.pk)

                    note_objectchanges = extras_models.ObjectChange.objects.filter(
                        changed_object_id__in=instance_note_pk_list
                    )
                    self.assertEqual(note_objectchanges.count(), 3)
                    for object_change in note_objectchanges:
                        self.assertEqual(object_change.action, extras_choices.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 = users_models.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 = lookup.get_changes_for_model(instance)
                    self.assertEqual(len(objectchanges), 1)
                    self.assertEqual(objectchanges[0].action, extras_choices.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 = users_models.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": testing.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": testing.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 lookup.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(helpers.validated_viewname(self.model, "list"))

            def get_title(self):
                return helpers.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 = testing.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)
                if instance1.get_absolute_url() in content:
                    self.assertNotIn(instance2.get_absolute_url(), content, msg=content)

            @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 = testing.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("None", 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.core.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.core.filters:{filterset.__name__}: Unknown filter field "ice_cream_flavor"',
                    ],
                )
                self.assertHttpStatus(response, 200)
                content = testing.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.assertIn("None", content, msg=content)
                if hasattr(self.model, "name"):
                    self.assertRegex(content, r">\s*" + re.escape(instance1.name) + r"\s*<", msg=content)
                    self.assertRegex(content, r">\s*" + re.escape(instance2.name) + r"\s*<", msg=content)
                if instance1.get_absolute_url() in content:
                    self.assertIn(instance2.get_absolute_url(), content, msg=content)

            @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
            def test_list_objects_without_permission(self):
                # Try GET without permission
                with testing.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 = users_models.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 = users_models.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 = testing.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(instance1.name) + r"\s*<", msg=content)
                    self.assertNotRegex(content, r">\s*" + re.escape(instance2.name) + r"\s*<", 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 = users_models.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
                )

        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": testing.post_data(self.bulk_create_data),
                }

                # Try POST without permission
                with testing.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": testing.post_data(self.bulk_create_data),
                }

                # Assign non-constrained permission
                obj_perm = users_models.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": testing.post_data(self.bulk_create_data),
                }

                # Assign constrained permission
                obj_perm = users_models.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.

            Note that CSV import, since it's now implemented via the REST API,
            is also exercised by APIViewTestCases.CreateObjectViewTestCase.test_recreate_object_csv().

            :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 testing.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 testing.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 = users_models.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 = users_models.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
                response = self.client.post(self._get_url("import"), data)
                self.assertHttpStatus(response, 200)
                self.assertEqual(
                    self._get_queryset().count(),
                    initial_count + len(self.csv_data) - 1,
                    testing.extract_page_body(response.content.decode(response.charset)),
                )

            @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 = users_models.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 testing.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(testing.post_data(self.bulk_edit_data))

                # Assign model-level permission
                obj_perm = users_models.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 = users_models.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 = testing.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_form_contains_all_filtered(self):
                # We are testing the intermediary step of bulk_edit with pagination applied and additional filter.
                # i.e. "_all" passed in the form and filter using query params.
                self.add_permissions(f"{self.model._meta.app_label}.change_{self.model._meta.model_name}")

                pk_iter = iter(self._get_queryset().values_list("pk", flat=True))
                try:
                    first_pk = next(pk_iter)
                    second_pk = next(pk_iter)
                    third_pk = next(pk_iter)
                except StopIteration:
                    self.fail(f"Test requires at least three instances of {self.model._meta.model_name} to be defined.")

                post_data = testing.post_data(self.bulk_edit_data)

                # Open bulk update form with first two objects
                selected_data = {
                    "pk": third_pk,  # This is ignored when filtering with "_all"
                    "_all": "on",
                    **post_data,
                }
                query_string = urlencode({"id": (first_pk, second_pk)}, doseq=True)
                response = self.client.post(f"{self._get_url('bulk_edit')}?{query_string}", 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 = testing.extract_page_body(response.content.decode(response.charset))
                # Check if the first and second pk is passed into the form.
                self.assertIn(f'<input type="hidden" name="pk" value="{first_pk}"', response_body)
                self.assertIn(f'<input type="hidden" name="pk" value="{second_pk}"', response_body)
                self.assertIn("Editing 2 ", response_body)
                # Check if the third pk is not passed into the form.
                self.assertNotIn(f'<input type="hidden" name="pk" value="{third_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 = next(iter(self.bulk_edit_data.keys()))
                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]

                # Assign constrained permission
                obj_perm = users_models.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(testing.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 testing.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 testing.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 = users_models.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 = users_models.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 = testing.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_form_contains_all_filtered(self):
                # We are testing the intermediary step of bulk_delete with pagination applied and additional filter.
                # i.e. "_all" passed in the form and filter using query params.
                self.add_permissions(f"{self.model._meta.app_label}.delete_{self.model._meta.model_name}")

                pk_iter = iter(self._get_queryset().values_list("pk", flat=True))
                try:
                    first_pk = next(pk_iter)
                    second_pk = next(pk_iter)
                    third_pk = next(pk_iter)
                except StopIteration:
                    self.fail(f"Test requires at least three instances of {self.model._meta.model_name} to be defined.")

                # Open bulk delete form with first two objects
                selected_data = {
                    "pk": third_pk,  # This is ignored when filtering with "_all"
                    "_all": "on",
                }
                query_string = urlencode({"id": (first_pk, second_pk)}, doseq=True)
                response = self.client.post(f"{self._get_url('bulk_delete')}?{query_string}", selected_data)
                # Expect a 200 status cause we are only rendering the bulk delete table after pressing Delete Selected button.
                self.assertHttpStatus(response, 200)
                response_body = testing.extract_page_body(response.content.decode(response.charset))
                # Check if the first and second pk is passed into the form.
                self.assertIn(f'<input type="hidden" name="pk" value="{first_pk}"', response_body)
                self.assertIn(f'<input type="hidden" name="pk" value="{second_pk}"', response_body)
                self.assertIn("<strong>Warning:</strong> The following operation will delete 2 ", response_body)
                # Check if the third pk is not passed into the form.
                self.assertNotIn(f'<input type="hidden" name="pk" value="{third_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 = users_models.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 testing.disable_warnings("django.request"):
                    self.assertHttpStatus(self.client.get(self._get_url("bulk_rename")), 403)

                # Try POST without permission
                with testing.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 = users_models.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 = users_models.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 = users_models.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": testing.post_data({"pk": data["device"]}),
                    }
                else:
                    url = reverse(f"virtualization:virtualmachine_bulk_add_{self.model._meta.model_name}")
                    request = {
                        "path": url,
                        "data": testing.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"] = testing.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 = users_models.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)} {helpers.bettertitle(verbose_name_plural)} "
                        f"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/core/testing/views.py`

    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
    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 testing.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 testing.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 = users_models.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 = users_models.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 = testing.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_form_contains_all_filtered(self):
            # We are testing the intermediary step of bulk_delete with pagination applied and additional filter.
            # i.e. "_all" passed in the form and filter using query params.
            self.add_permissions(f"{self.model._meta.app_label}.delete_{self.model._meta.model_name}")

            pk_iter = iter(self._get_queryset().values_list("pk", flat=True))
            try:
                first_pk = next(pk_iter)
                second_pk = next(pk_iter)
                third_pk = next(pk_iter)
            except StopIteration:
                self.fail(f"Test requires at least three instances of {self.model._meta.model_name} to be defined.")

            # Open bulk delete form with first two objects
            selected_data = {
                "pk": third_pk,  # This is ignored when filtering with "_all"
                "_all": "on",
            }
            query_string = urlencode({"id": (first_pk, second_pk)}, doseq=True)
            response = self.client.post(f"{self._get_url('bulk_delete')}?{query_string}", selected_data)
            # Expect a 200 status cause we are only rendering the bulk delete table after pressing Delete Selected button.
            self.assertHttpStatus(response, 200)
            response_body = testing.extract_page_body(response.content.decode(response.charset))
            # Check if the first and second pk is passed into the form.
            self.assertIn(f'<input type="hidden" name="pk" value="{first_pk}"', response_body)
            self.assertIn(f'<input type="hidden" name="pk" value="{second_pk}"', response_body)
            self.assertIn("<strong>Warning:</strong> The following operation will delete 2 ", response_body)
            # Check if the third pk is not passed into the form.
            self.assertNotIn(f'<input type="hidden" name="pk" value="{third_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 = users_models.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/core/testing/views.py`

    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    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 testing.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/core/testing/views.py`

    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
    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 testing.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(testing.post_data(self.bulk_edit_data))

            # Assign model-level permission
            obj_perm = users_models.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 = users_models.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 = testing.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_form_contains_all_filtered(self):
            # We are testing the intermediary step of bulk_edit with pagination applied and additional filter.
            # i.e. "_all" passed in the form and filter using query params.
            self.add_permissions(f"{self.model._meta.app_label}.change_{self.model._meta.model_name}")

            pk_iter = iter(self._get_queryset().values_list("pk", flat=True))
            try:
                first_pk = next(pk_iter)
                second_pk = next(pk_iter)
                third_pk = next(pk_iter)
            except StopIteration:
                self.fail(f"Test requires at least three instances of {self.model._meta.model_name} to be defined.")

            post_data = testing.post_data(self.bulk_edit_data)

            # Open bulk update form with first two objects
            selected_data = {
                "pk": third_pk,  # This is ignored when filtering with "_all"
                "_all": "on",
                **post_data,
            }
            query_string = urlencode({"id": (first_pk, second_pk)}, doseq=True)
            response = self.client.post(f"{self._get_url('bulk_edit')}?{query_string}", 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 = testing.extract_page_body(response.content.decode(response.charset))
            # Check if the first and second pk is passed into the form.
            self.assertIn(f'<input type="hidden" name="pk" value="{first_pk}"', response_body)
            self.assertIn(f'<input type="hidden" name="pk" value="{second_pk}"', response_body)
            self.assertIn("Editing 2 ", response_body)
            # Check if the third pk is not passed into the form.
            self.assertNotIn(f'<input type="hidden" name="pk" value="{third_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 = next(iter(self.bulk_edit_data.keys()))
            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]

            # Assign constrained permission
            obj_perm = users_models.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(testing.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.

Note that CSV import, since it's now implemented via the REST API, is also exercised by APIViewTestCases.CreateObjectViewTestCase.test_recreate_object_csv().

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

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

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

        Note that CSV import, since it's now implemented via the REST API,
        is also exercised by APIViewTestCases.CreateObjectViewTestCase.test_recreate_object_csv().

        :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 testing.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 testing.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 = users_models.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 = users_models.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
            response = self.client.post(self._get_url("import"), data)
            self.assertHttpStatus(response, 200)
            self.assertEqual(
                self._get_queryset().count(),
                initial_count + len(self.csv_data) - 1,
                testing.extract_page_body(response.content.decode(response.charset)),
            )

        @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 = users_models.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/core/testing/views.py`

    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
    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 testing.disable_warnings("django.request"):
                self.assertHttpStatus(self.client.get(self._get_url("bulk_rename")), 403)

            # Try POST without permission
            with testing.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 = users_models.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 = users_models.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/core/testing/views.py`

    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
    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": testing.post_data(self.bulk_create_data),
            }

            # Try POST without permission
            with testing.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": testing.post_data(self.bulk_create_data),
            }

            # Assign non-constrained permission
            obj_perm = users_models.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": testing.post_data(self.bulk_create_data),
            }

            # Assign constrained permission
            obj_perm = users_models.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/core/testing/views.py`

    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
    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 testing.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": testing.post_data(self.form_data),
            }
            response = self.client.post(**request)
            with testing.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 = users_models.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": testing.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" or "name".
            if isinstance(self._get_queryset().first(), TreeNode):
                filter_by = self.slug_source if getattr(self, "slug_source", None) else "name"
                instance = self._get_queryset().get(**{filter_by: self.form_data.get(filter_by)})
                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 = lookup.get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                # Assert that Created By table row is updated with the user that created the object
                self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_CREATE)
                # Validate if detail view exists
                validate = URLValidator()
                detail_url = instance.get_absolute_url()
                try:
                    validate(detail_url)
                    response = self.client.get(detail_url)
                    response_body = testing.extract_page_body(response.content.decode(response.charset))
                    advanced_tab_href = f"{detail_url}#advanced"
                    self.assertIn(advanced_tab_href, response_body)
                    self.assertIn("<td>Created By</td>", response_body)
                    self.assertIn("<td>nautobotuser</td>", response_body)
                except ValidationError:
                    # Instance does not have a valid detail view, do nothing here.
                    pass

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

            # Assign constrained permission
            obj_perm = users_models.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": testing.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": testing.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):
                filter_by = self.slug_source if getattr(self, "slug_source", None) else "name"
                instance = self._get_queryset().get(**{filter_by: self.form_data.get(filter_by)})
                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 getattr(self.model, "slug_source", None) 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 getattr(self.model, "slug_source", None) 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/core/testing/views.py`

    403
    404
    405
    406
    407
    408
    409
    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 getattr(self.model, "slug_source", None) 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/core/testing/views.py`

    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    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 getattr(self.model, "slug_source", None) 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/core/testing/views.py`

    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
    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 = testing.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 testing.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": testing.post_data({"confirm": True}),
            }
            with testing.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()
            instance_note_pk_list = []
            assigned_object_type = ContentType.objects.get_for_model(self.model)
            if hasattr(self.model, "notes") and isinstance(instance.notes, extras_querysets.NotesQuerySet):
                notes = (
                    extras_models.Note(
                        assigned_object_type=assigned_object_type, assigned_object_id=instance.id, note="hello 1"
                    ),
                    extras_models.Note(
                        assigned_object_type=assigned_object_type, assigned_object_id=instance.id, note="hello 2"
                    ),
                    extras_models.Note(
                        assigned_object_type=assigned_object_type, assigned_object_id=instance.id, note="hello 3"
                    ),
                )
                for note in notes:
                    note.validated_save()
                    instance_note_pk_list.append(note.pk)

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

            # 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": testing.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 = lookup.get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_DELETE)

            if hasattr(self.model, "notes") and isinstance(instance.notes, extras_querysets.NotesQuerySet):
                # Verify Notes deletion
                with self.assertRaises(ObjectDoesNotExist):
                    extras_models.Note.objects.get(assigned_object_id=instance.pk)

                note_objectchanges = extras_models.ObjectChange.objects.filter(
                    changed_object_id__in=instance_note_pk_list
                )
                self.assertEqual(note_objectchanges.count(), 3)
                for object_change in note_objectchanges:
                    self.assertEqual(object_change.action, extras_choices.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 = users_models.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 = lookup.get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, extras_choices.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 = users_models.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": testing.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": testing.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/core/testing/views.py`

    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    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 = testing.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/core/testing/views.py`

    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467
    1468
    1469
    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/core/testing/views.py`

    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    1480
    1481
    1482
    1483
    1484
    1485
    1486
    1487
    1488
    1489
    1490
    1491
    1492
    1493
    1494
    1495
    1496
    1497
    1498
    1499
    1500
    1501
    1502
    1503
    1504
    1505
    1506
    1507
    1508
    1509
    1510
    1511
    1512
    1513
    1514
    1515
    1516
    1517
    1518
    1519
    1520
    1521
    1522
    1523
    1524
    1525
    1526
    1527
    1528
    1529
    1530
    1531
    1532
    1533
    1534
    1535
    1536
    1537
    1538
    1539
    1540
    1541
    1542
    1543
    1544
    1545
    1546
    1547
    1548
    1549
    1550
    1551
    1552
    1553
    1554
    1555
    1556
    1557
    1558
    1559
    1560
    1561
    1562
    1563
    1564
    1565
    1566
    1567
    1568
    1569
    1570
    1571
    1572
    1573
    1574
    1575
    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 = users_models.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": testing.post_data({"pk": data["device"]}),
                }
            else:
                url = reverse(f"virtualization:virtualmachine_bulk_add_{self.model._meta.model_name}")
                request = {
                    "path": url,
                    "data": testing.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"] = testing.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 = users_models.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)} {helpers.bettertitle(verbose_name_plural)} "
                    f"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/core/testing/views.py`

    1492
    1493
    1494
    1495
    1496
    1497
    1498
    1499
    1500
    1501
    1502
    1503
    1504
    1505
    1506
    1507
    1508
    1509
    1510
    1511
    1512
    1513
    1514
    1515
    1516
    1517
    1518
    1519
    1520
    1521
    1522
    1523
    1524
    1525
    1526
    1527
    1528
    1529
    1530
    1531
    1532
    1533
    1534
    1535
    1536
    1537
    1538
    @override_settings(EXEMPT_VIEW_PERMISSIONS=["*"])
    def test_bulk_add_component(self):
        """Test bulk-adding this component to devices/virtual-machines."""
        obj_perm = users_models.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": testing.post_data({"pk": data["device"]}),
            }
        else:
            url = reverse(f"virtualization:virtualmachine_bulk_add_{self.model._meta.model_name}")
            request = {
                "path": url,
                "data": testing.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"] = testing.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/core/testing/views.py`

    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
    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 testing.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": testing.post_data(self.form_data),
            }
            with testing.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 = users_models.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": testing.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 = lookup.get_changes_for_model(instance)
                self.assertEqual(len(objectchanges), 1)
                self.assertEqual(objectchanges[0].action, extras_choices.ObjectChangeActionChoices.ACTION_UPDATE)
                # Validate if detail view exists
                validate = URLValidator()
                detail_url = instance.get_absolute_url()
                try:
                    validate(detail_url)
                    response = self.client.get(detail_url)
                    response_body = testing.extract_page_body(response.content.decode(response.charset))
                    advanced_tab_href = f"{detail_url}#advanced"
                    self.assertIn(advanced_tab_href, response_body)
                    self.assertIn("<td>Last Updated By</td>", response_body)
                    self.assertIn("<td>nautobotuser</td>", response_body)
                except ValidationError:
                    # Instance does not have a valid detail view, do nothing here.
                    pass

        @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 = users_models.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": testing.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": testing.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/core/testing/views.py`

    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    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/core/testing/views.py`

    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    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/core/testing/views.py`

    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
    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, extras_models.ChangeLoggedModel):
                response_body = testing.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 testing.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 = users_models.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 = testing.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(extras_choices.RelationshipSideChoices.SIDE_SOURCE)),
                            response_body,
                            msg=response_body,
                        )
                    if content_type == relationship.destination_type:
                        self.assertIn(
                            escape(relationship.get_label(extras_choices.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)
                    if custom_field.type == extras_choices.CustomFieldTypeChoices.TYPE_MULTISELECT:
                        for value in instance.cf.get(custom_field.key):
                            self.assertIn(escape(str(value)), response_body, msg=response_body)
                    else:
                        self.assertIn(
                            escape(str(instance.cf.get(custom_field.key) 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 = users_models.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 = users_models.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 = testing.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/core/testing/views.py`

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

        filterset = None

        def get_filterset(self):
            return self.filterset or lookup.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(helpers.validated_viewname(self.model, "list"))

        def get_title(self):
            return helpers.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 = testing.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)
            if instance1.get_absolute_url() in content:
                self.assertNotIn(instance2.get_absolute_url(), content, msg=content)

        @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 = testing.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("None", 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.core.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.core.filters:{filterset.__name__}: Unknown filter field "ice_cream_flavor"',
                ],
            )
            self.assertHttpStatus(response, 200)
            content = testing.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.assertIn("None", content, msg=content)
            if hasattr(self.model, "name"):
                self.assertRegex(content, r">\s*" + re.escape(instance1.name) + r"\s*<", msg=content)
                self.assertRegex(content, r">\s*" + re.escape(instance2.name) + r"\s*<", msg=content)
            if instance1.get_absolute_url() in content:
                self.assertIn(instance2.get_absolute_url(), content, msg=content)

        @override_settings(EXEMPT_VIEW_PERMISSIONS=[])
        def test_list_objects_without_permission(self):
            # Try GET without permission
            with testing.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 = users_models.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 = users_models.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 = testing.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(instance1.name) + r"\s*<", msg=content)
                self.assertNotRegex(content, r">\s*" + re.escape(instance2.name) + r"\s*<", 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 = users_models.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
            )

#### `test_list_objects_unknown_filter_no_strict_filtering()`

Verify that without STRICT_FILTERING, an unknown filter is ignored.

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

    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
    @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.core.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.core.filters:{filterset.__name__}: Unknown filter field "ice_cream_flavor"',
            ],
        )
        self.assertHttpStatus(response, 200)
        content = testing.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.assertIn("None", content, msg=content)
        if hasattr(self.model, "name"):
            self.assertRegex(content, r">\s*" + re.escape(instance1.name) + r"\s*<", msg=content)
            self.assertRegex(content, r">\s*" + re.escape(instance2.name) + r"\s*<", msg=content)
        if instance1.get_absolute_url() in content:
            self.assertIn(instance2.get_absolute_url(), content, msg=content)

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

    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    @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 = testing.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("None", 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/core/testing/views.py`

    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    @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 = users_models.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/core/testing/views.py`

    1440
    1441
    1442
    1443
    1444
    1445
    1446
    1447
    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    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/core/testing/views.py`

    1422
    1423
    1424
    1425
    1426
    1427
    1428
    1429
    1430
    1431
    1432
    1433
    1434
    1435
    1436
    1437
    1438
    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

## `nautobot.apps.testing.create_job_result_and_run_job(module, name, source='local', *args, **kwargs)`

Test helper function to call get_job_class_and_model() then call run_job_for_testing().

Source code in `nautobot/core/testing/__init__.py`

    80
    81
    82
    83
    84
    85
    def create_job_result_and_run_job(module, name, source="local", *args, **kwargs):
        """Test helper function to call get_job_class_and_model() then call run_job_for_testing()."""
        _job_class, job_model = get_job_class_and_model(module, name, source)
        job_result = run_job_for_testing(job=job_model, **kwargs)
        job_result.refresh_from_db()
        return job_result

## `nautobot.apps.testing.create_test_user(username='testuser', permissions=None)`

Create a User with the given permissions.

Source code in `nautobot/core/testing/utils.py`

    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    def create_test_user(username="testuser", permissions=None):
        """
        Create a User with the given permissions.
        """
        user = User.objects.create_user(username=username)
        if permissions is None:
            permissions = ()
        for perm_name in permissions:
            app, codename = perm_name.split(".")
            perm = Permission.objects.get(content_type__app_label=app, codename=codename)
            user.user_permissions.add(perm)

        return user

## `nautobot.apps.testing.disable_warnings(logger_name)`

Temporarily suppress expected warning messages to keep the test output clean.

Source code in `nautobot/core/testing/utils.py`

    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    @contextmanager
    def disable_warnings(logger_name):
        """
        Temporarily suppress expected warning messages to keep the test output clean.
        """
        logger = logging.getLogger(logger_name)
        current_level = logger.level
        logger.setLevel(logging.ERROR)
        yield
        logger.setLevel(current_level)

## `nautobot.apps.testing.extract_form_failures(content)`

Given decoded HTML content from an HTTP response, return a list of form errors.

Source code in `nautobot/core/testing/utils.py`

    58
    59
    60
    61
    62
    63
    def extract_form_failures(content):
        """
        Given decoded HTML content from an HTTP response, return a list of form errors.
        """
        FORM_ERROR_REGEX = r"<!-- FORM-ERROR (.*) -->"
        return re.findall(FORM_ERROR_REGEX, content)

## `nautobot.apps.testing.extract_page_body(content)`

Given raw HTML content from an HTTP response, extract the main div only.

...
...
...

Source code in `nautobot/core/testing/utils.py`

    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    def extract_page_body(content):
        """
        Given raw HTML content from an HTTP response, extract the main div only.

        <html>
          <head>...</head>
          <body>
            <nav>...</nav>
            <div class="container-fluid wrapper"> <!-- BEGIN -->
              ...
            </div> <!-- END -->
            <footer class="footer">...</footer>
            ...
          </body>
        </html>
        """
        try:
            return re.findall(r"(?<=</nav>).*(?=<footer)", content, flags=(re.MULTILINE | re.DOTALL))[0]
        except IndexError:
            return content

## `nautobot.apps.testing.generate_random_device_asset_tag_of_specified_size(size)`

For testing purposes only; it returns a random string of size 100 consisting of letters and numbers.

Source code in `nautobot/core/testing/utils.py`

    114
    115
    116
    117
    118
    119
    def generate_random_device_asset_tag_of_specified_size(size):
        """
        For testing purposes only; it returns a random string of size 100 consisting of letters and numbers.
        """
        asset_tag = "".join(random.choices(string.ascii_letters + string.digits, k=size))  # noqa: S311  # suspicious-non-cryptographic-random-usage
        return asset_tag

## `nautobot.apps.testing.get_deletable_objects(model, queryset)`

Returns a subset of objects in the given queryset that have no protected relationships that would prevent deletion.

Source code in `nautobot/core/testing/utils.py`

    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    def get_deletable_objects(model, queryset):
        """
        Returns a subset of objects in the given queryset that have no protected relationships that would prevent deletion.
        """
        q = Q()
        for field in model._meta.get_fields(include_parents=True):
            if getattr(field, "on_delete", None) is PROTECT:
                q &= Q(**{f"{field.name}__isnull": True})
            # Only delete leaf nodes of trees to reduce complexity
            if isinstance(field, (TreeNodeForeignKey)):
                q &= Q(**{f"{field.related_query_name()}__isnull": True})
        return queryset.filter(q)

## `nautobot.apps.testing.get_job_class_and_model(module, name, source='local')`

Test helper function to look up a job class and job model and ensure the latter is enabled.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`module` | `str` | Job module name | required
`name` | `str` | Job class name | required
`source` | `str` | Job grouping (default: "local") | `'local'`

Returns:

Type | Description
--- | ---
`JobClassInfo` | Named 2-tuple of (job_class, job_model)

Source code in `nautobot/core/testing/__init__.py`

     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    def get_job_class_and_model(module, name, source="local"):
        """
        Test helper function to look up a job class and job model and ensure the latter is enabled.

        Args:
            module (str): Job module name
            name (str): Job class name
            source (str): Job grouping (default: "local")

        Returns:
            (JobClassInfo): Named 2-tuple of (job_class, job_model)
        """
        job_class = get_job(f"{module}.{name}")
        job_model = Job.objects.get(module_name=module, job_class_name=name)
        job_model.enabled = True
        job_model.validated_save()
        return JobClassInfo(job_class, job_model)

## `nautobot.apps.testing.post_data(data)`

Take a dictionary of test data (suitable for comparison to an instance) and return a dict suitable for POSTing.

Source code in `nautobot/core/testing/utils.py`

    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    def post_data(data):
        """
        Take a dictionary of test data (suitable for comparison to an instance) and return a dict suitable for POSTing.
        """
        ret = {}

        for key, value in data.items():
            if value is None:
                ret[key] = ""
                ret.setdefault("_nullify", [])
                ret["_nullify"].append(key)
            elif isinstance(value, (list, tuple)):
                if value and hasattr(value[0], "pk"):
                    # Value is a list of instances
                    ret[key] = [v.pk for v in value]
                else:
                    ret[key] = value
            elif hasattr(value, "pk"):
                # Value is an instance
                ret[key] = value.pk
            else:
                ret[key] = str(value)

        return ret

## `nautobot.apps.testing.run_job_for_testing(job, username='test-user', profile=False, **kwargs)`

Provide a common interface to run Nautobot jobs as part of unit tests.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`job` | `Job` | Job model instance (not Job class) to run | required
`username` | `str` | Username of existing or to-be-created User account to own the JobResult. | `'test-user'`
`profile` | `bool` | Whether to profile the job execution. | `False`

Other Parameters:

Name | Type | Description
--- | --- | ---
`**kwargs` | `any` | Input keyword arguments for Job run method.

Returns:

Type | Description
--- | ---
`JobResult` | representing the executed job

Source code in `nautobot/core/testing/__init__.py`

    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
    def run_job_for_testing(job, username="test-user", profile=False, **kwargs):
        """
        Provide a common interface to run Nautobot jobs as part of unit tests.

        Args:
            job (Job): Job model instance (not Job class) to run
            username (str): Username of existing or to-be-created User account to own the JobResult.
            profile (bool): Whether to profile the job execution.

        Keyword Args:
            **kwargs (any): Input keyword arguments for Job run method.

        Returns:
            (JobResult): representing the executed job
        """
        # Enable the job if it wasn't enabled before
        if not job.enabled:
            job.enabled = True
            job.validated_save()

        user_instance, _ = User.objects.get_or_create(
            username=username, defaults={"is_superuser": True, "password": "password"}
        )
        # Run the job synchronously in the current thread as if it were being executed by a worker
        job_result = JobResult.execute_job(
            job_model=job,
            user=user_instance,
            profile=profile,
            **kwargs,
        )
        return job_result