Data driven testing in python

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:

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.

Читайте также:  JavaScript User defined object

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~

Читайте также:  Html textarea font size

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.

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

Hot Tags

  • Java — 7906
  • Database — 3176
  • Python — 3103
  • Attribute — 2963
  • Programming — 2938
  • Javascript — 2788
  • Spring — 2575
  • xml — 2270
  • Android — 2243
  • Linux — 2204
  • JSON — 2150
  • less — 2137
  • network — 2115
  • github — 2063
  • MySQL — 1760
  • SQL — 1616
  • PHP — 1559
  • encoding — 1360
  • Mobile — 1172
  • Apache — 1137

Источник

Writing tests for RESTful APIs in Python using requests – part 2: data driven tests

Recently, I’ve delivered my first ever three day ‘Python for testers’ training course. One of the topics that was covered in this course is writing tests for RESTful APIs using the Python requests library and the pytest unit testing framework.

In this short series of blog posts, I want to explore the Python requests library and how it can be used for writing tests for RESTful APIs. This is the second blog post in the series, in which we will cover writing data driven tests. The first blog post in the series can be found here.

About data driven testing
Before we get started, let’s quickly review what data driven tests are.

Often, when developing automated tests, you will find yourself wanting to test the same business logic, algorithm, computation or application flow multiple times with different input values and expected output values. Now, technically, you could achieve that by simply copying and pasting an existing test and changing the requires values.

From a maintainability perspective, however, that’s not a good idea. Instead, you might want to consider writing a data driven test: a test that gets its test data from a data source and iterates over the rows (or records) in that data source.

Читайте также:  Алгоритм умножения матриц python

Creating a test data object
Most unit testing frameworks provide support for data driven testing, and pytest is no exception. Before we see how to create a data driven test in Python, let’s create our test data source first. In Python, this can be as easy as creating a list of tuples, where each tuple in the list corresponds to an iteration of the data driven test (a ‘test case’, if you will).

passing data driven test

To use this test data in our test, we need to write a Python method that reads the data from the file and returns it in a format that’s compatible with the pytest parametrize marker. Python offers solid support for handling .csv files in the built-in csv library:

import csv def read_test_data_from_csv(): test_data = [] with open("test_data/test_data_zip_codes.csv", newline="") as csvfile: data = csv.reader(csvfile, delimiter=",") next(data) # skip header row for row in data: test_data.append(row) return test_data

This method opens the .csv file in reading mode, skips the header row, adds all other lines to the list of test data values test_data one by one and returns the test data object.

The test method itself now needs to be updated to not use the hardcoded test data object anymore, but instead use the return value of the method that reads the data from the .csv file:

@pytest.mark.parametrize("country_code, zip_code, expected_place_name", read_test_data_from_csv()) def test_using_csv_get_location_data_check_place_name(country_code, zip_code, expected_place_name): response = requests.get(f"http://api.zippopotam.us/country_code>/zip_code>") response_body = response.json() assert response_body["places"][0]["place name"] == expected_place_name

Running this updated test code will show that this approach, too, results in three passing test iterations. Of course, you can use test data sources other than .csv too, such as database query results or XML or JSON files. As long as you’re able to write a method that returns a list of test data value tuples, you should be good to go.

In the next blog post, we’re going to further explore working with JSON and XML in API request and response bodies.

Using the examples for yourself
The code examples I have used in this blog post can be found on my GitHub page. If you download the project and (given you have installed Python properly) run

pip install -r requirements.txt

from the root of the python-requests project to install the required libraries, you should be able to run the tests for yourself. See you next time!

Источник

Оцените статью