DataDriven testing in python

Driving test from a set of data is an integral art of any automation test suite. @DataProvider in TestNG is an example of feature that enables rotating data to the same test. But what's the analogy in python pytest ?
It is ddt
To get started, install ddt
cmd > pip install ddt 
My class without data driven tests looks like this:
import pytest,unittest

class Test_Class(unittest.TestCase):
    def test_py_1(self):        print("This is test 1")
        

Now import
from ddt import ddt,unpack,data
Now add the @ddt decorators above the class. Class decorator for subclasses of unittest.TestCase.
Apply this decorator to the test case class, and then decorate test methods with @data.
For each method decorated with @data, this will effectively create as many methods as data items are passed as parameters to @data.The names of the test methods follow the pattern original_test_name_{ordinal}_{data}. ordinal is the position of the data argument, starting with 1.
For data we use a string representation of the data value converted into a valid python identifier. If data.__name__ exists, we use that instead.For each method decorated with @file_data('test_data.json'), the decorator will try to load the test_data.json file located relative to the python file containing the method that is decorated. It will, for each test_name key create as many methods in the list of values from the data key.

So now the code with decorators looks like this:
import pytest,unittest
from ddt import ddt, unpack, data


@ddtclass Test_Class_1(unittest.TestCase):
    @data(("Ruby","Cucumber"), ("Python","Behave"))
    @unpack    def test_py_1(self, lang,fr):        print(lang+" "+fr)

    @data(("Rspec"),("behave"))
    def test_2(self, lang):        print(lang)

Output:








For cases with just one param, we do not nee unpack.

Keep glued for more articles on ddt

Comments

Post a Comment

Popular Posts