Needle is a tool for testing your CSS with Selenium and nose.
It checks that CSS renders correctly by taking screenshots of portions of a website and comparing them against known good screenshots. It also provides tools for testing calculated CSS values and the position of HTML elements.
If you haven’t got pip installed:
$ sudo easy_install pip
As root, or in a virtualenv:
$ pip install -r requirements.txt
$ python setup.py install
Download selenium-server-standalone-2.8.0.jar. By default, Selenium requires Firefox 4.
Run the Selenium server:
$ java -jar selenium-server-standalone-2.8.0.jar
Create test_bbc.py in an empty directory:
from needle.cases import NeedleTestCase
class BBCNewsTest(NeedleTestCase):
def test_masthead(self):
self.driver.get('http://www.bbc.co.uk/news/')
self.assertScreenshot('#blq-mast', 'bbc-masthead')
This is a test case which tells the Selenium server to open BBC News and check the bar across the top of the page looks correct. assertScreenshot() take two arguments: a CSS selector for the element we are capturing and a filename for the image.
To create an initial screenshot of the logo, we need to run Needle in capture mode:
$ nosetests test_bbc.py --with-needle-capture
This will create bbc-masthead.png. Open it up and check it looks okay.
Now if we run our tests, it will take the same screenshot and check it against the screenshot on disk:
$ nosetests test_bbc.py
If a regression in your CSS causes them to become significantly different, the test will fail.
Needle adds a few useful methods to Selenium’s WebElement object. For example, we can check computed CSS values:
from needle.cases import NeedleTestCase
class GoogleTest(NeedleTestCase):
def test_footer(self):
self.driver.get('http://www.google.com')
e = self.driver.find_element_by_id('fctr')
self.assertScreenshot(e, 'google-footer')
self.assertEqual(e.get_computed_property('font-size'), '13px')