【问题标题】:django selenium LiveServerTestCasedjango selenium LiveServerTestCase
【发布时间】:2015-12-26 04:05:58
【问题描述】:

我对 selenium 和 LiveServerTestCase 有疑问。 当我运行./manage.py test functional_tests 时,它会加载一个页面“标题:加载页面时出现问题。正文:无法连接...”

functional_tests.py:

from selenium import webdriver
from django.test import LiveServerTestCase

class GeneralFunctionalTests(LiveServerTestCase):
    def setUp(self):
        self.browser = webdriver.Chrome()
        self.browser.implicitly_wait(3)

    def tearDown(self):
        self.browser.quit()

    def test_can_navigate_site(self):
        self.browser.get('http://localhost:8000')
        assert 'Django' in self.browser.title

我尝试使用 classmethod 设置和拆卸:

@classmethod
def setUpClass(cls):
    super(MySeleniumTests, cls).setUpClass()
    cls.browser = WebDriver()
...

结果是一样的。 但我可以使用self.browser.get('http://example.com') 加载网页中的任何其他页面。 Selenium 是最新的。

谢谢!

【问题讨论】:

    标签: python django selenium


    【解决方案1】:

    你做错了什么?

    LiveServerTestCase 默认情况下在端口8081 上运行实时服务器,您正在尝试访问端口8000 上的url。现在,由于没有服务器监听 8000 端口,浏览器无法加载页面。

    来自LiveServerTestCase docs:

    默认情况下,实时服务器的地址是 localhost:8081 和完整的 在测试期间可以使用 self.live_server_url 访问 URL。

    您需要做什么?

    选项 1:更改网址

    您可以将 url 更改为指向8081 端口。

    def test_can_navigate_site(self):
        self.browser.get('http://localhost:8081') # change the port
        assert 'Django' in self.browser.title
    

    选项 2:使用实时服务器 url

    正如@yomytho 也指出的那样,您可以在测试用例中使用live_server_url

    def test_can_navigate_site(self):
        self.browser.get(self.live_server_url) # use the live server url
        assert 'Django' in self.browser.title
    

    选项 3:在端口 8000 上运行实时服务器

    在 Django 1.10 之前,您可以通过 --liveserver 选项将端口号 8000 传递给测试命令,以在端口 8000 上运行 liveserver。

    $ ./manage.py test --liveserver=localhost:8000 # run liveserver on port 8000
    

    这个参数是removed in Django 1.11,但现在你可以在你的测试类上设置端口了:

    class MyTestCase(LiveServerTestCase):
        port = 8000
    
        def test_can_navigate_site(self):
            ....
    

    【讨论】:

    【解决方案2】:

    您尝试获取错误的服务器地址:by default, the address is http://localhost:8081

    访问正确地址的最佳方法是使用self.live_server_url

        def test_can_navigate_site(self):
            self.browser.get(self.live_server_url)
    

    【讨论】:

      【解决方案3】:

      对于使用Django 1.11LiveServerTestCase)的用户:

      实时服务器侦听localhost 并绑定到端口0,该端口使用操作系统分配的空闲端口。在测试期间可以使用self.live_server_url 访问服务器的 URL。

      所以...使用self.live_server_url

      【讨论】:

      • 该死。真的很好看。由于之前的安全问题,它会“随机”绑定端口吗?
      猜你喜欢
      • 2013-01-19
      • 1970-01-01
      • 2014-07-13
      • 2013-06-18
      • 2019-12-02
      • 2016-01-16
      • 1970-01-01
      • 2013-03-21
      • 2017-10-16
      相关资源
      最近更新 更多