Implementation of Data Driven Testing for Python Selenium

The benefits of data-driven mode testing are obvious compared to those of normal mode testing.Using a data-driven model, test data can be decomposed based on business by defining variables and parameterizing them with external or custom data, avoiding the use of fixed data from previous test scripts.Test scripts can be separated from test data, allowing them to be highly reused across different data collections.It not only increases test coverage for complex condition scenarios, but also greatly reduces the writing and maintenance of test scripts.

Below you will use the data-driven mode (ddt) Library under Python to create a test of Baidu Search in data-driven mode with the unittest library.

The ddt library contains a set of classes and methods for implementing data-driven testing.Variables in the test can be parameterized.

You can download and install it from the pip command that comes with python: pip install ddt.More information about DDT can be referenced:

https://pypi.org/project/ddt/

A simple data-driven test

To create a data-driven test, you need to use the @ddt decorator on the test class and the @data decorator on the test method.The @data decorator treats parameters as test data, which can be single values, lists, tuples, dictionaries.For lists, you need to parse tuples and lists into multiple parameters using the @unpack decorator.

Below the implementation of Baidu search test, incoming search keywords and expected results, the code is as follows:

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

@ddt
class SearchDDT(unittest.TestCase):
  '''docstring for SearchDDT'''
  def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.implicitly_wait(30)
    self.driver.maximize_window()
    self.driver.get("https://www.baidu.com")

  # specify test data using @data decorator
  @data(('python', 'PyPI'))
  @unpack
  def test_search(self, search_value, expected_result):
    search_text = self.driver.find_element_by_id('kw')
    search_text.clear()
    search_text.send_keys(search_value)

    search_button = self.driver.find_element_by_id('su')
    search_button.click()

    tag = self.driver.find_element_by_link_text("PyPI").text
    self.assertEqual(expected_result, tag)

  def tearDown(self):
    self.driver.quit()

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

In test_In the search() method, search_value and expected_The result two parameters are used to receive tuple parsed data.When running the script, ddt converts the test data into a valid python identifier to generate a test method with a more meaningful name.The results are as follows:

Data-driven testing using external data

If the required test data already exists externally, such as a text file, spreadsheet, or database, you can also use ddt to get the data directly and pass it into the test method for testing.

The ddt is implemented using external CSV (comma-separated values) files and EXCLE table data.

Getting data through CSV

Same as using Resolve External CSV in the @data decorator (Testdata.csvAs test data (instead of previous test data).The data are as follows:

Next, create a get_The data () method, which includes the path (where the current path is used by default), and the CSV file name.Call the CSV library to read the file and return a row of data.Then use @ddt and @data to implement external data-driven test of Baidu search, code as follows:

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

def get_data(file_name):
  # create an empty list to store rows
  rows = []
  # open the CSV file
  data_file = open(file_name, "r")
  # create a CSV Reader from CSV file
  reader = csv.reader(data_file)
  # skip the headers
  next(reader, None)
  # add rows from reader to list
  for row in reader:
    rows.append(row)
  return rows

@ddt
class SearchCSVDDT(unittest.TestCase):
  def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.implicitly_wait(30)
    self.driver.maximize_window()
    self.driver.get("https://www.baidu.com")

  # get test data from specified csv file by using the get_data funcion
  @data(*get_data('testdata.csv'))
  @unpack
  def test_search(self, search_value, expected_result):
    search_text = self.driver.find_element_by_id('kw')
    search_text.clear()
    search_text.send_keys(search_value)

    search_button = self.driver.find_element_by_id('su')
    search_button.click()

    tag = self.driver.find_element_by_link_text("PyPI").text
    self.assertEqual(expected_result, tag)

  def tearDown(self):
    self.driver.quit()

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

When the test executes, @data will call get_The data () method reads an external data file and returns the data row by row to @data.The result of execution is the same as above~
If you have experience in software testing, interface testing, automated testing, and interviews.Interested in software testing and communication: 1085991341, there will be peer technical exchanges.

Get data from Excel

Excle is often used to store test data in tests, as is the case with the @data decorator for resolving external CSV s.Testdata.csvAs test data (instead of previous test data).The data are as follows:

Next, create a get_The data () method, which includes the path (where the current path is used by default), and the EXCEL file name.Call the xlrd library to read the file and return the data.Then use @ddt and @data to implement external data-driven test of Baidu search, code as follows:

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

def get_data(file_name):
  # create an empty list to store rows
  rows = []
  # open the CSV file
  book = xlrd.open_workbook(file_name)
  # get the frist sheet
  sheet = book.sheet_by_index(0)
  # iterate through the sheet and get data from rows in list
  for row_idx in range(1, sheet.nrows): #iterate 1 to maxrows
    rows.append(list(sheet.row_values(row_idx, 0, sheet.ncols)))
  return rows

@ddt
class SearchEXCLEDDT(unittest.TestCase):
  def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.implicitly_wait(30)
    self.driver.maximize_window()
    self.driver.get("https://www.baidu.com")

  # get test data from specified excle spreadsheet by using the get_data funcion
  @data(*get_data('TestData.xlsx'))
  @unpack
  def test_search(self, search_value, expected_result):
    search_text = self.driver.find_element_by_id('kw')
    search_text.clear()
    search_text.send_keys(search_value)

    search_button = self.driver.find_element_by_id('su')
    search_button.click()

    tag = self.driver.find_element_by_link_text("PyPI").text
    self.assertEqual(expected_result, tag)

  def tearDown(self):
    self.driver.quit()

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

As with reading the CVS file above, @data will call get_when the test executesThe data () method reads an external data file and returns the data row by row to @data.The result of execution is the same as above~

If you want to get data from database tables, you also need a get_The data () method, and the DB-related libraries to connect to the database, SQL queries to obtain test data.

This is the whole content of this article, and I hope it will be helpful for everyone to learn.Welcome to comment and compliment from helped friends.

Tags: Programming Python Selenium Database pip

Posted on Wed, 03 Jun 2020 22:32:15 -0400 by dcgamers