5

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.

mkurnikov
  • 1,581
  • 2
  • 16
  • 19

2 Answers2

1

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

Till Kolter
  • 602
  • 1
  • 9
  • 13
0

Pretty late but for those having similar issues you can pass the version while calling the view -

response = CustomUserAPIView.as_view()(request, version='1.0')
5parkp1ug
  • 462
  • 6
  • 17