PyCharm unable to connect to GhostDriver

Stackoverflow Link -

I have a really simple unit test that is failing in PyCharm.

import unittest

class SimpleTestCase(unittest.TestCase):
    def test_alpha(self):
        from selenium.webdriver.common.utils import free_port
        from selenium import webdriver

        driver = webdriver.PhantomJS(executable_path=PHANTOMJS_PATH, port=free_port())

The test times out after 30 seconds. The exception I get when I run the test from within PyCharm is

WebDriverException: Message: 'Can not connect to GhostDriver'

However, everything works fine when I run it from my terminal. What is strange is that when I change free_port() call into a number, the test passes within PyCharm!

# if 50000 is a free port - this test PASSES
driver = webdriver.PhantomJS(executable_path=PHANTOMJS_PATH, port=50000)

To quickly recap:

  • Test passes when I run it from my terminal
  • Test passes in PyCharm if port is specified manually
  • Test fails in PyCharm if port=free_port()

# For convenience, the `free_port()` code snippet is here
# selenium.webdriver.common.utils.freeport

def free_port():
    free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    free_socket.bind(('', 0))
    port = free_socket.getsockname()[1]
    return port

What is PyCharm doing that is making the test unable to connect to Ghostdriver?

For anyone who wanting to try this out on their machine, only selenium and phantomjs need to be installed.

pip install selenium
sudo npm install -g phantomjs

Please sign in to leave a comment.