I start developing a web API with Django rest framework lately. So It was a little bit challenging for me to write the test for ImageField because I am not so familiar with Django environment.
So I just publish how I got over the problem. Maybe it helps someone out there.
In my case, It was a simple category app with photo field. All we need to do is populate the field with an image file but the trick is that the request format must be ‘multipart‘.
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 |
import os from django.conf import settings from rest_framework.test import APITestCase, APIClient from user.factories import UserFactory class CategoryTests(APITestCase): def setUp(self): self.user = UserFactory() self.client = APIClient() self.client.login(username=self.user.username, password='test_pass') def test_can_create_category(self): """ Test if we can create a category """ with open(os.path.join(settings.MEDIA_ROOT, 'uploads/category/example.jpg'), 'rb') as photo: data = { 'parent_category': '', 'title': 'Category 1', 'description': 'Test Description for category 1', 'photo': photo } response = self.client.post(self.path, data, format='multipart') self.assertEqual(response.status_code, status.HTTP_201_CREATED) |