使用Django 1.3的测试框架(TestCase),我想对静态文件运行一些测试(即,文件不一定由django本身在prod上提供,但可以用于调试(runserver))。 但如果我跑
self.client.get("/static/somefile.json")
...我的测试中出现404错误。 (当然,这个文件在runserver上可用)
为什么不,但是在我的静态文件中检查这个json模式的存在最好的方法是什么? (在我的情况下,我还想针对生成的json输出测试这个公共json模式,所以我想要文件的内容)
答案 0 :(得分:8)
怎么样:
from django.contrib.staticfiles import finders
from django.contrib.staticfiles.storage import staticfiles_storage
absolute_path = finders.find('somefile.json')
assert staticfiles_storage.exists(absolute_path)
这使用staticfiles finders查找名为'somefile.json'的文件,然后检查文件是否确实存在于您配置的存储上?
答案 1 :(得分:8)
我发现的另一种方法稍微容易,因为输入/导入的次数较少:
from django.contrib.staticfiles import finders
result = finders.find('css/base.css')
如果找到静态文件,它将返回文件的完整路径。如果未找到,则会返回None
来源:https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#finders-module
从Django 1.7+开始,您还可以找到/测试Django通过finders模块查看的位置:
searched_locations = finders.searched_locations
除了Django提供的SimpleTestCase.assertTemplateUsed(response, template_name, msg_prefix='')
断言之外,您还可以使用:
来自Response类的response.templates
以获取用于呈现响应的模板列表。
来源:https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.Response.templates
答案 2 :(得分:5)
您可以使用staticfiles模块中的类testing.StaticLiveServerTestCase
:
http://django.readthedocs.org/en/latest/ref/contrib/staticfiles.html#specialized-test-case-to-support-live-testing
答案 3 :(得分:2)
这仅用于在开发期间提供静态文件: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#static-file-development-view
答案 4 :(得分:2)
作为isbadawi评论,测试服务器始终以DEBUG = False
运行。因此,您不能依赖DEBUG处理静态文件,您需要一种类似于生产的显式方式来处理它们以便测试找到它们。您可以在urls.py
中设置一个特殊部分,以便在您运行serve()
时启用开发test
:
if 'test' in sys.argv:
static_url = re.escape(settings.STATIC_URL.lstrip('/'))
urlpatterns += patterns('',
url(r'^%s(?P<path>.*)$' % static_url, 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
答案 5 :(得分:0)
FWIW,对于重要的项目,我认为测试静态文件可能超出了纯 Django 测试的范围,因为 Django 的 runserver 不打算用于提供静态文件。这种测试通常用于集成测试,这些测试涉及测试部署而不是开发代码。