test_pl_vehicle_recharge_apply_zip_export.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import io
  2. import zipfile
  3. from openpyxl import load_workbook
  4. from app.services.export_attachment_zip import (
  5. build_attachment_zip_bytes,
  6. urls_to_attachment_items,
  7. )
  8. from app.utils.excel_export import ExportColumn
  9. def test_urls_to_attachment_items():
  10. items = urls_to_attachment_items("https://a/1.jpg,https://a/2.pdf")
  11. assert items == [
  12. {"url": "https://a/1.jpg", "label": "附件1"},
  13. {"url": "https://a/2.pdf", "label": "附件2"},
  14. ]
  15. def test_recharge_apply_zip_structure_and_hyperlink():
  16. columns = [
  17. ExportColumn(title="申请单号", field="applyNo"),
  18. ExportColumn(title="车牌号", field="licensePlate"),
  19. ]
  20. rows = [
  21. {
  22. "id": "r1",
  23. "rowNo": 1,
  24. "applyNo": "RA001",
  25. "licensePlate": "陕A12345",
  26. }
  27. ]
  28. attachments_by_id = {
  29. "r1": urls_to_attachment_items("https://cdn.example/a.jpg,https://cdn.example/b.pdf"),
  30. }
  31. def fake_download(url: str) -> bytes:
  32. return b"fake-bytes"
  33. stamp = "202609270900"
  34. data, failures = build_attachment_zip_bytes(
  35. db=None,
  36. tenant_no="t1",
  37. columns=columns,
  38. rows=rows,
  39. attachments_by_id=attachments_by_id,
  40. stamp=stamp,
  41. package_label="充值申请",
  42. id_field="id",
  43. sheet_title="充值申请",
  44. xlsx_basename="(总表)充值申请.xlsx",
  45. download_fn=fake_download,
  46. )
  47. assert failures == []
  48. with zipfile.ZipFile(io.BytesIO(data)) as zf:
  49. names = zf.namelist()
  50. assert f"充值申请({stamp})/(总表)充值申请.xlsx" in names
  51. att = [n for n in names if n.startswith(f"充值申请({stamp})/附件/")]
  52. assert len(att) == 2
  53. assert any("01_附件1_" in n for n in att)
  54. assert any("01_附件2_" in n for n in att)
  55. xlsx_bytes = zf.read(f"充值申请({stamp})/(总表)充值申请.xlsx")
  56. wb = load_workbook(io.BytesIO(xlsx_bytes))
  57. ws = wb.active
  58. headers = [c.value for c in ws[1]]
  59. assert "附件_1" in headers
  60. assert "附件_2" in headers
  61. attach_col = headers.index("附件_1") + 1
  62. assert str(ws.cell(2, attach_col).value).startswith("=HYPERLINK(")