Klevtsov Andrey
Klevtsov Andrey

Reputation: 79

How to run selenium+pytest in docker?

I'm new in using docker, so I have problems trying to run my selenium tests in it. I know that I need to run selenium server either with grid or standalone and it works fine, but how do I run my tests through docker (docker run mytest:1.0)? I'm keep getting errors such as "urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=4444): Max retries exceeded with url: /wd/hub/session", but if I run my tests on local machine - it works fine.

Dockerfile:

FROM python:3.8
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . /tests
WORKDIR /tests
CMD [ "pytest", "-vv", "-s", "test_selenium.py" ]

Docker-compose.yaml:

version: "3"
services:
  chrome:
    image: selenium/node-chrome:4.0.0-rc-1-prerelease-20210823
    shm_size: 2gb
    depends_on:
      - selenium-hub
    environment:
      - SE_EVENT_BUS_HOST=selenium-hub
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
    ports:
      - "7900:7900"

  selenium-hub:
    image: selenium/hub:4.0.0-rc-1-prerelease-20210823
    container_name: selenium-hub
    ports:
      - "4442:4442"
      - "4443:4443"
      - "4444:4444"

My driver initialization in test_file:

driver = webdriver.Remote('http://localhost:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME)

Upvotes: 3

Views: 2702

Answers (1)

Klevtsov Andrey
Klevtsov Andrey

Reputation: 79

Your docker-compose.yaml should only launch selenium server and nodes which are equal to the browsers you want to launch on the server.

version: '3'
services:
  chrome:
    image: selenium/node-chrome:latest
    shm_size: 2gb
    networks:
      - selenium
    depends_on:
      - selenium-hub
    environment:
      - SE_EVENT_BUS_HOST=selenium-hub
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
    ports:
      - '7900:7900'

  selenium-hub:
    image: selenium/hub:latest
    container_name: selenium-hub
    networks:
      - selenium
    ports:
      - '4442:4442'
      - '4443:4443'
      - '4444:4444'

networks:
  selenium:
    name: selenium

No changes are needed in your Dockerfile.

Your driver initialization in test_file should look like this :

driver = webdriver.Remote('http://localhost:4444/wd/hub', options=webdriver.ChromeOptions())

Note the usage of options here since desired_capabilities is deprecated.

After making the above changes, run the following commands in order :

  1. docker-compose up
  2. docker run --network "host" selenium_test:1.0

Upvotes: 2

Related Questions