def test_export_queryset_empty(self): audits = Audit.objects.all().iterator() export = QuerysetExporter(queryset=audits, file_format="csv") export_file = export.do_export() export_file.seek(0) entries = [row for row in export_file.readlines()] assert entries[0] == "NO EXPORT DATA FOUND\n"
def test_export_format_excel(self, audits): export = QuerysetExporter(queryset=audits, file_format="xlsx") export_file = export.do_export() wb = load_workbook(filename=export_file.name) ws = wb.active entries = [item for item in ws.iter_rows()] assert len(entries) == 7 # 6 audits + header
def batched_export(audits): """CSV Exporter with a custom batch size""" QuerysetExporter.BATCH_SIZE = 2 def fake_writer(rows): assert len(rows) <= QuerysetExporter.BATCH_SIZE export = QuerysetExporter(queryset=audits, file_format="csv") export.writer.write_rows = fake_writer return export
def get(request, case_id, *args, **kwargs): """Get audit trail export for a case. Generates an export file in the desired format (if specified in `format` query param). Supported formats are specified in `QuerysetExport.FILE_FORMATS`. :param (HTTPRequest) request: request object. :param (str) case_id: case id to filter report on. :returns (HTTPResponse): Audit trail export file in requested format (if specified). Default is `xlsx`. """ file_format = request.query_params.get("format", "xlsx") audit_trail = Audit.objects.filter( case_id=case_id).order_by("created_at").iterator() export = QuerysetExporter(queryset=audit_trail, file_format=file_format, prefix="tr-audit-export") export_file = export.do_export(compatible=True) mime_type = mimetypes.guess_type(export_file.name, False)[0] response = HttpResponse(export_file.read(), content_type=mime_type) response[ "Content-Disposition"] = f"attachment; filename={export_file.name}" return response
def test_export_compatible(self, audits): export = QuerysetExporter(queryset=audits, file_format="csv") export_file = export.do_export(compatible=True) export_file.seek(0) entry = export_file.readline() assert entry.strip("\n") == ",".join(Audit.row_columns())
def test_export_queryset_invalid(self): # Use a QuerySet, not required GeneratorType audits = Audit.objects.all() with pytest.raises(ValueError) as e: QuerysetExporter(queryset=audits, file_format="xlsx") assert "queryset must be a generator" in str(e)
def test_export_format_csv(self, audits): export = QuerysetExporter(queryset=audits, file_format="csv") export_file = export.do_export() export_file.seek(0) entries = [row for row in export_file.readlines()] assert len(entries) == 7 # 6 audits + header
def test_export_format_unsupported(self): audits = Audit.objects.all().iterator() with pytest.raises(ValueError) as e: QuerysetExporter(queryset=audits, file_format="unsupported") assert "Unsupported export format: unsupported" in str(e)