Django测试加载css文件

标签 django selenium static

我一直在尝试测试一个 css 文件是否加载。

我尝试使用以下代码,但它返回 404 代码。 css 文件在浏览器中加载正常。

client = Client()
response = client.get('/static/css/astyle.css')
self.assertEqual(200, response.status_code) # 200 != 404

如何使用 selenium 来测试 css 文件是否加载?

最佳答案

无论您在 settings.py 文件中指定什么,测试服务器都使用 DEBUG = False。这意味着 Django 在运行测试时不会提供静态文件,这就是您看到 404 状态的原因。

我认为您可以测试静态文件是否存在于正确的目录中,而不是查找 http 状态代码。

from django.contrib.staticfiles.storage import staticfiles_storage #The file storage engine to use when collecting static files with the collectstatic management command.
from django.contrib.staticfiles import finders


class MyTest(unittest.TestCase):
    self.assertTrue(staticfiles_storage.exists(finders.find('css/astyle.css')))

当然,您需要另一个测试来查看您的服务器配置是否可以提供静态文件,但这超出了 django 开发的范围。

关于Django测试加载css文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22991071/

相关文章:

java - java中的Selenium下拉问题

python - Flask & uwsgi 不渲染静态文件夹中的文件

python - 使用 to_representation 自定义 Django 序列化器输出

python - 如何更改 settings.py 以从 SQLite3 数据库迁移到 mysql 数据库?

python - Selenium for Python : Get text() of node that is shared with another element, 通过 XPath

python - Selenium 使用 Send_keys 自动提交表单?

python - 如何用 Python 编写自己的 OrderedDict 类?

python - 获取 auth_user 的所有 Django 级联依赖模型

Java:覆盖父类的静态变量?

c++ - 如何定义静态运算符<<?