| 20 | |
| 21 | |
| 22 | class APIRequestFactory(DjangoRequestFactory): |
| 23 | renderer_classes_list = api_settings.TEST_REQUEST_RENDERER_CLASSES |
| 24 | default_format = api_settings.TEST_REQUEST_DEFAULT_FORMAT |
| 25 | |
| 26 | def __init__(self, enforce_csrf_checks=False, **defaults): |
| 27 | self.enforce_csrf_checks = enforce_csrf_checks |
| 28 | self.renderer_classes = {} |
| 29 | for cls in self.renderer_classes_list: |
| 30 | self.renderer_classes[cls.format] = cls |
| 31 | super(APIRequestFactory, self).__init__(**defaults) |
| 32 | |
| 33 | def _encode_data(self, data, format=None, content_type=None): |
| 34 | """ |
| 35 | Encode the data returning a two tuple of (bytes, content_type) |
| 36 | """ |
| 37 | |
| 38 | if not data: |
| 39 | return ('', None) |
| 40 | |
| 41 | assert format is None or content_type is None, ( |
| 42 | 'You may not set both `format` and `content_type`.' |
| 43 | ) |
| 44 | |
| 45 | if content_type: |
| 46 | # Content type specified explicitly, treat data as a raw bytestring |
| 47 | ret = force_bytes_or_smart_bytes(data, settings.DEFAULT_CHARSET) |
| 48 | |
| 49 | else: |
| 50 | format = format or self.default_format |
| 51 | |
| 52 | assert format in self.renderer_classes, ("Invalid format '{0}'. " |
| 53 | "Available formats are {1}. Set TEST_REQUEST_RENDERER_CLASSES " |
| 54 | "to enable extra request formats.".format( |
| 55 | format, |
| 56 | ', '.join(["'" + fmt + "'" for fmt in self.renderer_classes.keys()]) |
| 57 | ) |
| 58 | ) |
| 59 | |
| 60 | # Use format and render the data into a bytestring |
| 61 | renderer = self.renderer_classes[format]() |
| 62 | ret = renderer.render(data) |
| 63 | |
| 64 | # Determine the content-type header from the renderer |
| 65 | content_type = "{0}; charset={1}".format( |
| 66 | renderer.media_type, renderer.charset |
| 67 | ) |
| 68 | |
| 69 | # Coerce text to bytes if required. |
| 70 | if isinstance(ret, six.text_type): |
| 71 | ret = bytes(ret.encode(renderer.charset)) |
| 72 | |
| 73 | return ret, content_type |
| 74 | |
| 75 | def get(self, path, data=None, **extra): |
| 76 | r = { |
| 77 | 'QUERY_STRING': urlencode(data or {}, doseq=True), |
| 78 | } |
| 79 | r.update(extra) |
no outgoing calls