Это функция, которую я использую для создания тестового изображения:
Код: Выделить всё
from PIL import Image
from django.core.files.uploadedfile import SimpleUploadedFile
def test_image(name='test.jpg', size=(250,250)):
img = Image.new('RGB', size)
content = img.tobytes()
# return Django file for testing in forms and serializers
return SimpleUploadedFile(name, content=content, content_type='image/jpeg')
Код: Выделить всё
class PhotoCreateView(LoginRequiredMixin, CreateView):
model = Photo
form_class = PhotoForm
success_url = '/'
template_name = 'photos/create.html'
def form_valid(self, form):
new_category = form.cleaned_data['new_category']
if new_category:
category = Category.objects.create(name=new_category)
form.instance.category = category
return super().form_valid(form)
Код: Выделить всё
class TestPhotoCreateView:
url = reverse('photos:create')
def test_photo_create_view_authenticated_user_can_access(self, client, user):
client.force_login(user)
response = client.get(self.url)
assert response.status_code == 200
def test_photo_create_view_unauthenticated_user_cannot_access(self, client):
response = client.get(self.url)
assert response.status_code == 302
def test_photo_create_view_form_valid_existing_category(self, client, user):
client.force_login(user)
for _ in range(3):
CategoryFactory()
category = CategoryFactory()
image = test_image()
form_data = {
'category': category.pk,
'new_category': '',
'description': 'hello world',
'image': image,
}
response = client.post(self.url, form_data)
print(response.content)
photo = Photo.objects.get(description=form_data['description'])
assert photo.category == form_data['category']
Я запустил pytest --capture=tee-sys, и эта ошибка была в поле изображения :
Код: Выделить всё
[b]Upload a valid image. The file you uploaded was either not an image or a corrupted image.[/b]
Весь код для этого проекта находится здесь: https:/ /github.com/leigh-data/photo_gallery
Подробнее здесь: https://stackoverflow.com/questions/691 ... -unit-test