Home > Software design >  DRF test Swagger Fake View in get_queryset
DRF test Swagger Fake View in get_queryset

Time:01-20

I am able to test get_queryset() in ReadOnlyModelViewSet like this.

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 case is running properly and I am getting the output as expected. But in test_report this line is not tested. enter image description here As we can see red line is still showing untested because it is expecting swagger_faker_view variable to be true.

does anyone know how to write test case for this scenario ?

CodePudding user response:

You can add another decorator to your test to apply this like so:

@patch.object(CatalogView, "swagger_fake_view", True, create=True)
  •  Tags:  
  • Related