Creating a data-driven test in Python using DDT

Python is also a widely used language for building Selenium WebDriver tests. It offers various ways to parameterize tests.

In this recipe, we will use the DDT module along with unittest to create a parameterized test.

Getting ready

You need to install the DDT module by using the following command:

pip install ddt

This command will download and install all the dependencies required for DDT on your machine.

How to do it...

Let's create a simple Python test for parameterization using the DDT module. Create a new Python file named bmi_calc_ddt.py using the following code:

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

@ddt
class BmiCalcDDT(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 BMI Calculator page
        self.driver.get("http://bit.ly/1zdNrFZ")

    # specify test data using @data decorator
    @data(("160", "45", "17.6", "Underweight"),
          ("168", "70", "24.8", "Normal"),
          ("181", "89", "27.2", "Overweight"))
    @unpack
    def test_bmi_calc(self, height, weight, bmi, category):
        driver = self.driver

        height_field = driver.find_element_by_name("heightCMS")
        height_field.clear()
        height_field.send_keys(height)

        weight_field = driver.find_element_by_name("weightKg")
        weight_field.clear()
        weight_field.send_keys(weight)

        calculate_button = driver.find_element_by_id("Calculate")
        calculate_button.click()

        bmi_label = driver.find_element_by_name("bmi")
        bmi_category_label = driver.find_element_by_name("bmi_category")

        self.assertEqual(bmi, bmi_label.get_attribute("value"))
        self.assertEqual(category, bmi_category_label.get_attribute("value"))

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

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

How it works...

The DDT module is an extension for the Python unittest library. We can use this module to parameterize unit tests in Python. We need to add a special decorator @ddt to parameterize the test class:

@ddt
class BmiCalcDDT(unittest.TestCase):

Next, we need to describe the test data above the test method using the @data decorator:

    # specify test data using @data decorator
    @data(("160", "45", "17.6", "Underweight"),
          ("168", "70", "24.8", "Normal"),
          ("181", "89", "27.2", "Overweight"))
    @unpack

When we execute this test, Python will read the data tuples and pass each row to the test.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.236