Sie können den Upload auch dann testen, wenn Sie die Bilddatei lokal ablegen, um sie jedoch im Testcode zu vervollständigen.
(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 #Verzeichnis zum Speichern von Bildern
core/
settings.py
#Nur zusätzliche Teile
IINSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'photos', #hinzufügen
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/') #hinzufügen
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)
#Überprüfen Sie, ob es in db gespeichert wurde
self.assertEqual(Photo.objects.count(), 1)
#Überprüfen Sie, ob das gespeicherte Bild und das hochgeladene Dummy-Bild identisch sind
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'...