'Testing Django FileResponse

I have a Django view that returns a file. The FileResponse is built for that purpose. However, I do not understand how to test this.

Right now I use the HttpResponse and test it like this:

response = client.get(url)
io = io = BytesIO(response.content)

The io object can now be used for further testing.

However, if I try the following with FileResponse (which is derived from StreamingHttpResponse and thus has streaming_content instead of content), I get the following exception:

TypeError: a bytes-like object is required, not 'map'

If I cast the map object to bytes like this:

response = client.get(url)
io = io = BytesIO(bytes(response.streaming_content))

I get another exception: TypeError: 'bytes' object cannot be interpreted as an integer

How can I get an BytesIO object from FileResponse.streaming_content?



Solution 1:[1]

streaming_content is iterable, not bytestring, so you will have to join them.

fileres = bytes("test", 'utf-8')
stream = b''.join(response.streaming_content)
assert stream == fileres

Solution 2:[2]

response.getvalue() is responsible to convert from map to bytes:

bytes_io = BytesIO(response.getvalue())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rasca0027
Solution 2 Thiago Falcao