The first step: Write Excel Operation method
excel_operate.py file
fromOpenpyxlImportLoad_workbook#Introducing ModulesclassMyexcel:def __init__(self,filepath,sheetname):#the initialization function is called when the object is instantiatedSELF.WB =Load_workbook (filepath) self.sh=Self.wb[sheetname]#reads the data for the specified cell defRead_data (self,row,column):returnSelf.sh.cell (row,column). Value#Read all data defread_alldate (self): forIndexinchRange (1,self.sh.max_row+1): Print('Line number:', index) forIinchRange (1,self.sh.max_column+1): Print('column number:'I'content:', Self.sh.cell (row=index,column=1). Value)#Write Data defWrite_data (self,row,column,content): Self.sh.cell (row,column). Value=content#Save Data defSave_data (Self,filepath): Self.wb.save (filepath)#Excel = Myexcel (' testdata.xlsx ', ' Sheet1 ')#Print (Excel.read_data (2,1))##excel.write_data (4,1, ' 12345678936 ')#excel.write_data (4,2, ' a1234567 ')#excel.save_data (' testdata.xlsx ')
Step Two: Write test cases
test_excel_operate.py file
ImportUnitTest fromExcel_operateImportMyexcelclassTestexcel (unittest. TestCase): @classmethoddefSetupClass (CLS): Cls.excel= Myexcel ('testdata.xlsx','Sheet1') #test Case Read defTest_read_data (self):Pass #Test Case Write defTest_write_data (self):#Call your Own Write methodSelf.excel.write_data (5, 1,'12345678937') Self.excel.write_data (5, 2,'a1234567') Self.excel.save_data ('testdata.xlsx')
Step three: Execute the test case and generate the HTML report
testsuite_excel.py file
ImportUnitTest fromHtmltestrunnernewImportHtmltestrunner fromTest_excel_operateImportTestexcelImport TimeImportOSif __name__=='__main__': S=UnitTest. TestSuite () s.addtests (unittest. Testloader (). Loadtestsfromtestcase (Testexcel)) now= Time.strftime ('%y%m%d_%h%m%s') filename= Open (OS.GETCWD () +'/excelunittestreport_'+ Now +'. html','WB') Runner=Htmltestrunner (Stream=filename, title='Excel Unit Test Report', Description='Excel Unit Test Report', Tester='Lixiaozhe') Runner.run (s)
Python Operation excel--Unit test