Python is fairly good programming language for writing and maintaining unit and functional tests. One advantage of python is that it does not require compilation like Java and hence debug cycle can be little faster for simple tests. This article will cover pytest (py.test) to test various pages on a website. Here are quick steps to get started with pytest for writing functional tests on Ubuntu Linux.
First install pip (if not installed) and pytest using the following commands:
$ sudo apt-get install python-pip $ sudo pip install pytest
Write site testing code using pytest
Write the following code in a file test_hello.py in a new directory. Note that file name begins with
test_ here as py.test looks for these files when no argument is specified.
#!/usr/bin/python import pytest, urllib2 class TestHello(): def test_page(self): print "Starting test..." url = "https://google.co.in/" req = urllib2.Request(url) response = urllib2.urlopen(req) data = response.read() response.close() assert(response.getcode(), 200, "HTTP status code must be 200") assert(data.find("</html>") > 0, "response html must have closing html tag") print "Done with the test..."
Now run the test using the following command in same directory:
$ py.test ==================================================================== test session starts ==================================================================== platform linux2 -- Python 2.7.6, pytest-2.8.2, py-1.4.30, pluggy-0.3.1 rootdir: /home/gopj/svn/cloud/infoheap/ui/tests, inifile: collected 1 items test_hello.py . ================================================================= 1 passed in 0.12 seconds ==================================================================
Note that we checked if the status code of http request is 200 and also the page content should have “