Selenium Test case using Data Driven Testing in Python

Reading Time: 2 minutes

In data-driven testing approach, we can use a single test to verify different sets of test cases or test data by driving the test with input and expected values from an external data source instead of using the hard coded values every time a test is run. Its very useful when we have similar tests that consist of the same steps but differ in the input data and expected value or the application state.

We need to install DDT in python to work with Data driven Testing

Installing ddt
We can download and install ddt using the following command line:

pip install ddt[/code]

Assuming that you have unittest,selenium and nose installed. If not go here.

Steps to Create the DDT using unittest , nose with external data sources(Excel):
1.  Use the @ddt decorator for the test class.
2.  Use the @data decorator on the data-driven test methods.
3.  Use the @unpack decorator, which unpacks tuples or lists into multiple arguments.

Project Structure:

Importing ddt in the  test

from ddt import ddt, data, unpack[/code]

Lets write code for the Searching a Text on the “” site and getting expected results. I have written a search test, which accepts a pair of arguments for different search value and expected value.


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

def getData(fileName):
     myrows = []
     book = xlrd.open_workbook(fileName)
     sheet = book.sheet_by_index(0)
     for row_index in range(1, sheet.nrows):
         myrows.append(list(sheet.row_values(row_index, 0, sheet.ncols)))
     return myrows

class SearchResultDDT(unittest.TestCase):
     def setUpClass(cls):
         cls.driver = webdriver.Firefox()

     def test_SearchResults(self, search_values, expected_value):
         self.driver.get("<a href="">")</a>
         self.search_field = self.driver.find_element_by_name("q")
         products = self.driver.find_elements_by_xpath("//h2[@class=’product-name’]/a")
         if expected_value > 0:
             self.assertEqual(expected_value, len(products))
             msg = self.driver.find_element_by_class_name("note-msg")
             self.assertEqual("Your search returns no results.", msg.text)

def tearDownClass(cls):

if __name__=="__main__":


Running the test case with Nose

DDT will generate new test methods giving them meaningful names by converting the data values to valid Python identifier.
Final Code Here

2 thoughts on “Selenium Test case using Data Driven Testing in Python”

Leave a Comment

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