I created some tests for my views before. Like that
class TestUserRegistrationViewUserCreate(APITestCase):
def setUp(self):
self.factory = APIRequestFactory()
def test_create_user(self):
data = {
'phone_number': '+79513332211',
'password': 'qwerty'
}
request = self.factory.post(reverse('user'), data=data)
response = CustomUserAPIView.as_view()(request)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
Everything worked great, until I was asked to add API versioning.
DRF supports versioning natively http://www.django-rest-framework.org/api-guide/versioning/ so I just went with it and added namespace-based versioning to my APIs with
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'
}
Now I need to rewrite my views unit tests to support versioning.
This problem is that in order to get versioned url through reverse
, I have to use
from rest_framework.reverse import reverse
reverse('bookings-list', request=request)
like in the docs.
But I don't have a request
objects in the tests, as I'm making one myself and versioned url required for making it.
What should I do?
P.S. I can implement versioning without using DRF one, with view decorator and a couple of utils functions and solve this problem, but it feels bad for me as I'm reinventing the wheel. Also, I might forget some edge cases too.
I use reverse('<VERSION>:<VIEW_NAME>')
in my test cases.
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