DRF 在 get_queryset 中测试 Swagger 假视图
DRF test Swagger Fake View in get_queryset
我可以像这样在 ReadOnlyModelViewSet 中测试 get_queryset()。
class CatalogViewTests(APITestCase):
def setUp(self) -> None:
self.cur_user = UserFactory()
self.cur_dataset = DataSetFactory(created_by=self.cur_user)
@patch.object(CatalogView, "permission_classes", [])
def test_get_queryset(self):
url = reverse('data_tab:catalog-list')
response = self.client.get(url, format='json', **{DATASET_ID: self.cur_dataset.id})
self.assertEqual(response.status_code, status.HTTP_200_OK)
views.py
class CatalogView(ReadOnlyModelViewSet):
"""
Returns the Data tab catalog page with pagination
"""
serializer_class = CatalogSerializer
permission_classes = [UserHasDatasetChangeAccess]
pagination_class = StandardResultsSetPagination
queryset = TableMeta.objects.all()
renderer_classes = [JSONRenderer]
ordering_fields = ["created_on", "modified_on"]
ordering = ["-modified_on"]
def get_queryset(self):
if getattr(self, "swagger_fake_view", False):
# queryset just for schema generation metadata
return TableMeta.objects.none()
return TableMeta.objects.filter(
dataset=get_object_or_404(DataSet, id=self.request.META.get(DATASET_ID, ""))
).prefetch_related(
"table_columns", "table_metrics", "table_relationship_source"
)
测试用例 运行 正确,我得到了预期的输出。
但在 test_report 中,此行未经过测试。
正如我们所见,红线仍显示为未经测试,因为它期望 swagger_faker_view 变量为真。
有谁知道如何为这个场景编写测试用例?
您可以将另一个装饰器添加到您的测试中以像这样应用它:
@patch.object(CatalogView, "swagger_fake_view", True, create=True)
我可以像这样在 ReadOnlyModelViewSet 中测试 get_queryset()。
class CatalogViewTests(APITestCase):
def setUp(self) -> None:
self.cur_user = UserFactory()
self.cur_dataset = DataSetFactory(created_by=self.cur_user)
@patch.object(CatalogView, "permission_classes", [])
def test_get_queryset(self):
url = reverse('data_tab:catalog-list')
response = self.client.get(url, format='json', **{DATASET_ID: self.cur_dataset.id})
self.assertEqual(response.status_code, status.HTTP_200_OK)
views.py
class CatalogView(ReadOnlyModelViewSet):
"""
Returns the Data tab catalog page with pagination
"""
serializer_class = CatalogSerializer
permission_classes = [UserHasDatasetChangeAccess]
pagination_class = StandardResultsSetPagination
queryset = TableMeta.objects.all()
renderer_classes = [JSONRenderer]
ordering_fields = ["created_on", "modified_on"]
ordering = ["-modified_on"]
def get_queryset(self):
if getattr(self, "swagger_fake_view", False):
# queryset just for schema generation metadata
return TableMeta.objects.none()
return TableMeta.objects.filter(
dataset=get_object_or_404(DataSet, id=self.request.META.get(DATASET_ID, ""))
).prefetch_related(
"table_columns", "table_metrics", "table_relationship_source"
)
测试用例 运行 正确,我得到了预期的输出。
但在 test_report 中,此行未经过测试。
有谁知道如何为这个场景编写测试用例?
您可以将另一个装饰器添加到您的测试中以像这样应用它:
@patch.object(CatalogView, "swagger_fake_view", True, create=True)