Implementation of data-driven testing in Python Selenium

The benefits of data-driven mode testing are obvious compared to normal mode testing! Using the data-driven model, you can decompose test data according to the business. You only need to define variables and use external or custom data to make it parameterized, thus avoiding the use of fixed data in the previous test script. The test script can be separated from the test data, so that the test script is highly reused under different data sets. Not only can it increase the test coverage of complex conditions, it can also greatly reduce the writing and maintenance of test scripts.

The following will use the data-driven mode (ddt) library under Python, combined with the unittest library to create a Baidu search test in a data-driven mode.

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

You can download and install it through the pip command that comes with python: pip install ddt. For more information about ddt, please refer to:

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

A simple data-driven test

In order 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. Parameters can be single values, lists, tuples, and dictionaries. For lists, you need to use the @unpack decorator to parse tuples and lists into multiple parameters.

The following is to implement Baidu search test, input 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 the test_search() method, two parameters, search_value and expected_result, are used to receive tuple parsed data. When the script is run, ddt converts the test data into a valid python identifier, and generates a more meaningful test method 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 directly obtain the data and pass it to the test method for testing.

The following will implement ddt with the help of external CSV (comma separated value) files and EXCLE table data.

Get data via CSV

As above, the @data decorator uses the parsed external CSV (testdata.csv) as the test data (instead of the previous test data). The data are as follows:

Next, first create a get_data() method, which includes the path (here 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 Baidu search, the code is 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 is executed, @data will call the get_data() method to read the external data file and return the data to @data line by line. The results of the implementation are also the same as above~
If you exchange experience in software testing, interface testing, automated testing, and interviews. If you are interested, you can add software test communication: 1085991341, and there will be technical exchanges with colleagues.

Get data through Excel

Excle is often used to store test data during testing. As above, the @data decorator can also be used to parse external CSV (testdata.csv) as test data (instead of previous test data). The data are as follows:

Next, we must first create a get_data() method, which includes the path (here 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 Baidu search, the code is 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 the CVS file read above, when the test is executed, @data will call the get_data() method to read the external data file and return the data to @data line by line. The results of the execution are the same as above~

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

The above is the whole content of this article, I hope it will be helpful to everyone's study. Friends who have been helped are welcome to like and comment.

Guess you like

Origin blog.csdn.net/Chaqian/article/details/106524512