Vous pouvez tester le téléchargement même si vous placez le fichier image localement, mais pour le compléter dans le code de test.
(python2.7, django1.6)
$ django-admin.py startproject core
$ mv core photo_book
$ cd photo_book
$ python manage.py startapp photos
$ mkdir -p static/upload #Répertoire pour enregistrer les images
core/
settings.py
#Seulement des pièces supplémentaires
IINSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'photos', #ajouter à
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/') #ajouter à
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from photos.views import ImageCreateView
urlpatterns = patterns(
'',
url(r'^images/$', ImageCreateView.as_view(), name='images'),
url(r'^admin/', include(admin.site.urls)),
)
photos/
models.py
from django.db import models
class Photo(models.Model):
image = models.ImageField(upload_to='upload')
forms.py
from django import forms
class PhotoForm(forms.Form):
image = forms.ImageField()
views.py
from django.views.generic.edit import CreateView
from photos.models import Photo
class ImageCreateView(CreateView):
model = Photo
success_url = '/'
test.py
from StringIO import StringIO
from django.core.urlresolvers import reverse
from django.test import TestCase
from photos.models import Photo
class CreateImageTest(TestCase):
def test_post(self):
url = reverse("images")
dummy_image = StringIO(
'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;'
)
dummy_image.name = 'dummy_image.gif'
dummy_image.content_type = 'image/gif'
response = self.client.post(url, {'image': dummy_image})
self.assertEqual(response.status_code, 302)
#Vérifiez s'il a été enregistré dans la base de données
self.assertEqual(Photo.objects.count(), 1)
#Vérifiez si l'image enregistrée et l'image factice téléchargée sont identiques
uploaded_image = StringIO(open(Photo.objects.last().image._get_path(), 'rb').read())
self.assertEqual(uploaded_image.getvalue(), dummy_image.getvalue())
$ python manage.py test
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.042s
OK
Destroying test database for alias 'default'...
Recommended Posts