I have exposed my database model using Django-rest-framework view sets and routers, and I am trying to write the unit tests for it.
Here are my API and test code
Viewsets.py
class Model1ViewSet(viewsets.ReadOnlyModelViewSet):
model = Model1
serializer_class = Model1Serializer
filter_class = Model1Filter
filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter)
ordering = ('id', 'cl1')
Serializer.py
class Model1Serializer(serializers.HyperlinkedModelSerializer):
chip = serializers.HyperlinkedRelatedField(view_name="some-detail")
class Meta:
model = Model1
fields = ('url', 'id', 'cl1', 'cl2', 'cl3', 'cl4')
depth = 1
Unit-tests
from rest_framework.test import APIClient
class TestModel1Api(unittest.TestCase):
def setUp(self):
self.client = APIClient()
def test_Model1_list(self):
response = self.client.get(reverse('Model1-list'))
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_Model1_detail(self):
mm_objs = Model1.objects.all()
if mm_objs:
response = self.client.get(reverse('Model1-detail', args=[mm_objs[0].id]))
self.assertEqual(response.status_code, status.HTTP_200_OK)
I don't want to connect to the database for unit testing because it falls under integration tests.
Is there any way to mock the database? I know how to apply mocking for standard view functions but here mocking is not working.
REST APIs are usually rigorously tested during integration testing. However, a good developer should test REST endpoints even before integration in their Unit Tests, since they are a vital part of the code since it's the sole access point of every entity wanting to make use of the services in the server.
For Django REST Framework to work on top of Django, you need to add rest_framework in INSTALLED_APPS, in settings.py. Bingo..!! Django REST Framework is successfully installed, one case use it in any app of Django.
When you run manage.py test
then the base of your database will be created but it contains no data. To do that you can simply create the necessary objects yourself or use something like FactoryBoy
Just keep in mind that the database is cleaned of data from previous test methods when starting a new one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With