Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django selenium LiveServerTestCase

I have an issue with selenium and LiveServerTestCase. When I run ./manage.py test functional_tests it loads a page "Title: Problem loading page. Body: Unable to connect..."

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

I tried to setUp and tearDown using classmethod:

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

Result is the same. But I could load any other pages in web with self.browser.get('http://example.com'). Selenium is up to date.

Thank You!

like image 943
tack Avatar asked Sep 28 '15 20:09

tack


2 Answers

What you are doing wrong?

LiveServerTestCase runs the live server on port 8081 by default and you are trying to access the url on port 8000. Now, since there is no server listening on port 8000, the browser is not able to load the page.

From the LiveServerTestCase docs:

By default the live server’s address is localhost:8081 and the full URL can be accessed during the tests with self.live_server_url.

What you need to do instead?

Option 1: Changing the url

You can change the url to point to 8081 port.

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

Option 2: Using the live server url

You can use the live_server_url in your test case as @yomytho has also pointed out.

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

Option 3: Running the live server on port 8000

Until Django 1.10, you can pass the port number as 8000 to the test command via the --liveserver option to run the liveserver on port 8000.

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

This parameter was removed in Django 1.11, but now you can set the port on your test class:

class MyTestCase(LiveServerTestCase):
    port = 8000

    def test_can_navigate_site(self):
        ....
like image 91
Rahul Gupta Avatar answered Nov 09 '22 03:11

Rahul Gupta


You're trying to get the wrong server address : by default, the address is http://localhost:8081.

The best way to access the right address is to use self.live_server_url :

    def test_can_navigate_site(self):
        self.browser.get(self.live_server_url)
like image 25
yomytho Avatar answered Nov 09 '22 03:11

yomytho