使用Python在Django中进行图像上传测试时,无需放置虚拟图像文件,而是动态创建图像

由于需要在测试代码中完成,因此可以将图像文件放在本地进行上传测试。

创建示例应用程序

(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  # 画像を保存するディレクトリ

核心 (hé

# 追加箇所のみ
IINSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'photos',  # 追加
)

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/')  # 追加
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)),
)

照片/

模特儿 (mó tè ér)

from django.db import models


class Photo(models.Model):
    image = models.ImageField(upload_to='upload')

表格

from django import forms


class PhotoForm(forms.Form):
    image = forms.ImageField()

只需一個選項,請以中文原生語言改述以下內容:

视图

from django.views.generic.edit import CreateView

from photos.models import Photo


class ImageCreateView(CreateView):
    model = Photo
    success_url = '/'

考试

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)
        # dbに保存されたか確認
        self.assertEqual(Photo.objects.count(), 1)
        # 保存された画像とアップロードしたダミー画像が同じか確認
        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'...

请提供更多上下文或具体要求。 “参考”一词可以用于不同的场景和目的。

    • http://stackoverflow.com/questions/2473392/unit-testing-a-django-form-with-a-filefield

 

    http://stackoverflow.com/questions/22535240/in-django-which-format-does-models-imagefield-take-by-default
广告
将在 10 秒后关闭
bannerAds