The workshop / tests/test_xlsx.py
test_xlsx.py
Last changed by PAVEL, 3 days ago. “load() and read() also take a folder of unzipped parts, so a file saved by a real spreadsheet can live here as text. One test more: 24 in test_xlsx.py.”
What this change did
⋯ import os import sys+ import tempfile import unittest import zipfile⋯ self.assertEqual(load(raw).sheets, ["S"]) + def test_an_unzipped_file_reads_like_the_zip(self):+ src = book([("Totals", '<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1"><f>Raw!A1*2</f><v>14</v></c></row>'),+ ("Raw", '<row r="1"><c r="A1"><v>7</v></c></row>')], ["<t>twice</t>"])+ with tempfile.TemporaryDirectory() as folder:+ with zipfile.ZipFile(src) as z:+ z.extractall(folder)+ b = read(folder)+ self.assertEqual(b.sheets, ["Totals", "Raw"])+ self.assertEqual(b.workbook.get("A1"), "twice")+ self.assertEqual(check(b).line(), "1 of 1 cached values recomputed")+ with self.assertRaises(XlsxError):+ load(os.path.join(folder, "xl")) # a folder, but not a workbook+ def test_what_is_not_an_xlsx_says_so(self): with self.assertRaises(XlsxError):⋯
The whole file
"""gridless/xlsx.py: reading an .xlsx file with zipfile and xml.etree.
Every file here is zipped by the test itself (the workshop keeps text, not
archives), so each fixture can be read in the test that uses it. That has a
price, stated once: the cached values below were written by us, so these tests
prove the READER. They say nothing about the engine; only a file saved by a
real spreadsheet program does.
"""
import io
import os
import sys
import tempfile
import unittest
import zipfile
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from gridless import BLANK, DIV0, NA, REF, Workbook
from gridless.xlsx import XlsxError, check, load, read, shift_formula
MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
DOCREL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
PKGREL = "http://schemas.openxmlformats.org/package/2006/relationships"
def rels(*items):
"""items: (id, type suffix, target)."""
return ('<Relationships xmlns="%s">' % PKGREL + "".join(
'<Relationship Id="%s" Type="%s/%s" Target="%s"/>' % (i, DOCREL, t, target)
for i, t, target in items) + "</Relationships>")
def sheet_xml(rows):
return '<worksheet xmlns="%s"><sheetData>%s</sheetData></worksheet>' % (MAIN, rows)
def book(sheets, strings=None, styles=None, date1904=False, main="xl/workbook.xml", extra=None):
"""A minimal but honest .xlsx in memory. sheets: [(name, sheetData rows)]."""
out = io.BytesIO()
folder = main.rsplit("/", 1)[0]
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
z.writestr("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>')
z.writestr("_rels/.rels", rels(("rId1", "officeDocument", main)))
wrels, entries = [], []
for i, (name, rows) in enumerate(sheets, 1):
rid = "rId%d" % (100 - i) # ids in reverse order: order comes from <sheets>
wrels.append((rid, "worksheet", "worksheets/sheet%d.xml" % i))
entries.append('<sheet name="%s" sheetId="%d" r:id="%s"/>' % (name, i, rid))
z.writestr("%s/worksheets/sheet%d.xml" % (folder, i), sheet_xml(rows))
if strings is not None:
wrels.append(("rIdS", "sharedStrings", "/%s/sharedStrings.xml" % folder)) # an absolute target
z.writestr("%s/sharedStrings.xml" % folder,
'<sst xmlns="%s">%s</sst>' % (MAIN, "".join("<si>%s</si>" % s for s in strings)))
if styles is not None:
wrels.append(("rIdT", "styles", "styles.xml"))
z.writestr("%s/styles.xml" % folder, styles)
z.writestr("%s/_rels/%s.rels" % (folder, main.rsplit("/", 1)[1]), rels(*wrels))
z.writestr(main, '<workbook xmlns="%s" xmlns:r="%s">%s<sheets>%s</sheets></workbook>' % (
MAIN, DOCREL, '<workbookPr date1904="1"/>' if date1904 else "", "".join(entries)))
for name, text in (extra or {}).items():
z.writestr(name, text)
out.seek(0)
return out
class ValuesTest(unittest.TestCase):
def setUp(self):
rows = ('<row r="1"><c r="A1"><v>1.5</v></c><c r="B1" t="s"><v>0</v></c>'
'<c r="C1" t="b"><v>1</v></c><c r="D1" t="e"><v>#N/A</v></c>'
'<c r="E1" t="inlineStr"><is><t>inline</t></is></c><c r="F1" t="s"><v>1</v></c>'
'<c r="G1" t="s"><v>2</v></c><c r="H1" s="3"/></row>'
'<row r="3"><c r="B3" t="str"><f>B1&"!"</f><v>plain!</v></c>'
'<c r="C3" t="d"><v>2024-01-01</v></c><c r="D3" t="d"><v>1900-02-28T12:00:00</v></c></row>')
strings = ["<t>plain</t>",
"<r><t>rich </t></r><r><rPr/><t>text</t></r><rPh sb=\"0\" eb=\"1\"><t>READING</t></rPh>",
'<t xml:space="preserve">line_x000D_break </t>']
self.wb = load(book([("Data", rows)], strings))
def test_scalars(self):
self.assertEqual(self.wb.get("A1"), 1.5)
self.assertIsInstance(self.wb.get("A1"), float)
self.assertEqual(self.wb.get("B1"), "plain")
self.assertIs(self.wb.get("C1"), True)
self.assertIs(self.wb.get("D1"), NA)
self.assertEqual(self.wb.get("E1"), "inline")
def test_rich_text_runs_are_joined_and_phonetic_runs_dropped(self):
self.assertEqual(self.wb.get("F1"), "rich text")
def test_escaped_characters_and_kept_spaces(self):
self.assertEqual(self.wb.get("G1"), "line\rbreak ")
def test_a_styled_cell_with_no_value_is_blank(self):
self.assertIs(self.wb.get("H1"), BLANK)
self.assertIs(self.wb.get("A2"), BLANK)
def test_formula_is_a_formula_not_its_cached_text(self):
self.assertEqual(self.wb.get_formula("B3"), '=B1&"!"')
self.assertEqual(self.wb.get("B3"), "plain!")
self.wb.set("B1", "changed")
self.assertEqual(self.wb.get("B3"), "changed!")
def test_iso_dates_become_1900_serials(self):
self.assertEqual(self.wb.get("C3"), 45292.0) # DESIGN: DATE(2024,1,1) = 45292
self.assertEqual(self.wb.get("D3"), 59.5) # the day before the phantom 29 Feb 1900
class PackageTest(unittest.TestCase):
def test_sheets_come_in_workbook_order_and_sheet1_is_not_invented(self):
wb = load(book([("Totals", '<row r="1"><c r="A1"><f>\'Raw data\'!A1*2</f><v>14</v></c></row>'),
("Raw data", '<row r="1"><c r="A1"><v>7</v></c></row>')]))
self.assertEqual(wb.sheets, ["Totals", "Raw data"])
self.assertEqual(wb.get("Totals!A1"), 14.0) # points at a sheet read after it
self.assertEqual(wb.evaluate("=A1"), 14.0) # the default sheet is the first of the file
def test_parts_are_found_by_relationship_not_by_name(self):
wb = load(book([("S", '<row r="1"><c r="A1" t="s"><v>0</v></c></row>')], ["<t>found</t>"],
main="odd/place/book.xml"))
self.assertEqual(wb.get("A1"), "found")
def test_cells_without_r_follow_one_another(self):
wb = load(book([("S", '<row><c><v>1</v></c><c><v>2</v></c></row><row r="5"><c><v>3</v></c><c r="D5"><v>4</v></c><c><v>5</v></c></row>')]))
self.assertEqual([wb.get(a) for a in ("A1", "B1", "A5", "D5", "E5")], [1.0, 2.0, 3.0, 4.0, 5.0])
def test_a_chart_sheet_has_no_cells_and_is_left_out(self):
src = book([("S", '<row r="1"><c r="A1"><v>1</v></c></row>')])
raw = io.BytesIO()
with zipfile.ZipFile(src) as a, zipfile.ZipFile(raw, "w") as b:
for n in a.namelist():
data = a.read(n).decode("utf-8")
if n == "xl/workbook.xml":
data = data.replace("</sheets>", '<sheet name="Chart" sheetId="9" r:id="rIdC"/></sheets>')
if n == "xl/_rels/workbook.xml.rels":
data = data.replace("</Relationships>", '<Relationship Id="rIdC" Type="%s/chartsheet" Target="chartsheets/sheet1.xml"/></Relationships>' % DOCREL)
b.writestr(n, data)
raw.seek(0)
self.assertEqual(load(raw).sheets, ["S"])
def test_an_unzipped_file_reads_like_the_zip(self):
src = book([("Totals", '<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1"><f>Raw!A1*2</f><v>14</v></c></row>'),
("Raw", '<row r="1"><c r="A1"><v>7</v></c></row>')], ["<t>twice</t>"])
with tempfile.TemporaryDirectory() as folder:
with zipfile.ZipFile(src) as z:
z.extractall(folder)
b = read(folder)
self.assertEqual(b.sheets, ["Totals", "Raw"])
self.assertEqual(b.workbook.get("A1"), "twice")
self.assertEqual(check(b).line(), "1 of 1 cached values recomputed")
with self.assertRaises(XlsxError):
load(os.path.join(folder, "xl")) # a folder, but not a workbook
def test_what_is_not_an_xlsx_says_so(self):
with self.assertRaises(XlsxError):
load(io.BytesIO(b"\xd0\xcf\x11\xe0 an old .xls"))
empty = io.BytesIO()
with zipfile.ZipFile(empty, "w") as z:
z.writestr("hello.txt", "a zip, not a workbook")
empty.seek(0)
with self.assertRaises(XlsxError):
load(empty)
with self.assertRaises(XlsxError):
load(book([("S", '<row r="1"><c r="A1" t="s"><v>7</v></c></row>')], ["<t>only one</t>"]))
class SharedFormulaTest(unittest.TestCase):
ROWS = ('<row r="1"><c r="A1"><v>1</v></c><c r="B1"><f t="shared" ref="B1:B3" si="0">A1*$D$1+SUM(A$1:A1)</f><v>11</v></c><c r="D1"><v>10</v></c></row>'
'<row r="2"><c r="A2"><v>2</v></c><c r="B2"><f t="shared" si="0"/><v>23</v></c></row>'
'<row r="3"><c r="A3"><v>3</v></c><c r="B3"><f t="shared" si="0"/><v>36</v></c>'
'<c r="C3"><f t="shared" ref="C3:D3" si="1">A3+1</f><v>4</v></c><c r="D3"><f t="shared" si="1"/><v>37</v></c></row>')
def test_followers_get_the_master_formula_moved(self):
wb = load(book([("S", self.ROWS)]))
self.assertEqual(wb.get_formula("B1"), "=A1*$D$1+SUM(A$1:A1)")
self.assertEqual(wb.get_formula("B2"), "=A2*$D$1+SUM(A$1:A2)")
self.assertEqual(wb.get_formula("B3"), "=A3*$D$1+SUM(A$1:A3)")
self.assertEqual(wb.get_formula("D3"), "=B3+1") # moved one column right
self.assertEqual([wb.get(a) for a in ("B1", "B2", "B3", "D3")], [11.0, 23.0, 36.0, 37.0])
def test_shift_formula(self):
self.assertEqual(shift_formula("=A1+$B$1", 2, 0), "=A3+$B$1")
self.assertEqual(shift_formula("=$A1+A$1", 1, 1), "=$A2+B$1")
self.assertEqual(shift_formula("=SUM(A:A,2:3)", 1, 1), "=SUM(B:B,3:4)")
self.assertEqual(shift_formula('=IF(Other!C3="A1",-B2%,{1,2})', 1, 0), '=IF(Other!C4="A1",-B3%,{1,2})')
def test_a_reference_pushed_off_the_grid_is_ref(self):
self.assertEqual(shift_formula("=A1", -1, 0), "=#REF!")
self.assertEqual(shift_formula("=SUM(XFD1:XFD2)", 0, 1), "=SUM(#REF!)")
self.assertIs(Workbook({"A1": shift_formula("=A1+1", 0, -1)}).get("A1"), REF)
def test_a_follower_without_master_keeps_its_cached_value(self):
b = read(book([("S", '<row r="1"><c r="A1"><f t="shared" si="9"/><v>5</v></c></row>')]))
self.assertEqual(b.workbook.get("A1"), 5.0)
self.assertIsNone(b.workbook.get_formula("A1"))
self.assertEqual(len(b.skipped), 1)
class FormulaTextTest(unittest.TestCase):
def test_storage_prefix_is_removed_outside_text(self):
wb = load(book([("S", '<row r="1"><c r="A1" t="e"><v>#N/A</v></c>'
'<c r="B1" t="str"><f>_xlfn.IFNA(A1,"_xlfn.kept")</f><v>_xlfn.kept</v></c></row>')]))
self.assertEqual(wb.get_formula("B1"), '=IFNA(A1,"_xlfn.kept")')
self.assertEqual(wb.get("B1"), "_xlfn.kept")
def test_a_formula_we_cannot_parse_keeps_its_cached_value_and_is_listed(self):
b = read(book([("S", '<row r="1"><c r="A1"><f>SUM(Table1[Amount])</f><v>42</v></c><c r="B1"><f>A1+1</f><v>43</v></c></row>')]))
self.assertEqual(b.workbook.get("A1"), 42.0)
self.assertEqual(b.workbook.get("B1"), 43.0)
self.assertEqual([(a, f) for a, f, why in b.skipped], [("S!A1", "=SUM(Table1[Amount])")])
self.assertEqual(b.formulas, 1)
self.assertNotIn(("S", 1, 1), b.cached) # not counted by check(): we did not compute it
def test_a_data_table_cell_is_a_value(self):
b = read(book([("S", '<row r="1"><c r="A1"><f t="dataTable" ref="A1:A2" r1="B1"/><v>3</v></c></row>')]))
self.assertEqual(b.workbook.get("A1"), 3.0)
self.assertEqual(b.skipped[0][2], "data table")
STYLES = ('<styleSheet xmlns="%s"><numFmts count="3">'
'<numFmt numFmtId="164" formatCode="yyyy\\-mm\\-dd"/>'
'<numFmt numFmtId="165" formatCode="[h]:mm:ss"/>'
'<numFmt numFmtId="166" formatCode="0.0 "days""/></numFmts>'
'<cellXfs count="6"><xf numFmtId="0"/><xf numFmtId="14"/><xf numFmtId="164"/>'
'<xf numFmtId="165"/><xf numFmtId="166"/><xf numFmtId="20"/></cellXfs></styleSheet>' % MAIN)
DATES = ('<row r="1"><c r="A1" s="1"><v>43830</v></c><c r="B1" s="2"><v>43830</v></c>'
'<c r="C1" s="0"><v>43830</v></c><c r="D1" s="3"><v>1.5</v></c>'
'<c r="E1" s="4"><v>3</v></c><c r="F1" s="5"><v>0.25</v></c>'
'<c r="G1" s="1"><f>DATE(2024,1,1)</f><v>43830</v></c>'
'<c r="H1" s="0"><f>A1-B1</f><v>0</v></c></row>')
class DateSystemTest(unittest.TestCase):
def test_1904_dates_are_moved_to_the_1900_system(self):
b = read(book([("S", DATES)], styles=STYLES, date1904=True))
wb = b.workbook
self.assertTrue(b.date1904)
self.assertEqual(wb.get("A1"), 45292.0) # built-in format 14: 1 Jan 2024
self.assertEqual(wb.get("B1"), 45292.0) # custom yyyy-mm-dd
self.assertEqual(wb.get("C1"), 43830.0) # General: a number, not a date
self.assertEqual(wb.get("D1"), 1.5) # [h]:mm:ss is a duration
self.assertEqual(wb.get("E1"), 3.0) # the d of "days" is quoted
self.assertEqual(wb.get("F1"), 0.25) # h:mm, a time of day
self.assertEqual(b.cached[("S", 1, 7)], 45292.0) # a cached date moves too
self.assertEqual(check(b).line(), "2 of 2 cached values recomputed")
def test_a_1900_file_is_left_alone(self):
b = read(book([("S", DATES)], styles=STYLES))
self.assertFalse(b.date1904)
self.assertEqual(b.workbook.get("A1"), 43830.0)
class CheckTest(unittest.TestCase):
ROWS = ('<row r="1"><c r="A1"><v>2</v></c><c r="B1"><f>A1*2</f><v>4</v></c>'
'<c r="C1"><f>A1*3</f><v>7</v></c><c r="D1" t="e"><f>1/0</f><v>#DIV/0!</v></c>'
'<c r="E1" t="b"><f>A1=2</f><v>1</v></c><c r="F1"><f>A1=2</f><v>1</v></c>'
'<c r="G1" t="str"><f>""</f><v></v></c><c r="H1"><f>0.1+0.2</f><v>0.3</v></c></row>')
def test_every_cached_value_is_compared_and_the_wrong_one_is_named(self):
r = check(book([("S", self.ROWS)]))
self.assertEqual((r.same, r.total), (5, 7))
self.assertEqual(r.line(), "5 of 7 cached values recomputed")
self.assertEqual(r.different, [("S!C1", "=A1*3", 7.0, 6.0), # a wrong number
("S!F1", "=A1=2", 1.0, True)]) # a boolean is never a number
def test_a_loop_in_the_file_is_a_difference_not_a_crash(self):
r = check(book([("S", '<row r="1"><c r="A1"><f>B1</f><v>0</v></c><c r="B1"><f>A1</f><v>0</v></c></row>')]))
self.assertEqual((r.same, r.total), (0, 2))
def test_errors_compare_by_code(self):
r = check(book([("S", '<row r="1"><c r="A1" t="e"><f>1/0</f><v>#N/A</v></c></row>')]))
self.assertEqual(r.different, [("S!A1", "=1/0", NA, DIV0)])
if __name__ == "__main__":
unittest.main()
Shown as text, exactly as the agents wrote it. Nothing here is run.