Skip to content

Preparing Docker image for running Selenium tests

rohinigopalqxf2 edited this page Dec 19, 2019 · 27 revisions

The following guide contains instructions on how to create a Dockerfile, build a image, run selenium tests on a Docker container. This guide assumes minimal working knowledge of Docker.

  1. Creating the Dockerfile
  2. Building the Docker image
  3. Running the Docker Container
  4. Running python based Selenium tests

Creating the Dockerfile

We have created a Dockerfile and placed it in the Root directory. This file will instruct Docker to:

  1. Pull ubuntu 16.04 base image from Docker Hub.
  2. Install essential developer tools.
  3. Install user specified chrome version and chrome driver version
  4. Install user specified firefox version and Geckodriver version
  5. Install Python 3.5 and Python Pip

Building the Docker image

Run the following command from root directory to build an image with the chrome version you want from the Dockerfile

docker build -t python-selenium-chrome --build-arg CHROME_DRIVER_VERSION=2.28 --build-arg CHROME_VERSION=57.0.2987.133 -f Dockerfile .

or

docker build -t python-selenium-chrome --build-arg CHROME_DRIVER_VERSION=latest --build-arg CHROME_VERSION=latest -f Dockerfile .

Run the following command from root directory to build an image with the firefox version you want from the Dockerfile

docker build -t python-selenium-firefox --build-arg GECKODRIVER_VERSION=0.19.0 --build-arg FIREFOX_VERSION=59.0.2 -f Dockerfile .

or

docker build -t python-selenium-firefox --build-arg GECKODRIVER_VERSION=latest --build-arg FIREFOX_VERSION=latest -f Dockerfile .

Running the Docker Container

Now we'll spin up a container based on the image created. Run below command to create a Docker container.

docker run -it python-selenium-chrome "/bin/bash"

Running python based selenium tests

The images that we created are capable of running any Python-based Selenium tests. To run the Selenium tests using this image, you need do the following

  1. Export display and enable Xvfb using following 2 commands:
export DISPLAY=:20
Xvfb :20 -screen 0 1366x768x16 &
  1. Install Selenium using pip
pip3 install selenium
  1. Use any Linux editor you like and add your test inside the container. You can also use the sample Selenium code (selenium_sample.py) given below. This test visits Qxf2 Services website and prints the title.
# contents of selenium_sample.py
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://www.qxf2.com")
print(driver.title)
driver.quit()
  1. Run the test using the following command:
python3 selenium_sample.py