Data Driven Testing in Python

Data Driven test in Python

In this article, we are going to show the tips of using Data Driven Test (DDT) library in python.

We will explain why do we need DDT and give a sample code in python for web automation.

Why DDT?

Why do we need DDT? Image you would like to do google search testing with various input of search keyword.

The ideal case is that you write the automation scripts once and then read all the various search keyword from data or CSV.

It doesn’t matter if you have 100 or 1000 search keyword data set, you all need one set of automation script.

We don’t need to have 100 set of automation script. That’s the value of DDT (Data Driven Test)

 

DDT Python Library Installation

To achieve the DDT in python, we will need to install the DDT library. To install the DDT library, it can be installed by using python PIP.

 

pip   install   ddt

or download it from here.  https://pypi.python.org/pypi/ddt

 

Key Tips Annotation

There are three key definition for the uses of the DDT library in Python. listed below.

  • @ddt decorator: To define the test class
  • @data: Define the data-driven test methods.
  • @unpack decorator, unpacks tuples or lists into multiple arguments.

 

Python Sample Code

Testing Scenario

  • 1. Visit Google.
  • 2. Search keyword “selenium” as test case 1
  • 3. Search keyword “python” as test case 2

In this sample, we search the google with keyword “selenium” for test case 1. and then search “python” as test case 2.

 

[pastacode lang=”python” message=”Data Driven Testing in Python” highlight=”5,6,20,21,22″ provider=”manual”]

import unittest
from ddt import ddt, data, unpack
from selenium import webdriver


@ddt


class DDTSimpleTest(unittest.TestCase):
    def setUp(self):
        # create a new Firefox session
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()
        # navigate to the application home page
        self.driver.get("http://www.google.com/")



    # specify test data using @data decorator
    @data(("Selenium", 1), ("Python",2))
    @unpack


    def test_search(self, search_text, TestCase_ID):

        print " Search Text " + search_text
        print " Search TestCase ID " + str(TestCase_ID)

        # get the search textbox
        self.search_field = self.driver.find_element_by_name("q")
        self.search_field.clear()


        # enter search keyword and submit.
        # use search_text argument to input data
        self.search_field.send_keys(search_text)
        self.search_field.submit()



    def tearDown(self):
        # close the browser window
        self.driver.quit()

if __name__ == '__main__':
    unittest.main(verbosity=2)

[/pastacode]

Leave a Reply

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