📜 ⬆️ ⬇️

Testing Django Applications with Selenium



Selenium


Selenium is a very convenient (IMHO) tool for testing web applications.

Tests are created using Firefox Add-on, which can generate test code in various languages, including Python. Then these tests are performed by a special server, Selenium RC.
')
By itself, Selenium is not tied to any languages ​​or frameworks, so to integrate it into the Django application testing system, you need to make very little effort.

To solve the integration problem, I will use the Django library: Sane Testing. It is a library that extends the capabilities of the standard Django testing system, including support for Selenium tests.


Put Django: Sane Testing


Installing this library would be standard if it did not pull Django behind. What is not right, if you use a trunk, like me.

Download the current release , unpack (you can in / tmp), open setup.py, find

install_requires = [ 'Django>=1.0_final' , 'nose>=0.10' ], <br/>
either delete or comment on the Django part. After that we put:

sudo python setup.py install



We put Selenium


Need to put the server and plugin for Firefox. Both are on the download page .

To install the plugin, just open the Selenium IDE link, allow the plugin installation, install it and restart Firefox. In addition, the respected bazzzman wrote an extension for this plugin (!) , For the convenience of work.

To install the server, you need to download the archive by the link Selenium RC, unpack it somewhere. In the resulting directory after unpacking there will be several subdirectories. Among them will be selenium-server-xyz, this is the directory with the server. The server itself is the selenium-server.jar file. Here we copy it somewhere, in a convenient place, for example in / usr / local / lib, after which the entire unpacked directory can be rubbed, it is no longer needed.

For convenient start we create a script,

sudo nano / usr / local / bin / selenium-server

with this content:

#! / bin / bash
/ usr / bin / env java -jar /usr/local/lib/selenium-server.jar

We ask him the right to perform:

sudo chmod 755 / usr / local / bin / selenium-server

Check: after executing the / usr / local / bin / selenium-server command, something like this should appear:

23:58:17.788 INFO - Java: Sun Microsystems Inc. 14.2-b01
23:58:17.798 INFO - OS: Linux 2.6.31-14-generic i386
23:58:17.863 INFO - v1.0.1 [2696], with Core v@VERSION@ [@REVISION@]
23:58:18.111 INFO - Version Jetty/5.1.x
23:58:18.113 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]
23:58:18.114 INFO - Started HttpContext[/selenium-server,/selenium-server]
23:58:18.114 INFO - Started HttpContext[/,/]
23:58:18.166 INFO - Started SocketListener on 0.0.0.0:4444
23:58:18.166 INFO - Started org.mortbay.jetty.Server@fc9944


if it is, then the server is working OK.



Test project


Create a test project:

django-admin.py startproject justtotest

The project will have one application, let's call it habrahabr:

./manage.py startapp habrahabr

Our test Habr will consist of one model:

class Greeting (models.Model):
text = models.CharField (max_length = 200 )


one form to enter greetings:

class GreetingForm (forms.ModelForm):
text = forms.CharField (widget = forms.TextInput (attrs = { 'size' : '40' }),
error_messages = { 'required' : 'Do you enter the greeting text? ' })
class Meta :
model = Greeting


and one view:

def Greetings (request):
template_name = 'habrahabr / index.html'
title = 'Selenium'
if request.method == 'GET' :
form = GreetingForm ()
else :
form = GreetingForm (request.POST)
if form.is_valid ():
text = form.cleaned_data [ 'text' ]
new_greeting = Greeting (text = text)
new_greeting.save ()
return HttpResponseRedirect ( '/' )
greetings = Greeting.objects.all (). order_by ( '-id' )
context = {
'title' : title,
'greetings' : greetings,
'form' : form,
}
return render_to_response (template_name, context,
context_instance = RequestContext (request))


which displays a list of previously added greetings and a form for adding a new greeting.



Creation of the test Selenium


Run the project and create a test in the browser using a plugin, look at the video (I advise you to look at HQ):



As you can see, we got the code on the python. From this generated code, take a class file and modify it a little bit to make this :.

# coding: utf-8

from djangosanetesting.selenium.driver import selenium
import unittest, time, re

class Untitled ( unittest .TestCase):

test_type = "selenium"
start_live_server = True

def setUp (self):
self .start_live_server = True
self .verificationErrors = []
self .selenium = selenium ( "localhost" , 4444 , "* chrome" , " 127.0.0.1 : 8000 /" )
self .selenium.start ()

def test_required_text_exists (self):
sel = self .selenium
sel. open ( "/" )
sel. type ( "id_text" , "Testing with Selenium" )
sel.click (u "// input [@ value = 'Add']" )
sel.wait_for_page_to_load ( "30000" )
try : self .failUnless (sel.is_text_present ( "Testing with Selenium" ))
except AssertionError, e: self .verificationErrors.append ( str (e))

def tearDown (self):
self .selenium.stop ()
self .assertEqual ([], self .verificationErrors)

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


We added two attributes to the class. test_type - indicates the type of test and start_live_server - it says that you will need to start the test server.

In addition, the imports are different, after installing sane, we already have everything in the installed package.



Scripts to run tests


There are two options for running tests. The first option is to add the TEST_RUNNER variable in settings.py, but in this case it’s impossible to select individual test types, for example, only unit tests, or only selenium tests, and you don’t always have to run everything.

Therefore, I chose the second option - wrote scripts to run tests. The first script, nose-selenium:

#! / bin / bash
DJANGO_SETTINGS_MODULE = “settings” PYTHONPATH = ".: .." nosetests --with-django --with-djangoliveserver --with-sanetestselection - select -seleniumtests;

This script will run Selenium tests with a test server.

The second script, nose-unittests:

#! / bin / bash
DJANGO_SETTINGS_MODULE = “settings” PYTHONPATH = ".: .." nosetests --with-django --with-sanetestselection - select -unittests;

This script will run unit tests, without a test server.

You can make the necessary scripts for all occasions, all types of tests are listed in the documentation . Do not forget to set the script execution rights, chmod 755 .



Running tests


Now everything is ready to run the tests. You need to start the Selenium server, / usr / local / bin / selenium-server, after which you can run tests using scripts.

I did not make a screencast, but be sure that everything works OK - the browser starts, contacts the server, fills in the form, checks for the presence of text, the results are displayed as usual.

The code for the article posted on Yandex , if the file disappears from there, write in a personal.



Summary


In my opinion, selenium is a good addition to the test system, since allows you to test javascript-rich interfaces that the standard test system can not do. In addition, Django: Sane Testing itself offers additional features, which I advise you to read in the documentation .

I hope my article will be useful for a wide range of Django-developers, both beginners and experienced. From experienced developers waiting for comments on the topic :-)



PS


Windmill did not try. If it is simpler / better / safer than Selenium, please describe in the comments or in the form of an article. Link to the article put in the beginning of this.

Source: https://habr.com/ru/post/74334/


All Articles