Data-driven testing of Python Selenium

Source: Internet
Author: User
Tags unpack

  The test benefits of data-driven mode are obvious compared to normal mode testing! Using a data-driven pattern, you can test data based on business decomposition by simply defining variables, using external or custom data to parameterize them, and avoiding the use of fixed data in previous test scripts. You can separate test scripts from test data so that test scripts are highly reusable under different sets of data. It can not only increase the test coverage of complex condition scenarios, but also greatly reduce the writing and maintenance of test scripts.

The following will use the data-driven mode (DDT) library under Python to create a test of Baidu search in a 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.

For more information on DDT, 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 adorner on the test class and the @data adorner on the test method. @data Decorator treats parameters as test data, parameters can be single values, lists, tuples, dictionaries. For lists, tuples and lists need to be parsed into multiple parameters with the @unpack adorner.

The following implementation of Baidu search testing, the introduction of search keywords and expected results, the code is as follows:

ImportUnitTest fromSeleniumImportWebdriver fromDdtImportDDT, data, UNPACK@DDTclassSEARCHDDT (unittest. TestCase):" "docstring for SEARCHDDT" "    defsetUp (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')) @unpackdefTest_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)defTearDown (self): Self.driver.quit ()if __name__=='__main__': Unittest.main (verbosity=2)

In the Test_search () method, the Search_value and expected_result two parameters are used to receive the data that the tuple resolves. When the script is run, DDT converts the test data to a valid Python identifier, generating a test method with a name that is more meaningful. The results are as follows:

Data-driven testing using external data

  If the required test data, such as a text file, spreadsheet, or database, is already present externally, DDT can be used to directly retrieve the data and pass the test method.

DDT is implemented using external CSV (comma-separated value) files and excle tabular data.

Get data from CSV

  Ibid. The @data decorator uses the parse external CSV (TESTDATA.CSV) as the test data (instead of the previous test data). The data are as follows:

  

Next, you'll create a get_data () method that includes the path (which uses the current path 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 Baidu search, the code is as follows:

Importcsv, UnitTest fromSeleniumImportWebdriver fromDdtImportDDT, data, unpackdefGet_data (file_name):#Create an empty list to store rowsrows = []    #Open the CSV filedata_file = open (file_name,"R")    #Create a CSV Reader from CSV fileReader =Csv.reader (data_file)#Skip the HeadersNext (reader, None)#add rows from reader to list     forRowinchreader:rows.append (Row)returnROWS@DDTclassSEARCHCSVDDT (unittest. TestCase):defsetUp (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')) @unpackdefTest_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)defTearDown (self): Self.driver.quit ()if __name__=='__main__': Unittest.main (verbosity=2)

When the test executes, the @data calls the Get_data () method to read the external data file and returns the data to @data line by row. The results of the implementation also ibid.

Getting data from Excel

Test data are often stored in tests using Excle, as in the same can be used to parse the external CSV (TESTDATA.CSV) as test data (instead of the previous test data) using the @data decorator. The data are as follows:

  

Next, you'll create a get_data () method that includes the path (which uses the current path 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 testing Baidu search, the code is as follows:

Importxlrd, UnitTest fromSeleniumImportWebdriver fromDdtImportDDT, data, unpackdefGet_data (file_name):#Create an empty list to store rowsrows = []    #Open the CSV fileBook =Xlrd.open_workbook (file_name)#get the frist sheetSheet =book.sheet_by_index (0)#iterate through the sheet and get data from rows in list     forRow_idxinchRange (1, sheet.nrows):#Iterate 1 to MaxRowsrows.append (List (sheet.row_values (row_idx, 0, Sheet.ncols) )returnROWS@DDTclassSEARCHEXCLEDDT (unittest. TestCase):defsetUp (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')) @unpackdefTest_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)defTearDown (self): Self.driver.quit ()if __name__=='__main__': Unittest.main (verbosity=2)

As with the CVS file read above, when the test executes, the @data calls the Get_data () method to read the external data file and returns the data to @data line by row. The results of the implementation also ibid.

If you want to get data from a database's library table, you also need a Get_data () method, and a DB-related library to connect to the database, SQL query to get the test data.

Data-driven testing of Python Selenium

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.