我有一个带过滤器的excel文件的导出功能。该文件下载正常,一些手动测试看起来不错。 我想编写单元测试来测试过滤器。为此,我用 openpyxl 读取了返回的文件。我得到了错误。
出口:
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
测试:
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
错误:
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)
编辑: 导出的文件似乎是问题所在。如果我尝试使用 openpyxl 手动打开导出的文件,我会得到同样的错误。 现在我在 LibreOffice 中打开导出并说“另存为”。它仍然是相同的文件类型和所有内容,但是如果我用 openpyxl 打开这个新文件,它就可以工作
我无法使用 openpyxl 进行测试,因为在导出中使用了 xlwt。现在我使用 xlrd 进行测试。
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)