Run your Python Selenium tests headless

This time i show you the headless testing with Selenium WebDriver and PhantomJS. This method can be used for example on continuous integration systems.

Install PhantomJS

Follow the documentation on PhantomJS website or as Mac OS X user simply use Mac Ports.

# on Mac OS X
$ sudo port install PhantomJS

# check version
$ phantomjs --version

Create a tiny test script

#!/usr/bin/env python
import unittest
from selenium import webdriver


class SearchContentOnWebsite(unittest.TestCase):

    def setUp(self):
        # create a new PhantomJS session
        self.driver = webdriver.PhantomJS()
        self.driver.set_window_size(800, 600)
        self.driver.get("http://softwaretester.info")

    def test_search_headline(self):
        title = 'This will fail | - Softwaretester -'
        assert title in self.driver.title

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main(verbosity=2)

Just create a instance of PhantomJS WebDriver and run you tests. That is all! 😉