Python TestCase 中无法使用 self.client.get() 找到媒体文件

Sas*_*nko 5 python django django-testing

media我的项目根目录下的文件夹中有一个图像。我可以./manage.py runserver通过浏览器中的 url 成功访问我的文件127.0.0.1:8000/media/img.jpg。但以下测试失败并显示404!=200. 为什么?

class MyTestCase(TestCase):
    def test_image_shows(self):
         response = self.client.get('/media/img.jpg')
         self.assertEquals(response.status_code, 200)
Run Code Online (Sandbox Code Playgroud)

设置.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Run Code Online (Sandbox Code Playgroud)

Joc*_*nde 3

这既不简单也不优雅,但这是我为自己找到的最好的简单方法:

1)在urls.py中添加静态规则(在生产中未启用):

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Run Code Online (Sandbox Code Playgroud)

2)DEBUG为您的测试用例启用(以便启用静态规则):

from django.test import TestCase
from django.test.utils import override_settings

@override_settings(DEBUG=True)
class SomeTestCase(TestCase):
    def test_something(self):
        assert self.client.get('/medias/something.jpg').status_code == 200
Run Code Online (Sandbox Code Playgroud)

如果您在测试期间写入媒体,您可能还需要为MEDIA_ROOT测试指定不同的值,以免污染您的开发人员。可以在 caktus 博客上MEDIA_ROOT找到一个示例。