我有一个用户配置文件应用程序,该应用程序允许用户上传化身。我正在尝试测试图像上传,但遇到了错误。这是我的相关文件:
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=100, blank=True)
last_name = models.CharField(max_length=100, blank=True)
avatar = models.ImageField(upload_to="media/", blank=True, null=True)
views.py
def userprofile(request):
# some code omitted for brevity
if form.is_valid():
form.save()
return HttpResponseRedirect(userprofile.get_absolute_url())
tests.py
class UserProfileTest(TestCase):
def setUp(self):
self.client = Client()
self.user = User.objects.create_user(
username='testuser',
email='test@test.test',
password='testpassword',
)
self.user.userprofile.first_name = 'John'
self.user.userprofile.last_name = 'Doe'
def test_image_upload(self):
self.client.login(username='testuser', password='testpassword')
with open('media/tests/up.png', 'rb') as image:
self.client.post('/profile/', {'avatar': image})
print(self.user.userprofile.avatar.url)
错误:
File "userprofile/tests.py", line 110, in test_image_upload
print(self.user.userprofile.avatar.url)
ValueError: The 'avatar' attribute has no file associated with it.
在测试中,我已经打印了response.content
,并且可以在模板中看到阿凡达的URL。'media/tests/up.png'
文件已在服务器上,并已成功上传。我的目标是在测试结束时删除文件,因为它每次运行测试时都会上传。我打算通过获取文件路径来删除文件(Django有重复的情况时,将随机的alpha-numeric字符附加到文件名的末尾),但是我现在无法获得其文件路径。
您需要一个Django文件对象进行测试。您可以制作一个python文件,然后拥有一个django imagefile:
from django.core.files.images import ImageFile
with open('media/tests/up.png', 'rb') as image:
test_file = ImageFile(image)
然后使用test_file进行测试。