测试图片上传总是失败
Test Image Upload Always Fails
我的任何图片上传单元测试都无法正常工作。以下测试失败并显示 AssertionError: <ImageFieldFile: profile_pics/default.jpg> != 'test_image.jpg'
(忽略我的测试无论如何都会失败的事实,因为它将 ImageFieldFile 与我的字符串进行比较,更重要的是图像不会更新。我稍后会修复断言)。
def test_upload_image_works(self):
user = User.objects.create(username='testuser', email='user@example.com')
self.client.force_login(user)
with open(settings.MEDIA_ROOT+'\profile_pics\default_test.jpg', 'rb') as infile:
self.client.post(
reverse('update_profile', args=('testuser',)),
content_type='multipart/form-data',
#data = {'image': infile},
data={'image': infile.read()},
follow=True
)
user.refresh_from_db()
self.assertEqual(user.profile.image, 'default_test.jpg')
但是这个类似的测试通过了
def test_info_update_works(self):
user = User.objects.create(username='username', email='user@example.com')
self.client.force_login(user)
self.client.post(reverse('update_profile', args=('username',)), {
'email': 'updated@example.com'
})
user.refresh_from_db()
self.assertEqual(user.email, 'updated@example.com')
编辑:
@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def update_profile(request, username):
# refuse access if logged in user does not match username
if not request.user == User.objects.get(username=username):
response = HttpResponse()
response.status_code = 403
return response
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated')
return redirect('update_profile', username=User.objects.get(username=username))
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form' : u_form,
'p_form' : p_form
}
return render(request, 'users/update_profile.html', context)
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics')
谢谢。
user.profile.image
' 类型是 ImageFieldFile 而不是 str。所以你不能比较它们。
正确的方法应该是:
self.assertEqual(user.profile.image.name, 'profile_pics/default_test.jpg')
这就是我编写测试的方式,这样您就不必在测试失败时进行调试:
import os
def test_upload_image_works(self):
user = User.objects.create(username='testuser', email='user@example.com')
self.client.force_login(user)
self.assertTrue(user.is_authenticated)
# This should be whatever you have implemented to check if a user
# has a role.
self.assertTrue(user.wears_hat('registered_user'))
# Avoid uploading the file to itself and use an image in a subdirectory of the
# test. This also allows it to be in the repository so CI pipelines and
# colleagues do not need special steps.
test_dir = os.path.join(os.path.dirname(__file__), 'data')
test_img_path = os.path.join(test_dir, 'default_test.jpg')
expected_path = os.path.join(settings.MEDIA_ROOT, 'profile_pics', 'default_test.jpg')
self.assertTrue(os.path.exists(test_img_path))
with open(test_img_path, 'rb') as infile:
r = self.client.post(
reverse('update_profile', args=('testuser',)),
content_type='multipart/form-data',
data = {'image': infile},
follow=True
)
self.assertTrue(r.ok)
user.refresh_from_db()
self.assertEqual(user.profile.image.path, expected_path)
我的任何图片上传单元测试都无法正常工作。以下测试失败并显示 AssertionError: <ImageFieldFile: profile_pics/default.jpg> != 'test_image.jpg'
(忽略我的测试无论如何都会失败的事实,因为它将 ImageFieldFile 与我的字符串进行比较,更重要的是图像不会更新。我稍后会修复断言)。
def test_upload_image_works(self):
user = User.objects.create(username='testuser', email='user@example.com')
self.client.force_login(user)
with open(settings.MEDIA_ROOT+'\profile_pics\default_test.jpg', 'rb') as infile:
self.client.post(
reverse('update_profile', args=('testuser',)),
content_type='multipart/form-data',
#data = {'image': infile},
data={'image': infile.read()},
follow=True
)
user.refresh_from_db()
self.assertEqual(user.profile.image, 'default_test.jpg')
但是这个类似的测试通过了
def test_info_update_works(self):
user = User.objects.create(username='username', email='user@example.com')
self.client.force_login(user)
self.client.post(reverse('update_profile', args=('username',)), {
'email': 'updated@example.com'
})
user.refresh_from_db()
self.assertEqual(user.email, 'updated@example.com')
编辑:
@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def update_profile(request, username):
# refuse access if logged in user does not match username
if not request.user == User.objects.get(username=username):
response = HttpResponse()
response.status_code = 403
return response
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated')
return redirect('update_profile', username=User.objects.get(username=username))
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form' : u_form,
'p_form' : p_form
}
return render(request, 'users/update_profile.html', context)
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics')
谢谢。
user.profile.image
' 类型是 ImageFieldFile 而不是 str。所以你不能比较它们。
正确的方法应该是:
self.assertEqual(user.profile.image.name, 'profile_pics/default_test.jpg')
这就是我编写测试的方式,这样您就不必在测试失败时进行调试:
import os
def test_upload_image_works(self):
user = User.objects.create(username='testuser', email='user@example.com')
self.client.force_login(user)
self.assertTrue(user.is_authenticated)
# This should be whatever you have implemented to check if a user
# has a role.
self.assertTrue(user.wears_hat('registered_user'))
# Avoid uploading the file to itself and use an image in a subdirectory of the
# test. This also allows it to be in the repository so CI pipelines and
# colleagues do not need special steps.
test_dir = os.path.join(os.path.dirname(__file__), 'data')
test_img_path = os.path.join(test_dir, 'default_test.jpg')
expected_path = os.path.join(settings.MEDIA_ROOT, 'profile_pics', 'default_test.jpg')
self.assertTrue(os.path.exists(test_img_path))
with open(test_img_path, 'rb') as infile:
r = self.client.post(
reverse('update_profile', args=('testuser',)),
content_type='multipart/form-data',
data = {'image': infile},
follow=True
)
self.assertTrue(r.ok)
user.refresh_from_db()
self.assertEqual(user.profile.image.path, expected_path)