Django:测试静态文件

sma*_*mad 18 testing django

使用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

  • 这会在我的上传内容测试中引发 SuspiciousFileOperation (3认同)

oji*_*jii 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)
Run Code Online (Sandbox Code Playgroud)

这使用staticfiles finders查找名为'somefile.json'的文件,然后检查文件是否确实存在于您配置的存储上?


Ris*_*nha 5

您可以通过testing.StaticLiveServerTestCasestaticfiles模块使用类:http ://django.readthedocs.org/en/latest/ref/contrib/staticfiles.html#specialized-test-case-to-support-live-testing