Python data-driven-DDT

Source: Internet
Author: User
Tags unpack

Directory

[TOC]

First, data-driven introduction

Data-driven, my understanding, the simple point is that the data test data parameterization.

Ii. Basic use of DDT Introduction 2.0 test base class
classTest:def __init__( Self, A, B): Self. A=A Self. b=BdefAdd Self):return  Self. A+  Self. bdefSub Self):return  Self. A-  Self. bdefMulti Self):return  Self. A*  Self. bdefDiv Self):return  Self. A/  Self. b
2.1 Use steps
    1. Guide Package

      fromimport ddt, data, unpack
    2. Use of DDT

2.1 DDT reads single data

Not many applications in this way

2.2.1 Case
@ddtclass TestExample0428(unittest.TestCase):    def setUp(self):        pass    @data(123)    def test_add(self***kwargs):        print(*args)

Print 3 times, 1, 2, 3, respectively

2.2 DDT reading data from a combination (@unpack)

This approach is a more common way to enable parameterization of multi-parameter use cases

2.2.1 Plus Unpack
@ddtclass TestExample0428(unittest.TestCase):    def setUp(self):        pass            @data((123), (235), (111))    @unpack    def test_dict(self***kwargs):        print("开始打印数据")        # print(*args, **kwargs)        print(*args)

Print results

开始打印数据123开始打印数据235开始打印数据111
2.2.2 Don't add unpack
@ddtclass TestExample0428(unittest.TestCase):    def setUp(self):        pass            @data((123), (235), (111))    def test_dict(self***kwargs):        print("开始打印数据")        # print(*args, **kwargs)        print(*args)

Print results

开始打印数据(123)开始打印数据(235)开始打印数据(111)
2.3 Reading Dictionaries
@ddtclass TestExample0428(unittest.TestCase):    def setUp(self):        pass            @data({"name":"gupan""length":"170cm"}, {"age":"12"})    def test_dict(self***kwargs):        print("开始打印数据")        print(***kwargs)

Print results

