test_export_spreadsheet_cells.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """Archive and statistics exports show typed text as it was typed in a spreadsheet.
  2. Print names, notes, tags, project names and failure reasons are typed by
  3. people, and a spreadsheet reads a cell that starts like a formula as one. In
  4. CSV such a cell gets a leading quote; in Excel it is stored as text. Numbers
  5. and empty cells are written as they are.
  6. """
  7. from __future__ import annotations
  8. import csv
  9. import io
  10. import pytest
  11. from openpyxl import load_workbook
  12. from backend.app.services.export import ExportService, _spreadsheet_text
  13. LINK = '=HYPERLINK("https://elsewhere.example","open")'
  14. @pytest.mark.parametrize(
  15. ("value", "expected"),
  16. [
  17. ("Benchy", "Benchy"),
  18. ("a = b", "a = b"),
  19. (LINK, "'" + LINK),
  20. ("+1 extra", "'+1 extra"),
  21. ("-x", "'-x"),
  22. ("@SUM(A1)", "'@SUM(A1)"),
  23. (" =1+1", "' =1+1"),
  24. ("\t=1+1", "'\t=1+1"),
  25. ("\nnote", "'\nnote"),
  26. ("=1+1", "'=1+1"),
  27. ("", ""),
  28. (None, None),
  29. (-5, -5),
  30. (2.5, 2.5),
  31. ],
  32. )
  33. def test_cell_values(value, expected):
  34. assert _spreadsheet_text(value) == expected
  35. def _service() -> ExportService:
  36. return ExportService(db=None) # type: ignore[arg-type]
  37. def test_archive_csv_keeps_typed_text_as_text():
  38. data = _service()._generate_csv(["print_name", "notes", "cost"], [["Benchy", LINK, -1.5]])
  39. rows = list(csv.reader(io.StringIO(data.decode("utf-8"))))
  40. assert rows[1] == ["Benchy", "'" + LINK, "-1.5"]
  41. def test_stats_csv_keeps_typed_text_as_text():
  42. data = _service()._generate_csv_simple([["Failures by Reason", ""], ["+spaghetti", 3]])
  43. rows = list(csv.reader(io.StringIO(data.decode("utf-8"))))
  44. assert rows == [["Failures by Reason", ""], ["'+spaghetti", "3"]]
  45. def test_archive_xlsx_stores_typed_text_as_text():
  46. data = _service()._generate_xlsx(["print_name", "notes", "cost"], [["Benchy", LINK, -1.5]], ["a", "b", "c"])
  47. sheet = load_workbook(io.BytesIO(data)).active
  48. assert sheet is not None
  49. assert (sheet["B2"].value, sheet["B2"].data_type) == (LINK, "s")
  50. assert sheet["C2"].value == -1.5
  51. def test_stats_xlsx_stores_typed_text_as_text():
  52. data = _service()._generate_xlsx_simple([["Failures by Reason", ""], [LINK, 3]])
  53. sheet = load_workbook(io.BytesIO(data)).active
  54. assert sheet is not None
  55. assert (sheet["A2"].value, sheet["A2"].data_type) == (LINK, "s")
  56. assert sheet["B2"].value == 3