在docker容器外运行pytest命令失败,因为容器已停止



我使用docker selenium grid和pytest来执行测试。我现在做的是:

  • 通过makerfile启动selenium grid
  • 启动docker容器(一个卷指向我的本地pc进行测试)。容器也运行pytest命令。

这一切都很好,除了我宁愿分割第二个动作,并能够在一个已经运行的容器上运行测试。首选设置:

  • 使用pyton+pytest启动selenium grid + docker容器
  • 运行测试的命令(使用容器作为解释器)

当我尝试这样做时,我遇到了python+pytest容器在命令全部完成后停止运行的问题。没有长生命过程。

Dockerfile
FROM python:3.9.0-alpine
RUN apk add tk
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
RUN ls ..
CMD pytest --junitxml ../r/latest.xml

我的docker-compose文件看起来像:

docker-compose.yml
version: "3.0"
services:
pytest:
container_name: pytest
build:
context: .
dockerfile: Dockerfile
volumes:
- ./t:/t 
- ./r:/r 
working_dir: /t/
networks:
default:
name: my_local_network #same as selenium grid

在容器设置本身中使用这个pytest命令并不"感觉"好。

容器关闭

这是因为CMD pytest --junitxml ../r/latest.xml行将执行一次,完成后它将退出容器。

在现有容器上运行cmd

你可以运行命令在现有码头工人容器使用这个命令:

docker exec <container_name> python -m pytest

在您的情况下,<container_name>将是pytest,因为这是您的docker-compose.yml文件中容器的名称。

查看更多信息:https://docs.docker.com/engine/reference/commandline/exec/


使用使

如果您想将其扩展为makefile命令:

docker:
docker-compose up -d
ci-tests: docker
docker exec <container_name> python -m pytest

要同时启动和运行测试,可以使用:

make ci-tests

如果你想让这个解决方案完全可移植,你也可以在docker中运行selenium-grid: https://www.conductor.com/nightlight/running-selenium-grid-using-docker-compose/

最新更新