Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF testing views with versioning: versioned url retrieval

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.

like image 591
mkurnikov Avatar asked Nov 21 '22 07:11

mkurnikov


1 Answers

I use reverse('<VERSION>:<VIEW_NAME>') in my test cases.

like image 144
Till Kolter Avatar answered Dec 10 '22 16:12

Till Kolter