我一直在尝试测试一个 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/