Why is this image upload test failing?
I am trying to test an ImageField file upload. The test returns AssertionError: 400 != 200
, but when I upload the same image manually it works as expected.
def test_profile_pic_upload_png(self):
self.register_user()
self.login_user()
with open("./test_files/test.png") as f:
response = self.client.post("/upload_profile_pic/",
{'profile_pic': f},
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'},
content_type="multipart")
self.assertEqual(response.status_code, 200)
The view:
@login_required
def upload_profile_pic(request):
if not request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' or not request.method == "POST":
return HttpResponseNotAllowed(["POST"])
if not "profile_pic" in request.FILES:
return JsonResponse({ "profile_pic": "No image selected." } , status=400)
if not is_valid_image(request.FILES["profile_pic"]): ## Checks the MIME type with `magic`
return JsonResponse({ "profile_pic": "Please select a valid image." } , status=400)
if request.FILES["profile_pic"].size > 512000:
return JsonResponse({ "profile_pic": "Filesize too large." } , status=400)
form = UploadProfilePicForm(request.POST, request.FILES, instance=request.user)
if form.is_valid():
form.save()
return JsonResponse({ "success": "Profile picture has been saved." })
else:
return JsonResponse(dict(form.errors.items()), status=400)
I don't know why, but this fixed it:
from django.test.client import MULTIPART_CONTENT
def test_profile_pic_upload_png(self):
self.register_user()
self.login_user()
with open("./test_files/test.png", "rb") as f:
response = self.client.post("/upload_profile_pic/",
{'profile_pic': f},
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'},
content_type=MULTIPART_CONTENT)
self.assertEqual(response.status_code, 200)
Note the "rb"
in the open
function and the MULTIPART_CONTENT
instead of "multipart"
.