-1

I have an export function for excel files with filters. The file downloads normaly and some manual tests looked fine. I wanted to write unittests to test the filter. For this I read the returned file with openpyxl. There I get the error.

export:

class DeviceExport(APIView):
    def get(self, request):
    response = HttpResponse(content_type="application/vnd.ms-excel")
    response["Content-Disposition"] = 'attachment; filename="device_export.xlsx"'
    wb = xlwt.Workbook(encoding="utf-8")
    ws = wb.add_sheet("device")

    # write data
    
    wb.save(response)
    return response

test:

class DeviceExportTest(TestCase):
    def setUp(self):
        # some set up

    def test_filter(self):
        self.c.login(username="testuser", password="password")
        mommy.make("app.Device", name="name", serial_number=123)        #should be in export
        mommy.make("app.Device", name="name", serial_number=132)        #shouldnt be in export
        data = {'filter': '{"name": "name", "serial_number": "123"}'}
        response = self.c.get(reverse('app:export_device'), data)
        wb = load_workbook(filename=BytesIO(response.content))          #error here
        ws = wb.worksheets[0].active
        row_count = ws.max_row

error:

export with filter ... ERROR

======================================================================
ERROR: test_filter (app.tests.test_device.DeviceExportTest)
export with filter
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/.../app/tests/test_device.py", line 1067, in test_filter
    wb = load_workbook(filename=BytesIO(response.content))
  File "/.../lib/python3.8/site-packages/openpyxl/reader/excel.py", line 315, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "/.../lib/python3.8/site-packages/openpyxl/reader/excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "/.../lib/python3.8/site-packages/openpyxl/reader/excel.py", line 96, in _validate_archive
    archive = ZipFile(filename, 'r')
  File "/.../python3.8/zipfile.py", line 1269, in __init__
    self._RealGetContents()
  File "/.../python3.8/zipfile.py", line 1336, in _RealGetContents
    raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file

----------------------------------------------------------------------
Ran 1 test in 12.967s

FAILED (errors=1)

Edit: The exported file seems to be the problem. If I try to manualy open the exported file with openpyxl I get the same error. Now I open the export in LibreOffice and say "save as". Its still the same file type and everything but if I open this new file with openpyxl it works

1 Answers1

0

I couldnt use openpyxl for the test because in the export xlwt was used. Now I use xlrd for my test.

wb = xlrd.open_workbook(file_contents=response.content)
ws = wb.sheet_by_index(0)
self.assertEqual(response.status_code, 200)
self.assertEqual(ws.nrows, 4)