0

I have a function that reads an excel file and generates a report based on its content. How do I write a test in pytest to check if the file is generated and the report is created as expected?

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')

What is the best practice when testing functions that involves creating a new file for generating a report? Can this function be tested by Mocking the file path?

user2077648
  • 951
  • 7
  • 27
  • 42
  • You can add a `report_path` argument to the function and, in your test, create a temporary directory, pass the path to that directory and delete it after the test. This would be also helpful as the report filename would no longer be hardcoded. – warownia1 Jan 24 '21 at 20:36
  • @warownia1 can we read and write to the excel files without even opening the real ones using mock function? – user2077648 Jan 25 '21 at 02:41
  • You should be able to load and save from and to streams instead of file names. Change your function signature to `create_report(input_file, output_file='test_report.xlsx')`. Your program will be able to use it as before, providing input file path only, but tests will pass two in-memory buffers. – warownia1 Jan 25 '21 at 16:02
  • @warownia1 is it possible to mock the input_file which is an excel file instead of loading the original file? – user2077648 Jan 26 '21 at 16:15

1 Answers1

0

just have a fixture for reading the data from the file, and then use the fixture in your test, and test the data.

however, it depends on what exactly you want to test, if it is just the parsing logic, or the way you query data from this file, you can use mock data (as a string in a different file), and save the time and the unnecessary dependency of reading the file.

Tomer Cohen
  • 222
  • 1
  • 6
  • Is reading data from the original file considered as a good practice during testing? – user2077648 Jan 26 '21 at 16:17
  • Yes, reading and writing to files during tests is a common practice. You can have separate input files dedicated for tests. Just remember to delete any files created during the test after it's done. Ideally create them in some temporary directory. `tempfile` module is often helpful in such case. – warownia1 Jan 27 '21 at 13:58