Implementation of data-driven testing in Python Selenium!

The benefits of testing in data-driven mode are obvious compared to testing in normal mode! Using the data-driven model, the test data can be decomposed according to the business, just define variables, and use external or custom data to parameterize them, thus avoiding the use of fixed data in previous test scripts. Test scripts can be separated from test data, making test scripts highly reusable under different data sets. Not only can it increase the test coverage of complex condition scenarios, but it can also greatly reduce the writing and maintenance work of test scripts.

Next, we will use the data-driven mode (ddt) library under Python and combine it with the unittest library to create a test for Baidu search in data-driven mode.

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

You can download and install it through the pip command that comes with python: pip install 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, or dictionaries. For lists, you need to use the @unpack decorator to parse tuples and lists into multiple parameters.

The following implements the Baidu search test, passing in 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, the two parameters search_value and expected_result are used to receive tuple parsed data. When running the script, ddt converts the test data into valid Python identifiers, generating test methods with more meaningful names. The result is 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 in the test method for testing.

Below we will implement ddt with the help of external CSV (comma separated values) files and EXCLE table data.

Get data through CSV
As above, use the @data decorator to parse the external CSV (testdata.csv) as the test data (replacing the previous test data). The data is as follows:

Next, you must first create a get_data() method, which includes the path (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 testing of 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 execution results are 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 testing communication: 1085991341, and there will also be technical exchanges with peers.

Get data through Excel
Excel is often used to store test data during testing. As above, you can also use the @data decorator to parse external CSV (testdata.csv) as test data. (Replacing previous test data). The data is as follows:

Next, you must first create a get_data() method, which includes the path (the current path is used by default here) 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 testing of 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)

Just like reading the CVS file 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 execution result is the same as above~

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

The above is the entire 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.

Summarize:

Thank you to everyone who reads my article carefully! ! !

As someone who has experienced it, I also hope that everyone will avoid some detours. If you don’t want to experience the feeling of not being able to find information, no one to answer questions, and giving up after persisting for a few days while studying, here I will share with you some learning about automated testing. Resources, I hope they can help you on your way forward

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are from the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

 

Guess you like

Origin blog.csdn.net/2301_79535733/article/details/134981033
Recommended