简体   繁体   中英

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?

PS 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.

我在我的测试用例中使用了reverse('<VERSION>:<VIEW_NAME>')

很晚但是对于那些有类似问题的人,你可以在调用视图的同时传递版本 -

response = CustomUserAPIView.as_view()(request, version='1.0')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM