Data driven testing in Python Pytest using json

In pytest automation framework, we have tested many test cases manually now we will import data from external sources (CSV, Excell, JSON, YAML), and to do this we have to use DDT (data-driven testing) module. data-driven testing is a test automation framework used to store data. In this tutorial, we will use JSON data for testing.

Prerequisites

  • Python 3.6+ or pypy3
  • Install pytest — pip install pytest
  • Install ddt — pip install ddt

Data-Driven Testing Using JSON in Pytest

Create a test file with the name test_dd.py

  • Import necessary modules and define decorator @ddt
  • Define class Test_class and give unittest.Testcase as import parameter
  • In the class define function test_py_1() to print data from the JSON file
import pytest,unittest
from ddt import ddt, unpack, data
from readdata import getJSONData
@ddt
class Test_Class_1(unittest.TestCase):
    @data(*getJSONData("myjson.json"))
    def test_py_1(self,a):
        for x in a:
            print(x)

Create a JSON file with name data.json

{
  "toDoEdit":
  {
    "locator": "model",
    "value": "todoList.todoTest"
  },

  "addBtn":
  {
    "locator": "css",
    "value": "[value=\"add\"]"
  },

  "todoList":
  {
    "locator": "repeater",
    "value": "todo in todoList.todos"
  },

  "completedAmount":
  {
    "locator": "css",
    "value": ".done-true"
  }
}

Now write a Python module to read JSON data and name file as readdata.py

  • Import pandas module to read data from JSON file and append data to the empty list by defining getJSONData() function.
import  pandas as pd

def getJSONData(fileName):
    rows = []
    myJson=pd.read_json(fileName,orient="values")
    for row in myJson:
        rows.append(row)
    return rows

Run the test using the command py.test -v -s test_dd.py  in the terminal.

Output

As we have got the output all four test cases have passed successfully after executing the command. similarly, we can get data externally from other sources like Excell, CSV, YAML, etc for testing various test cases using pytest.

Thus, in this tutorial, we have learned how to perform data-driven testing using JSON data in pytest.