我正在创建一个django项目,它将接受用户内容,在开发过程中,我试图创建一个测试用例来测试模型是否正常上传。
我有一个这样的文件结构:
Site
|----temp
| |----django-test
|----app
|----test_image.jpg
|----test_manual.pdf
|----tests.py我的测试用例代码如下:
from django.test import TestCase, override_settings
from django.core.files import File
import sys
import os
from .models import Manual
# Create your tests here.
class ManualModelTests(TestCase):
@override_settings(MEDIA_ROOT='/tmp/django_test')
def test_normal_manual_upload(self):
in_image = open(os.path.join('manuals','test_image.jpg'), 'r+b')
in_pdf = open(os.path.join('manuals','test_manual.pdf'), 'r+b')
thumbnail = File(in_image)
in_manual = File(in_pdf)
new_manual = Manual.objects.create(
photo=thumbnail,
manual=in_manual,
make='yoshimura',
model='001',
year_min=2007,
year_max=2010
)
#uploaded_image = open(os.path.join('temp','django_test','images','test_image.jpg'), 'r+b')
#uploaded_pdf = open(os.path.join('temp','django_test','manuals','test_manual.pdf'), 'r+b') #self.assertIs(open(), in_image)
#self.assertIs(uploaded_img, in_image)
#self.assertIs(uploaded_pdf, in_pdf)以下是模型代码:
class Manual(models.Model):
photo = models.ImageField(upload_to="photos")
make = models.CharField(max_length=50)
model = models.CharField(max_length=100)
manual = models.FileField(upload_to="manuals")
year_min = models.PositiveIntegerField(default=0)
year_max = models.PositiveIntegerField(default=0)由于某种原因,我在打开‘test_image.jpg’时得到了一个test_image.jpg)。我的问题是
发布于 2019-02-19 17:56:35
您将获得一个FileNotFoundError,因为open将尝试定位相对于当前工作目录(可能是Site )的文件。
使用__file__使用相对于测试模块本身的路径打开文件可能更好,因为这不依赖于当前的工作目录。例如:
open(os.path.join(os.path.dirname(__file__), 'test_image.jpg'), 'r+b')对于断言,只要测试上传的文件是否存在,就可能是最简单的。如果它们存在,那么上传一定是有效的。例如:
self.assertTrue(os.path.exists('/tmp/django_test/test_image.jpg'))您还应该在测试中添加一个tearDown()方法,以便在测试完成后删除上传的文件。
def tearDown(self):
try:
os.remove('/tmp/django_test/test_image.jpg')
except FileNotFoundError:
passhttps://stackoverflow.com/questions/54771209
复制相似问题