使用Django 1.3的测试框架(TestCase),我想对静态文件运行一些测试(即,文件不一定由django本身在prod上提供,但可以用于调试(runserver)).但是,如果我跑
self.client.get("/static/somefile.json")
Run Code Online (Sandbox Code Playgroud)
...我的测试中出现404错误.(当然,这个文件在runserver上可用)
为什么不,但在我的静态文件中检查这个json模式的存在最好的方法是什么?(在我的情况下,我还想针对生成的json输出测试这个公共json模式,所以我想要文件的内容)
Bro*_*bay 10
我发现的另一种方法稍微容易,因为输入/导入的次数较少:
from django.contrib.staticfiles import finders
result = finders.find('css/base.css')
Run Code Online (Sandbox Code Playgroud)
如果找到静态文件,它将返回文件的完整路径.如果没有找到,它将返回None
资料来源:https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#finders-module
从Django 1.7+开始,您还可以找到/测试Django通过finders模块查看的位置:
searched_locations = finders.searched_locations
Run Code Online (Sandbox Code Playgroud)
除了SimpleTestCase.assertTemplateUsed(response, template_name, msg_prefix='')Django提供的断言之外,您还可以使用:
response.templates从Response类获取用于呈现响应的模板列表.
资料来源:https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.Response.templates
这个怎么样:
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)
Run Code Online (Sandbox Code Playgroud)
这使用staticfiles finders查找名为'somefile.json'的文件,然后检查文件是否确实存在于您配置的存储上?
| 归档时间: |
|
| 查看次数: |
5795 次 |
| 最近记录: |