为了执行测试,我通常运行一个单独的容器:
docker-compose run --rm web /bin/bash
其中 web 是 django 的容器。我不时从 shell 执行 py.test。
为了能够使用 django 从容器访问 selenium 并允许来自 selenium 容器的浏览器访问 django 的 liveserver 我决定使用允许容器共享网络的“net”参数。所以我将它添加到 yml 中:
selenium:
image: selenium/standalone-firefox
net: "container:web"
不幸的是,这不起作用。我在我的 Django 容器中没有看到 4444 端口。
它只有在我指定一个自动生成的容器名称而不是 net:"container:web"
时才有效,例如 net:"container:project_web_run_1"
。
我还尝试使用 docker-compose up --no-deps
更改 command
而不是 docker-compose run --rm ....
code> 参数添加到 py.test functional_tests
但这也不起作用。
这就是容器使用selenium的权利吗?
最佳答案
这是我的做法。基本问题是 docker-compose run 会生成一个不同的主机名 (project_container_run_x),其中 x 很难确定。我最终只是离开了 ip 地址。我还要确保 DEBUG 为 False,否则我会收到错误的请求。
我正在像这样使用 StaticLiveServerTestCase:
import os
import socket
os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = '0.0.0.0:8000'
class IntegrationTests(StaticLiveServerTestCase):
live_server_url = 'http://{}:8000'.format(
socket.gethostbyname(socket.gethostname())
)
def setUp(self):
settings.DEBUG = True
self.browser = webdriver.Remote(
command_executor="http://selenium:4444/wd/hub",
desired_capabilities=DesiredCapabilities.CHROME
)
def tearDown(self):
self.browser.quit()
super().tearDown()
def test_home(self):
self.browser.get(self.live_server_url)
我的 docker-compose 文件有这个用于 selenium 并扩展了 web 容器(运行 django 的地方)。端口 5900 对 VNC 开放。我喜欢将它隔离在类似 docker-compose.selenium.yml 的东西中
version: '2'
services:
web:
environment:
SELENIUM_HOST: http://selenium:4444/wd/hub
TEST_SELENIUM: 'yes'
depends_on:
- selenium
selenium:
image: selenium/standalone-chrome-debug
ports:
- "5900:5900"
我可以像这样运行测试
docker-compose run --rm web ./manage.py test
因此我的 Web 容器正在通过“selenium”主机访问 selenium。 Selenium 然后通过动态确定的 IP 地址访问 Web 容器。
另一个问题是,很容易只使用“web”作为主机名。如果您的 docker-compose run 命令启动了一个单独的 Web 容器——这似乎可以工作。但是,它不会使用您的测试数据库,这不是一个很好的测试。
关于python - 在 docker 中使用 selenium 运行 django 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32408429/