django DRF测试get_queryset中的Swagger假视图

ulmd4ohb  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(141)

我可以在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)

查看次数.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"
        )
  • TestCase* 运行正常,我得到了预期的输出。但是在test_report中,这一行没有被测试。

正如我们所看到的,红线仍然显示未测试,因为它期望swagger_faker_view变量为True
有人知道如何为这个场景编写测试用例吗?

iyr7buue

iyr7buue1#

你可以添加另一个装饰器到你的测试中来应用它,如下所示:

@patch.object(CatalogView, "swagger_fake_view", True, create=True)

相关问题