Testing Django applications with Selenium
Testing applications and their frontend with an automated browser
In Django 1.4 we got LiveServerTestCase - a TestCase that spawns a test server. This allowed much easier Selenium integration in Django tests. You can change a presentation on benlopatin.com. If you will find something different - check the date as it may describe older solutions for older Django versions.
In this article I'll show some basic Selenium usage cases in tests - showcasing the api.
BasicsAt start install Python selenium package:
Methods of this class can use self.selenium to operate via Selenium on a browser (in this case Firefox). You can open URLs, find elements on page, fill and submit forms and more. Aside of mentioned presentation you can look at the sources or documentation for a list of API methods available.A simple Selenium test checking if "Django administration" header is displayed on /admin/ URL would look like so: The H1 header of the admin panel has an ID "site-name" so I can use "find_element_by_id" to get the element. This test is simple, doable also via standard test engine, but in real tests Selenium will usually tests something not testable with standard TestCase.
To test this login process with selenium we will need a test Facebook user and one change in used Facebook app config. The "Site URL" (Website with Facebook Login) needs to be set to "http://localhost:8081/" - which is the default URL of the dev server during tests. As the test user you have to autorize the application prior to running selenium tests (so that they get only the login form and not extra authorization form).The test looks like so:
open_login_page opens given url (self.selenium.get) and then finds a link given by ID on that opened page (self.selenium.find_element_by_id). The link is clicked which opens the login window.
submit_login_form finds form fields (find_element_by_name) and fills them with data (send_keys) - email and password. In the end it finds a submit type button and clicks it submitting the form.
When something is not thereSelenium find methods will raise NoSuchElementException if they can't find given element. That can also be used for tests checking if something is not there. Just import the exceptions:
That's how testing with Selenium looks like, at least in the basic form. This tool can also be used for acceptance tests checking user flow on the website or for task automation on external websites (login, check for data or perform some actions).