I'm using AcceptHeaderVersioning with the Django rest framework as described here:
https://www.django-rest-framework.org/api-guide/versioning/#versioning-with-rest-framework
I'd like to test that the API returns the default version if no version is specified but the correct version when it is. But, it seems impossible to pass the version parameter to the test. Here's an example:
def testCheckVersion(self):
versions = [u'v0.1', u'v0.2']
self.key = APIKey(name='Example Key')
self.key.save()
for version in versions:
response = self.client.get('/api/data/',
VERSION="{0}".format(version),
**{'Api-Key': self.key.key})
self.assertEqual(response.status_code, 200)
content = json.loads(response.content)
self.assertEqual(content['api_version'], version)
This always gives the default api version (v0.2 in this case). I've tried various means of re-working the response =
line with no luck. This could perhaps be fixed by using QueryParameterVersioning instead but I'd rather not, so please let me know if you have any suggestions.
https://www.django-rest-framework.org/api-guide/versioning/#acceptheaderversioning
The documentation says that you need to include the version in the Accept
header, using their example:
Here's an example HTTP request using the accept header versioning style.
GET /bookings/ HTTP/1.1
Host: example.com
Accept: application/json; version=1.0
In the example request above request.version attribute would return the string '1.0'.
You have also set the headers in your self.client.get()
call incorrectly, based on the Django documentation https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.META:
With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.
Your resulting test should probably look a bit more like this:
def testCheckVersion(self):
versions = [u'v0.1', u'v0.2']
self.key = APIKey(name='Example Key')
self.key.save()
for version in versions:
### This call has changed
response = self.client.get(
'/api/data/',
HTTP_ACCEPT=f"application/json; version={version}"
)
self.assertEqual(response.status_code, 200)
content = json.loads(response.content)
self.assertEqual(content['api_version'], version)