我有一个单元测试,当我通过 运行它时它通过了python manage.py test
,但是当我从 PyCharm 中运行它时它失败了。
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())
driver.quit()
从 PyCharm 运行时遇到的异常是
WebDriverException: Message: 'Can not connect to GhostDriver'
我花了相当多的时间来研究这个问题,并且我注意到当我手动指定一个端口时,测试在 PyCharm 中通过了。
# suppose 50000 happens to be a free port on your computer
driver = webdriver.PhantomJS(executable_path=PHANTOMJS_PATH, port=50000)
快速回顾一下:
- 测试通过
python manage.py test
- 如果手动指定端口,则测试通过 PyCharm
- 如果在 PyCharm 中测试失败
port=free_port()
PyCharm 在做什么使测试无法连接到 Ghostdriver?
# 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(('127.0.0.1', 0))
free_socket.listen(5)
port = free_socket.getsockname()[1]
free_socket.close()
return port