Running headless Selenium browser tests on PythonAnywhere with Xvfb

You can now run Selenium tests from PythonAnywhere, using a virtual display.

PythonAnywhere is a fully browser-based Python development environment. So that includes an editor, consoles to actually run your scripts, and a web hosting platform too... But until now, it hasn't been perfect for the Best Form of Development(TM), namely test-driven development, TDD.

Being an XP shop, we're very keen on TDD and functional testing, for which we use Selenium to drive a real web browser, and check the actual behaviour of our site. Until now we've not been able to "dogfood" our selenium tests and run them from PythonAnywhere itself, because opening up a real web browser tends to mean needing a real display, something our servers don't have.

But a solution exists! Even "headless" servers can use a virtual display like Xvfb to spoof apps like Firefox into running, even if there's no real screen for them to actually be displayed on. Inspired by this post, we've now added the binaries for Xvfb and Firefox (well, iceweasel actually) to our servers, as well as the excellent pyVirtualDisplay module, so running selenium tests on PythonAnywhere is now as easy as this:

from pyvirtualdisplay import Display
from selenium import webdriver

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

try:
    # we can now start Firefox and it will run inside the virtual display
    browser = webdriver.Firefox()
    browser.get('http://www.google.com')
    print browser.title #this should print "Google"

finally:
    #tidy-up
    browser.quit()
    display.stop() # ignore any output from this.

(Code shamelessly stolen from Corey Goldberg)

Give it a go! And if you need some inspiration for what kind of tests to run, I can recommend an excellent TDD/Django/Selenium book ;-)

[edited by admin on 2016-11-17 to update broken link]

blog comments powered by Disqus

PythonAnywhere is a Python development and hosting environment that displays in your web browser and runs on our servers. They're already set up with everything you need. It's easy to use, fast, and powerful. There's even a useful free plan.

You can sign up here.