[Fixed]-Django selenium LiveServerTestCase

23👍

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):
        ....

8👍

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)

6👍

For users who are using Django 1.11 (LiveServerTestCase):

The live server listens on localhost and binds to port 0 which uses a free port assigned by the operating system. The server’s URL can be accessed with self.live_server_url during the tests.

So… use self.live_server_url.

Leave a comment