1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
|
import os
import tempfile
import unittest
from django.http import HttpResponse
from django.test import override_settings
from django.urls import path, re_path
from rest_framework.compat import coreapi, coreschema
from rest_framework.parsers import FileUploadParser
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.response import Response
from rest_framework.test import APITestCase, CoreAPIClient
from rest_framework.views import APIView
def get_schema():
return coreapi.Document(
url='https://api.example.com/',
title='Example API',
content={
'simple_link': coreapi.Link('/example/', description='example link'),
'headers': coreapi.Link('/headers/'),
'location': {
'query': coreapi.Link('/example/', fields=[
coreapi.Field(name='example', schema=coreschema.String(description='example field'))
]),
'form': coreapi.Link('/example/', action='post', fields=[
coreapi.Field(name='example')
]),
'body': coreapi.Link('/example/', action='post', fields=[
coreapi.Field(name='example', location='body')
]),
'path': coreapi.Link('/example/{id}', fields=[
coreapi.Field(name='id', location='path')
])
},
'encoding': {
'multipart': coreapi.Link('/example/', action='post', encoding='multipart/form-data', fields=[
coreapi.Field(name='example')
]),
'multipart-body': coreapi.Link('/example/', action='post', encoding='multipart/form-data', fields=[
coreapi.Field(name='example', location='body')
]),
'urlencoded': coreapi.Link('/example/', action='post', encoding='application/x-www-form-urlencoded', fields=[
coreapi.Field(name='example')
]),
'urlencoded-body': coreapi.Link('/example/', action='post', encoding='application/x-www-form-urlencoded', fields=[
coreapi.Field(name='example', location='body')
]),
'raw_upload': coreapi.Link('/upload/', action='post', encoding='application/octet-stream', fields=[
coreapi.Field(name='example', location='body')
]),
},
'response': {
'download': coreapi.Link('/download/'),
'text': coreapi.Link('/text/')
}
}
)
def _iterlists(querydict):
if hasattr(querydict, 'iterlists'):
return querydict.iterlists()
return querydict.lists()
def _get_query_params(request):
# Return query params in a plain dict, using a list value if more
# than one item is present for a given key.
return {
key: (value[0] if len(value) == 1 else value)
for key, value in
_iterlists(request.query_params)
}
def _get_data(request):
if not isinstance(request.data, dict):
return request.data
# Coerce multidict into regular dict, and remove files to
# make assertions simpler.
if hasattr(request.data, 'iterlists') or hasattr(request.data, 'lists'):
# Use a list value if a QueryDict contains multiple items for a key.
return {
key: value[0] if len(value) == 1 else value
for key, value in _iterlists(request.data)
if key not in request.FILES
}
return {
key: value
for key, value in request.data.items()
if key not in request.FILES
}
def _get_files(request):
if not request.FILES:
return {}
return {
key: {'name': value.name, 'content': value.read()}
for key, value in request.FILES.items()
}
class SchemaView(APIView):
renderer_classes = [CoreJSONRenderer]
def get(self, request):
schema = get_schema()
return Response(schema)
class ListView(APIView):
def get(self, request):
return Response({
'method': request.method,
'query_params': _get_query_params(request)
})
def post(self, request):
if request.content_type:
content_type = request.content_type.split(';')[0]
else:
content_type = None
return Response({
'method': request.method,
'query_params': _get_query_params(request),
'data': _get_data(request),
'files': _get_files(request),
'content_type': content_type
})
class DetailView(APIView):
def get(self, request, id):
return Response({
'id': id,
'method': request.method,
'query_params': _get_query_params(request)
})
class UploadView(APIView):
parser_classes = [FileUploadParser]
def post(self, request):
return Response({
'method': request.method,
'files': _get_files(request),
'content_type': request.content_type
})
class DownloadView(APIView):
def get(self, request):
return HttpResponse('some file content', content_type='image/png')
class TextView(APIView):
def get(self, request):
return HttpResponse('123', content_type='text/plain')
class HeadersView(APIView):
def get(self, request):
headers = {
key[5:].replace('_', '-'): value
for key, value in request.META.items()
if key.startswith('HTTP_')
}
return Response({
'method': request.method,
'headers': headers
})
urlpatterns = [
path('', SchemaView.as_view()),
path('example/', ListView.as_view()),
re_path(r'^example/(?P<id>[0-9]+)/$', DetailView.as_view()),
path('upload/', UploadView.as_view()),
path('download/', DownloadView.as_view()),
path('text/', TextView.as_view()),
path('headers/', HeadersView.as_view()),
]
@unittest.skipUnless(coreapi, 'coreapi not installed')
@override_settings(ROOT_URLCONF='tests.test_api_client')
class APIClientTests(APITestCase):
def test_api_client(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
assert schema.title == 'Example API'
assert schema.url == 'https://api.example.com/'
assert schema['simple_link'].description == 'example link'
assert schema['location']['query'].fields[0].schema.description == 'example field'
data = client.action(schema, ['simple_link'])
expected = {
'method': 'GET',
'query_params': {}
}
assert data == expected
def test_query_params(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['location', 'query'], params={'example': 123})
expected = {
'method': 'GET',
'query_params': {'example': '123'}
}
assert data == expected
def test_session_headers(self):
client = CoreAPIClient()
client.session.headers.update({'X-Custom-Header': 'foo'})
schema = client.get('http://api.example.com/')
data = client.action(schema, ['headers'])
assert data['headers']['X-CUSTOM-HEADER'] == 'foo'
def test_query_params_with_multiple_values(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['location', 'query'], params={'example': [1, 2, 3]})
expected = {
'method': 'GET',
'query_params': {'example': ['1', '2', '3']}
}
assert data == expected
def test_form_params(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['location', 'form'], params={'example': 123})
expected = {
'method': 'POST',
'content_type': 'application/json',
'query_params': {},
'data': {'example': 123},
'files': {}
}
assert data == expected
def test_body_params(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['location', 'body'], params={'example': 123})
expected = {
'method': 'POST',
'content_type': 'application/json',
'query_params': {},
'data': 123,
'files': {}
}
assert data == expected
def test_path_params(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['location', 'path'], params={'id': 123})
expected = {
'method': 'GET',
'query_params': {},
'id': '123'
}
assert data == expected
def test_multipart_encoding(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
with tempfile.NamedTemporaryFile() as temp:
temp.write(b'example file content')
temp.flush()
temp.seek(0)
name = os.path.basename(temp.name)
data = client.action(schema, ['encoding', 'multipart'], params={'example': temp})
expected = {
'method': 'POST',
'content_type': 'multipart/form-data',
'query_params': {},
'data': {},
'files': {'example': {'name': name, 'content': 'example file content'}}
}
assert data == expected
def test_multipart_encoding_no_file(self):
# When no file is included, multipart encoding should still be used.
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['encoding', 'multipart'], params={'example': 123})
expected = {
'method': 'POST',
'content_type': 'multipart/form-data',
'query_params': {},
'data': {'example': '123'},
'files': {}
}
assert data == expected
def test_multipart_encoding_multiple_values(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['encoding', 'multipart'], params={'example': [1, 2, 3]})
expected = {
'method': 'POST',
'content_type': 'multipart/form-data',
'query_params': {},
'data': {'example': ['1', '2', '3']},
'files': {}
}
assert data == expected
def test_multipart_encoding_string_file_content(self):
# Test for `coreapi.utils.File` support.
from coreapi.utils import File
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
example = File(name='example.txt', content='123')
data = client.action(schema, ['encoding', 'multipart'], params={'example': example})
expected = {
'method': 'POST',
'content_type': 'multipart/form-data',
'query_params': {},
'data': {},
'files': {'example': {'name': 'example.txt', 'content': '123'}}
}
assert data == expected
def test_multipart_encoding_in_body(self):
from coreapi.utils import File
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
example = {'foo': File(name='example.txt', content='123'), 'bar': 'abc'}
data = client.action(schema, ['encoding', 'multipart-body'], params={'example': example})
expected = {
'method': 'POST',
'content_type': 'multipart/form-data',
'query_params': {},
'data': {'bar': 'abc'},
'files': {'foo': {'name': 'example.txt', 'content': '123'}}
}
assert data == expected
# URLencoded
def test_urlencoded_encoding(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['encoding', 'urlencoded'], params={'example': 123})
expected = {
'method': 'POST',
'content_type': 'application/x-www-form-urlencoded',
'query_params': {},
'data': {'example': '123'},
'files': {}
}
assert data == expected
def test_urlencoded_encoding_multiple_values(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['encoding', 'urlencoded'], params={'example': [1, 2, 3]})
expected = {
'method': 'POST',
'content_type': 'application/x-www-form-urlencoded',
'query_params': {},
'data': {'example': ['1', '2', '3']},
'files': {}
}
assert data == expected
def test_urlencoded_encoding_in_body(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['encoding', 'urlencoded-body'], params={'example': {'foo': 123, 'bar': True}})
expected = {
'method': 'POST',
'content_type': 'application/x-www-form-urlencoded',
'query_params': {},
'data': {'foo': '123', 'bar': 'true'},
'files': {}
}
assert data == expected
# Raw uploads
def test_raw_upload(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
with tempfile.NamedTemporaryFile(delete=False) as temp:
temp.write(b'example file content')
temp.flush()
temp.seek(0)
name = os.path.basename(temp.name)
data = client.action(schema, ['encoding', 'raw_upload'], params={'example': temp})
expected = {
'method': 'POST',
'files': {'file': {'name': name, 'content': 'example file content'}},
'content_type': 'application/octet-stream'
}
assert data == expected
def test_raw_upload_string_file_content(self):
from coreapi.utils import File
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
example = File('example.txt', '123')
data = client.action(schema, ['encoding', 'raw_upload'], params={'example': example})
expected = {
'method': 'POST',
'files': {'file': {'name': 'example.txt', 'content': '123'}},
'content_type': 'text/plain'
}
assert data == expected
def test_raw_upload_explicit_content_type(self):
from coreapi.utils import File
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
example = File('example.txt', '123', 'text/html')
data = client.action(schema, ['encoding', 'raw_upload'], params={'example': example})
expected = {
'method': 'POST',
'files': {'file': {'name': 'example.txt', 'content': '123'}},
'content_type': 'text/html'
}
assert data == expected
# Responses
def test_text_response(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['response', 'text'])
expected = '123'
assert data == expected
def test_download_response(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
data = client.action(schema, ['response', 'download'])
assert data.basename == 'download.png'
assert data.read() == b'some file content'
|