Here is code snippet example for uploading binary file through DRF (Django Rest Framework) using APITestCase once you creating integration testing.
class MyTestCase(APITestCase): def setUp(self): # Your initial data goes here. def test_upload_attachment(self): my_file = ... # You can get file path with `os.path` with open(my_file, 'rb') as binary: response = self.client.post(path='your_endpoint', data=binary, format='multipart') self.assertEqual(response.status_code, status.HTTP_201_CREATED)
Update, 14 September 2016:
I’m no longer to use my method above to test binary file on my testing, because with that method you have to push the dummy files to your repo that supposed to be only source code on the repo. If you are not push the dummy files your testing will fail if you run the on other machine, because the files does not exists.
Now I’m using base64 encoding to encode my binary files and parse it on my testing. First of all, what you need to do is encode your binary files to base64. There are a lot of online tools for it, for instance i’ll using this http://www.webutils.pl/Base64 , then see the example below:
from base64 import b64decode from django.core.files.base import ContentFile image_example = '/9j/4AAQSkZJRgABAQEBLAEsAAD/2Q==' # encoded file example. image_data = b64decode(image_example) image_name = 'testing.jpg' image = ContentFile(image_data, image_name)