Thursday, June 9, 2011

Python - Headless Selenium WebDriver Tests using PyVirtualDisplay

I need to integrate my functional UI tests (Selenium/WebDriver) with my Jenkins CI system. The problem is that my Jenkins CI server has no display, so I must run my GUI tests in a headless X-server.

A colleague pointed me to PyVirtualDisplay, a Python wrapper for Xvfb and Xephyr.

This makes running headless Python Selenium/WebDriver tests very easy.

Here is some Python code showing WebDriver with a virtual display provided by Xvfb:

    
#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

install PyVirtualDisplay on Ubuntu/Debian:

$ sudo apt-get install xvfb python-pip
$ sudo pip install pyvirtualdisplay

9 comments:

cburgmer said...

That sounds neat! I'll definitely give it a try.

Marius Gedminas said...

I have vague memories of seeing that Jenkins has a native xvfb plugin.

For buildbot jobs, I used to wrap my test-runner command with Debian's xvfb-run wrapper.

I find the PyVirtualDisplay solution (that I didn't know about) very interesting as well. You could take a screenshot when tests fail, to figure out why that happened.

Anonymous said...

Great post! Like Marius, I find that xvfb-run java -jar selenium-server-standalone-2.0b3.jar works really well if your stuck with Selenium RC.

Matt Austin said...

Very nice, I hadn't heard of Selenium before - looks very cool, especially as it can be paired with xvfb.

Prashant said...

Try xvnc plug-in for Jenkins

John said...

This code doesn't work for me on OS X Snow Leopard, I see the Firefox window.

Is there something other than PyVirtualDisplay and Selenium I need to install?

Jason said...

I agree with John this doesn't work for me on OS X 10.6. It still opens like normal.

Corey Goldberg said...

John, Jason,
pyvirtualdisplay has some dependencies (xvfb, etc). I show how to satisfy them on Ubuntu/Debian. You are on your own for Mac.

hth,

-Corey

Anonymous said...

Just wanted to say this was quite helpful for me, was struggling to find docs on how to run it headless. Works with no probs, Debian wheezy.