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"
)
The TestCase is running correctly and I am getting the output as expected. But in test_report this line is not tested.
As we can see the red line is still showing untested because it is expecting the swagger_faker_view
variable to be True.
Does anyone know how to write a test case for this scenario?
You can add another decorator to your test to apply this like so:
@patch.object(CatalogView, "swagger_fake_view", True, create=True)