0

我有一个读取 excel 文件并根据其内容生成报告的功能。如何在 pytest 中编写测试以检查文件是否生成并按预期创建报告?

import openpyxl

def create_report(file_path):
    #open an existing report
    xfile = openpyxl.load_workbook(file_path)
    
    sheet = xfile.get_sheet_by_name('Sheet1')
    sheet['A1'] = 'hello world'
    sheet['A3'] = 22
    sheet.cell(row=2, column=2).value = 2
    #Write data to excel sheet
    #save as new report
    xfile.save('test_report.xlsx')

测试涉及创建新文件以生成报告的功能时,最佳实践是什么?这个功能可以通过Mocking文件路径来测试吗?

4

1 回答 1

0

只需有一个用于从文件中读取数据的夹具,然后在您的测试中使用夹具,并测试数据。

但是,这取决于您要测试的确切内容,如果只是解析逻辑,或者您从该文件中查询数据的方式,您可以使用模拟数据(作为不同文件中的字符串),并节省时间和读取文件的不必要的依赖。

于 2021-01-26T05:11:10.203 回答