I am trying to test DRF endpoints, and trying to add mixings dynamically to a test in order to execute tests again each method allowed in the endpoint (get, post, put, patch, delete)
So, my idea is to make a base test class that will automatically add some mixings to test endpoints if they are allowed. And I can create the actual test that will inherit from this base class.
The code:
from rest_framework.test import APITestCase
class GetTestMixin:
def test_get_all(self):
response = self.client.get(self.uri)
self.assertEqual(response.status_code,status.HTTP_200_OK)
class AutoMixinMeta(type):
def __call__(cls, *args, **kwargs):
allowed_methods = ['get', 'post']
# cls would be the Test class, for example TestExample
# cls.__bases__ is a tuple with the classes inherited in the Test class, for example:
# (<class 'unit_tests.endpoints.base_test.RESTTestCase'>, <class 'rest_framework.test.APITestCase'>)
bases = cls.__bases__
for method in allowed_methods:
bases += (cls.method_mixins[method.lower()],)
# Create a new instance with all the mixins
cls = type(cls.__name__, bases, dict(cls.__dict__))
return type.__call__(cls, *args, **kwargs)
class RESTTestCase(metaclass=AutoMixinMeta):
uri = None
method_mixins = {
'post': PostTestMixin,
'get': GetTestMixin,
}
class TestExample(RESTTestCase, APITestCase):
uri = reverse('somemodel-list')
I was expecting test_get_all to be executed, but it is not.
Mixings are in place. I made a dummy method inside TestExample
and put a debugger in place, and checked it, like this:
(Pdb) self.__class__
<class 'TestExample'>
(Pdb) self.__class__.__bases__
(<class 'RESTTestCase'>, <class 'rest_framework.test.APITestCase'>, <class 'GetTestMixin'>)