使用 Selenium 的 StaticLiveServerTestCase:ERR_CONNECTION_REFUSED

StaticLiveServerTestCase with Selenium: ERR_CONNECTION_REFUSED

我正在 运行 使用 docs 中的默认代码片段来使用 selenium 进行测试,但我正在使用 Chrome 驱动程序。当我 运行 使用 python manage.py test 进行测试时,它无法连接到服务器,似乎无法启动,并抛出错误 ::ERR_CONNECTION_REFUSED。有什么想法吗?

这是片段:

from django.test import LiveServerTestCase
from selenium import webdriver

class MySeleniumTests(LiveServerTestCase):
    # fixtures = ['user-data.json']

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.selenium = webdriver.Chrome(executable_path='./chromedriver')
        cls.selenium.implicitly_wait(10)

    @classmethod
    def tearDownClass(cls):
        cls.selenium.quit()
        super().tearDownClass()

    def test_login(self):
        self.selenium.get('http://localhost:8000/accounts/login')

为什么 url 硬编码 (localhost:8000) 在 test_login 中?由于您使用的是 LiveServerTestCase,因此您可以使用 self.live_server_url 访问服务器库 URL。您在说明中添加的文档 link 中也提到了这一点。由于以下原因之一,hard-coded URL 很可能会发生连接被拒绝错误:

  1. 8000 端口没有服务器或服务处于活动状态
  2. 允许的来源设置不允许连接,尽管这完全取决于设置。