Django应用程序Selenium测试无静态文件。

22

我希望对我的Django应用程序进行一些功能测试。我正在使用Selenium,测试工作正常,但问题出在静态文件上。CSS/JS状态未找到。我的测试正在本地主机上运行:localhost:8081。例如,bootstrap.css:

<h1>Not Found</h1><p>The requested URL /static/frontend/bootstrap/3.3.0/css/bootstrap.css was not found on this server.</p>

我找不到任何信息,我是否需要添加一些额外的配置来使用selenium应用程序?

引用追踪:

Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/home/t/py/django/bid/src/venv/local/lib/python2.7/site-packages/django/test/testcases.py", line 1028, in __call__
    return super(FSFilesHandler, self).__call__(environ, start_response)
  File "/home/t/py/django/bid/src/venv/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__
    response = self.get_response(request)
  File "/home/t/py/django/bid/src/venv/local/lib/python2.7/site-packages/django/test/testcases.py", line 1011, in get_response
    return self.serve(request)
  File "/home/t/py/django/bid/src/venv/local/lib/python2.7/site-packages/django/test/testcases.py", line 1023, in serve
    return serve(request, final_rel_path, document_root=self.get_base_dir())
  File "/home/t/py/django/bid/src/venv/local/lib/python2.7/site-packages/django/views/static.py", line 50, in serve
    fullpath = os.path.join(document_root, newpath)
  File "/home/t/py/django/bid/src/venv/lib/python2.7/posixpath.py", line 77, in join
    elif path == '' or path.endswith('/'):
AttributeError: 'NoneType' object has no attribute 'endswith'
3个回答

45

不要使用django.test中的LiveServerTestCase,而是可以使用django.contrib.staticfiles.testing中的StaticLiveServerTestCase

注意不仅是类名不同,模块名也不同:

from django.test import LiveServerTestCase
#     ^-- vs --v
from django.contrib.staticfiles.testing import StaticLiveServerTestCase

救命稻草。我找到的所有Selenium文档都是针对Django 1.6的。 - MagicLAMP

9

好的,我找到了解决方案。首先,我需要在设置中添加

STATIC_ROOT = 'my static dir'

然后:
./manage.py collectstatic

2
谢谢,LiveServerTestCase 使用生产设置(DEBUG = True),因此需要先收集静态文件。现在很清楚了。 - MartinM
3
@MartinM 这应该是DEBUG = False吗? - Jamie Bull

3

我曾遇到类似问题,但以上回答都没有帮到我。

如果你正在使用Whitenoise作为静态文件服务器,你可能需要改变你应用中STATICFILES_STORAGE设置的值:

STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

致:

STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"

那解决了我的问题。请查看此页面以获取更多信息。

1
非常感谢您的回答!否则我会在这上面花费无数个小时。我真的很想知道是什么导致了这个问题。 - SaturnFromTitan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接