我有一个带过滤器的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它的作品
1条答案
按热度按时间cgh8pdjw1#
我不能使用openpyxl进行测试,因为在导出中使用了xlwt。现在我使用xlrd进行测试。