Python FileNotFound Django测试媒体

问题描述 投票:0回答:1

我正在创建一个将接受用户内容的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'时出现FileNotFound)。我的问题是

  1. 为什么会出现此错误,以及如何纠正该错误?
  2. 我使用self.assert的评论部分看起来正确吗?
python django assertion file-not-found
1个回答
1
投票

您得到一个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: 
        pass
© www.soinside.com 2019 - 2024. All rights reserved.