开始打印数据{‘name‘‘gupan‘‘length‘‘170cm‘}开始打印数据{‘age‘‘12‘}
Third, DDT and Excel combine 3.1 Excel parsing class notation
#-*-Coding:utf-8-*-# __author__ = ' Gupan ' fromConfigImportSettingsImportOsImportSys fromSrc.utilsImportUtilsImportXlrdImportTracebackclassExcelparse:"""Excel parsing classesself.file_path: Test data storage Pathself.workbook: Open an Excel objectself.sheet_obj: Open Form Objectself.nrows: Number of rows with data in the formself.ncols: Number of columns with data in the form__init__ (Self, file_path):Aquire_cell_data (self, Row, col): Gets the data of a cell, does not need-1heads (Self, *args, **kwargs): Get test Data HeaderAquire_methodname_col (self): Gets the test method nameAquire_each_col_type (self): Gets the data type of each data columndatas (self, *args, **kwargs): Gets all the test data, stored by dictionary according to the method name    """    def __init__( Self, File_path):" ":p Aram File_path: Test data storage Path" "         Self. file_path=File_pathif  notOs.path.exists ( Self. File_path): Utils.print_log_error ( Self. file_path+ "does not exist, please confirm the path!!!!! ") Sys.exit (1)Try: Self. workbook=Xlrd.open_workbook ( Self. File_path)except Exception  asErr:utils.print_log_error ("file should be in XLS format data\ n") Utils.print_log_error (Traceback.format_exc ())RaiseErr# Only one form is stored in the default Excel table, and you only need to get the first one.         Self. sheet_obj=  Self. Workbook.sheets () [0]# Get the number of table lines         Self. nrows=  Self. sheet_obj.nrows# Get the number of forms in a single row         Self. ncols=  Self. sheet_obj.ncolsif  Self. nrows== 1 or  Self. ncols== 0: Utils.print_log_error (File_path+ "The form is empty, please fill in the test data!!!!! ") Sys.exit (1)defAquire_cell_data ( Self, Row, col):" "Get Cell data:p Aram Row: The number of rows in the cell (do not have to be active-1):p Aram Col: The number of columns in the cell (do not have to be active-1): Return: The cell data (str type)" "        return  Self. Sheet_obj.cell_value (Row- 1, col- 1)defHeads Self,*Args**Kwargs):" "Get table Header:p Aram args::p Aram Kwargs:: Return: Table header list" "Heads_info=[] forColinch Range(0, Self. Ncols): Heads_info.append ( Self. Sheet_obj.cell_value (0, col))returnHeads_infodefAquire_methodname_col ( Self):" "gets the number of columns that the test method name lock occupies: Return: Test method name Storage path" "Heads=  Self. Heads ()Try: IDX=Heads.index (SETTINGS.METHOD_DESC)except Indexerror  asErr:utils.print_log_error ( Self. file_path+"does not exist in "+Settings.method_desc+ '\ n') Utils.print_log_error (Traceback.format_exc ())RaiseErrreturnIdxdefAquire_each_col_type ( Self):" "gets the number of columns that the test method name lock occupies: Return: Gets the data type of each data column, returned as a list" "Col_type_desc_list=[] forColinch Range(0, Self. Ncols): Col_type_desc_list.append ( Self. Sheet_obj.cell_value (Settings.desc_type_row- 1, col))returnCol_type_desc_listdefDatas Self,*Args**Kwargs):" "gets the test data, returned by the dictionary according to the test method name:p Aram args::p Aram Kwargs:: Return: The test data in the dictionary format, the key value for each test method name is a list form" "Test_datas={}# test data start data column CountData_begin_col=Settings.data_begin_col- 1        # Gets the number of test start data rowsData_begin_row=Settings.data_begin_row- 1        # Get a list of data types corresponding to each column of dataType_list=  Self. Aquire_each_col_type ()# Test the number of columns in the test method nameMethod_col=  Self. Aquire_methodname_col ()# Initialize test method namePre_method_name=  Self. Sheet_obj.cell_value (Data_begin_row, Method_col)# Store test data for a methodMethod_datas=[] Method_count= 0        # table Header no test data, remove table header         forRowinch Range(Settings.data_begin_row- 1, Self. nrows): Row_data=[] Cur_method_name=  Self. Sheet_obj.cell_value (Row, Method_col)# start getting data             forColinch Range(Data_begin_col, Self. Ncols): Type_desc=Type_list[col] Cell_data=  Self. Sheet_obj.cell_value (Row, col) cell_data=Utils.type_switch (Cell_data, Type_desc) row_data.append (cell_data)ifPre_method_name==Cur_method_name:method_datas.append (Row_data) method_count+= 1            Else: Test_datas[pre_method_name]=Method_datas.copy ()# After the test method is changed, the test data pre-condition is emptiedMethod_datas.clear () Method_count= 0Pre_method_name=Cur_method_name Method_datas.append (Row_data)# No 0 means some data is not added        ifMethod_count!= 0: Test_datas[pre_method_name]=Method_datasreturnTest_datas
3.2 DDT and Excel combined case
@ddtclassTestExample0428 (unittest. TestCase):defSetUp ( Self):Pass    @data(*test_datas[' Test_add '])@unpack    defTest_add ( Self,*Args**Kwargs): P1, P2, value=Args result=Test (P1, p2). Add ()Try: Self. Assertequal (result, value,"Addition error, please reenter") Utils.print_log_info ("addition Test succeeded")except Assertionerror  asErr:err_str=Traceback.format_exc () utils.print_log_error (ERR_STR)RaiseErr

Test results

test_add_1__2__2__4_ (src.test.case.testExample.TestExample0428) ... 加法测试成功ok加法测试成功test_add_2__2__2__4_ (src.test.case.testExample.TestExample0428) ... ok加法测试成功test_add_3__3__3__6_ (src.test.case.testExample.TestExample0428) ... ok加法测试成功test_add_4__4__4__8_ (src.test.case.testExample.TestExample0428) ... oktest_dict (src.test.case.testExample.TestExample0428) ... oktest_div (src.test.case.testExample.TestExample0428) ... oktest_multi (src.test.case.testExample.TestExample0428) ... oktest_sub (src.test.case.testExample.TestExample0428) ... ok

Python data-driven-DDT

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.