Django : testing static files

标签 django testing

使用 Django 1.3 的测试框架 (TestCase),我想在静态文件上运行一些测试(即,文件不一定由 django 本身在产品上提供,但可以用于调试 (runserver))。 但是如果我跑

self.client.get("/static/somefile.json")

... 我在测试中遇到 404 错误。 (当然runserver上有这个文件)

为什么不呢,但是检查我的静态文件中是否存在此 json 模式的最佳方法是什么? (在我的例子中,我还想针对生成的 json 输出测试这个公共(public) json 模式,所以我想要文件的内容)

最佳答案

我发现另一种方法稍微简单一些,因为需要输入/导入的内容更少:

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+ 开始,您还可以通过 finders 模块找出/测试 Django 正在查找的位置:

searched_locations = finders.searched_locations

除了 Django 提供的 SimpleTestCase.assertTemplateUsed(response, template_name, msg_prefix='') 断言之外,您还可以使用: response.templates 来自 Response 类,以获取用于呈现响应的模板列表。

来源:https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.Response.templates

关于 Django : testing static files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7123161/

相关文章:

python - django 中的复杂 ORM 查询

javascript - 如何在 for 循环内使用 .each() 和列表?

testing - 使用 UFT 在移动应用程序上进行多次登录测试

scala - 游戏中的模拟对象[2.0]

testing - 使用 Jest 进行测试时模拟 native 模块

python - Django Save 创建两条记录而不是一条

python - Django-rest-framework教程中的AttributeError 4 : authentication

Django Celery 无法连接到 EC2 上的远程 RabbitMQ

url - grails测试网址参数

unit-testing - 设计一个健壮的单元测试——以几种不同的方式测试相同的逻辑?