Python Automation Scripts Examples Use Django And Selenium

Django is the most popular web framework in python world. You can use it to create a web site quickly and simple. Selenium is the most popular web site automation testing framework, it can be used to implement web site automation function testing in source code with coding language python, java etc. This example will tell you how to setup and run Django and Selenium to make a development environment for web site functional test.

If you do not install Python Django and selenium module, you need to install them first. You can run pip list command in a terminal to verify the Python Django and selenium module installation. If the two module do not exist in the list, follow below steps to install them.

1. Use Pip To Install Django Python Module.

192:~ $ pip install django
Collecting django
  Downloading https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl (7.3MB)
    100% |████████████████████████████████| 7.3MB 200kB/s 
Requirement already satisfied: pytz in ./anaconda3/lib/python3.6/site-packages (from django) (2018.4)
Installing collected packages: django
Successfully installed django-2.1

2. Use Pip To Install Selenium Python Module.

192:~ $ pip install selenium
Collecting selenium
  Downloading https://files.pythonhosted.org/packages/b8/53/9cafbb616d20c7624ff31bcabd82e5cc9823206267664e68aa8acdde4629/selenium-3.14.0-py2.py3-none-any.whl (898kB)
    100% |████████████████████████████████| 901kB 714kB/s 
Requirement already satisfied: urllib3 in ./anaconda3/lib/python3.6/site-packages (from selenium) (1.22)
Installing collected packages: selenium
Successfully installed selenium-3.14.0

3. Create Django Project And Startup Django Web Server.

  1. Open a terminal and input below command in your working directory.
    $ django-admin.py startproject TodoList
  2. Run ls -l command, then you can find the directory TodoList under current working folder.
  3. CD into the TodoList folder, there is a folder also named TodoList and a file manage.py. The inside TodoList folder is the place where all this web server project files are saved, the manage.py file is the Django web server management file. The _pycache_ folder is the cache folder for all the project python source files.
    python django web project files structure new
  4. To startup the Django project web server, please run below command.
    192:TodoList $ python manage.py runserver
    Performing system checks...
    System check identified no issues (0 silenced).
    You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
    Run 'python manage.py migrate' to apply them.
    August 30, 2018 - 16:01:58
    Django version 2.1, using settings 'TodoList.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
  5. Now the Django web server has been created and started up, open a web browser and access url  http://127.0.0.1:8000/ to see the Django project welcome page.
    django web server peoject home page
READ :   WebDriver Event Listener : Take Screenshot On Exception

4. Run Selenium In Python Code To Test Above Django Server.

Now save below code in a file TestDjango.py and execute python TestDjango.py in a terminal, you can get error message in the console.

from selenium import webdriver
import time

def assert_django_title():

    # Create the Firefox web browser
    browser = webdriver.Firefox(executable_path = '/Users/zhaosong/Documents/WorkSpace/tool/geckodriver')

    # Access the Django web server home page.
    browser.get('http://127.0.0.1:8000/') 

    # Assert the web page title, the web page title do not contains Djangl so you can see error message in the console.
    assert 'Djangl' in browser.title

    # Sleep 10 seconds.
    time.sleep(10)

    # Close and quit the Firefox web browser
    browser.quit()

if __name__ == '__main__':
    assert_django_title()

5. Use Python Unittest Module To Test Django Home Page Title.

'''
Created on Sep 2, 2018
@author: zhaosong
'''

from selenium import webdriver
import time
import unittest

class DjangoTest(unittest.TestCase):

    # This method is invoked when test case start.
    def setUp(self):
        # Create the Firefox browser when test case setup.
        self.browser = webdriver.Firefox(executable_path = '/Users/zhaosong/Documents/WorkSpace/tool/geckodriver')

    # This method is invoked when test case complete.    
    def tearDown(self):
        # Close and quit the Firefox browser when test case tear down.
        self.browser.quit()

    # This is the test method.    
    def testHomePage(self):
        # Get Django home page.
        self.browser.get('http://127.0.0.1:8000/')
        # Sleep 10 seconds to wait for the page load.
        time.sleep(10)
        # Assert whether the web page title contains word Djangl or not.
        self.assertIn("Djangl", self.browser.title, 'Browser title do not contains Django')

if __name__ == '__main__':
    # Runn all test case function.
    unittest.main()

Run above python code will get below error message in console.

======================================================================
FAIL: testHomePage (__main__.DjangoTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/selenium/SeleniumDjangoExample.py", line 23, in testHomePage
    self.assertIn("Djangl", self.browser.title, 'Browser title do not contains Django')
AssertionError: 'Djangl' not found in 'Django: the Web framework for perfectionists with deadlines.' : Browser title do not contains Django
----------------------------------------------------------------------
Ran 1 test in 15.181s
FAILED (failures=1)

Reference

  1. Python 3 Unittest Html And Xml Report Example

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.