Django:更改测试的媒体根
我正在尝试为 Django 应用程序编写一些测试,涉及文件上传。为此,我想将 MEDIA_ROOT
暂时更改为“myproject/fixtures/test_media/”。由于某种原因,这似乎阻止了 Django 找到固定装置。
我的测试用例看起来像
from django.conf import settings
class TestMedia(TestCase):
fixtures = ['fixtures/test_data.json']
def setUp(self):
settings.MEDIA_ROOT = ''.join(
[settings.PROJECT_PATH, '/fixtures/test_media/'])
def test_photo_size(self):
pass # Actually do something with the media files
出于某种原因,Django 无法加载固定装置,因此所有测试都会失败
安装固定装置“fixtures/test_data.json”时出现问题:回溯(最近一次调用最后一次) ...
我做错了什么?
I am trying to write some tests for a Django application, involving file upload. For that, I want to change the MEDIA_ROOT
temporarily to 'myproject/fixtures/test_media/'. For some reason it seems that this prevents Django to find the fixtures.
My test case looks like
from django.conf import settings
class TestMedia(TestCase):
fixtures = ['fixtures/test_data.json']
def setUp(self):
settings.MEDIA_ROOT = ''.join(
[settings.PROJECT_PATH, '/fixtures/test_media/'])
def test_photo_size(self):
pass # Actually do something with the media files
For some reason, Django cannot then load the fixtures, hence all tests fail with
Problem installing fixture 'fixtures/test_data.json': Traceback (most recent call last)
...
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过删除设置并查看是否可以加载灯具?
此外,我认为您确实不需要更改 MEDIA_ROOT 来测试上传。您只需在tearDown 中删除那些上传的文件即可恢复所有内容。
编辑:
看来您正在生产环境中运行单元测试。老实说,这不是一个好主意。
但如果你必须这样做,使用另一个设置文件怎么样?像这样:
并使用附加参数运行测试:
Have u tried to remove the setUp and see if the fixtures can be loaded?
Besides, I don't think you really need to change MEDIA_ROOT to test upload. You can just remove those uploaded files in tearDown to revert everything.
Edit:
It seems that you're running your unit test in production environment. Honestly, that's not a good idea.
But if u do have to do that, how about use another setting file? Like this:
And run you test with an additional parameter:
不在setUp中重写,它仅在运行TestCase子类的每个测试方法之前执行,在所有测试之前在模块中重写它。
Not override in setUp, it is execute only before of run each test method of TestCase subclass, override it in module before all tests.
您可以覆盖测试的所有设置。这是一种更“Django”的方式 - 文档不鼓励直接更改
设置
。 Django 文档中有一个关于它。关于覆盖设置的更多信息。您可以对整个测试使用装饰器:
或者您可以只覆盖部分代码的设置:
请注意内联版本的不同语法。示例取自文档。
You can override all the settings for tests. Its a more "Django" way of - the docs discourage directly altering
settings
. There is a section in the Django docs about it.A little bit more about overriding settings. You can use a decorator for a whole test:
or you can just override the setting for a portion of code:
Note the different syntax for the inline version. Examples are taken from the docs.