import ast import math import os import time import pytest from spreadsheet_engine import ( CircularReferenceError, FormulaError, FormulaSyntaxError, Spreadsheet, ) def test_01_no_eval_or_exec_used(): """Enforce a real parser — no eval(), exec(), or compile() shortcuts.""" src_path = os.path.join(os.path.dirname(__file__), "spreadsheet_engine.py") with open(src_path, "r", encoding="utf-8") as f: tree = ast.parse(f.read()) banned = {"eval", "exec", "compile", "__import__"} for node in ast.walk(tree): if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): assert node.func.id not in banned, f"Forbidden builtin `{node.func.id}` used!" def test_02_basic_literals_and_case_insensitive_coords(): s = Spreadsheet() s.set_cell("a1", 10) s.set_cell("B2", 2.5) s.set_cell("C3", "=-a1 + b2 * 4") assert s.get("A1") == 10 assert s.get("b2") == 2.5 assert s.get("c3") == pytest.approx(0.0) assert s.get("Z99") == 0 # unset cell defaults to 0 def test_03_multi_letter_columns_and_ranges(): s = Spreadsheet() s.set_cell("Z1", 10) s.set_cell("AA1", 20) s.set_cell("AB1", 30) s.set_cell("AC1", "=SUM(Z1:AB1)") assert s.get("AC1") == pytest.approx(60.0) # Reversed 2D range s.set_cell("Z2", 4) s.set_cell("AA2", 6) s.set_cell("AB2", 10) s.set_cell("AD1", "=SUM(AB2:Z1)") assert s.get("AD1") == pytest.approx(80.0) def test_04_operator_precedence_and_right_assoc_power(): s = Spreadsheet() s.set_cell("A1", "=2^3^2") # right-associative: 2^(3^2) = 512 s.set_cell("A2", "=(2^3)^2") # 64 s.set_cell("A3", "=-2^2") # unary minus lower than ^: -(2^2) = -4 s.set_cell("A4", "=(-2)^2") # 4 s.set_cell("A5", "=2^-3") # 2^(-3) = 0.125 s.set_cell("A6", "=10 - 3 - 2") # left-associative: 5 s.set_cell("A7", "=20 / 4 / 2") # left-associative: 2.5 s.set_cell("A8", "=--5 + +-3") # chained unary ops: 5 + (-3) = 2 assert s.get("A1") == pytest.approx(512.0) assert s.get("A2") == pytest.approx(64.0) assert s.get("A3") == pytest.approx(-4.0) assert s.get("A4") == pytest.approx(4.0) assert s.get("A5") == pytest.approx(0.125) assert s.get("A6") == pytest.approx(5.0) assert s.get("A7") == pytest.approx(2.5) assert s.get("A8") == pytest.approx(2.0) def test_05_comparisons_and_if_short_circuit_div_zero(): s = Spreadsheet() s.set_cell("A1", 0) s.set_cell("B1", "=IF(A1 == 0, 99, 10 / A1)") assert s.get("B1") == pytest.approx(99.0) s.set_cell("A1", 2) assert s.get("B1") == pytest.approx(5.0) # Comparison operators s.set_cell("C1", "=IF(A1 >= 2, IF(A1 < 3, 1, 0), -1)") s.set_cell("C2", "=IF(A1 != 2, 100, 200)") assert s.get("C1") == pytest.approx(1.0) assert s.get("C2") == pytest.approx(200.0) def test_06_aggregates_empty_cell_semantics(): s = Spreadsheet() s.set_cell("A1", 10) s.set_cell("A3", 30) # A2 is unset/empty! s.set_cell("A4", 0) # explicit zero IS populated! s.set_cell("B1", "=SUM(A1:A4)") s.set_cell("B2", "=COUNT(A1:A4)") # 3 populated cells (A1, A3, A4) s.set_cell("B3", "=AVG(A1:A4)") # (10 + 30 + 0) / 3 = 13.3333... s.set_cell("B4", "=MIN(A1:A4)") # 0 s.set_cell("B5", "=MAX(A1:A4)") # 30 assert s.get("B1") == pytest.approx(40.0) assert s.get("B2") == pytest.approx(3.0) assert s.get("B3") == pytest.approx(40.0 / 3.0) assert s.get("B4") == pytest.approx(0.0) assert s.get("B5") == pytest.approx(30.0) # Clearing A4 to None removes it from populated set s.set_cell("A4", None) assert s.get("B2") == pytest.approx(2.0) assert s.get("B3") == pytest.approx(20.0) assert s.get("B4") == pytest.approx(10.0) def test_07_nested_functions_and_mixed_range_scalar_args(): s = Spreadsheet() s.set_cell("A1", 2) s.set_cell("A2", 4) s.set_cell("B1", 6) s.set_cell("B2", 8) s.set_cell("C1", "=SUM(A1:B2, MAX(A1:B2) * 2, IF(MIN(A1:B2) == 2, 10, 0))") assert s.get("C1") == pytest.approx(20.0 + 16.0 + 10.0) # AVG on completely empty range raises FormulaError s.set_cell("D1", "=AVG(K1:K5)") with pytest.raises(FormulaError): s.get("D1") def test_08_error_propagation_and_self_healing(): s = Spreadsheet() s.set_cell("A1", 0) s.set_cell("B1", "=10 / A1") s.set_cell("C1", "=B1 + 5") s.set_cell("D1", "=SUM(B1:C1)") s.set_cell("E1", "=IF(1, 42, B1)") # short-circuits past errored cell B1! assert s.get("E1") == pytest.approx(42.0) for cell in ("B1", "C1", "D1"): with pytest.raises(FormulaError): s.get(cell) # Heal A1 -> all downstream cells must automatically heal! s.set_cell("A1", 2) assert s.get("B1") == pytest.approx(5.0) assert s.get("C1") == pytest.approx(10.0) assert s.get("D1") == pytest.approx(15.0) def test_09_direct_and_indirect_cycle_transactional_rollback(): s = Spreadsheet() s.set_cell("A1", 5) s.set_cell("B1", "=A1 * 2") s.set_cell("C1", "=B1 + 3") s.set_cell("D1", "=C1 + 1") assert s.get("D1") == pytest.approx(14.0) # Self-cycle with pytest.raises(CircularReferenceError): s.set_cell("A1", "=A1 + 1") assert s.get("A1") == 5 and s.get("D1") == pytest.approx(14.0) # 4-hop cycle A1 -> B1 -> C1 -> D1 -> A1 with pytest.raises(CircularReferenceError): s.set_cell("A1", "=D1 + 1") assert s.get("A1") == 5 assert s.get("B1") == pytest.approx(10.0) assert s.get("C1") == pytest.approx(13.0) assert s.get("D1") == pytest.approx(14.0) # Downstream still updates cleanly after rejected cycle! s.set_cell("A1", 10) assert s.get("D1") == pytest.approx(24.0) def test_10_cycle_hidden_inside_2d_range_rollback(): s = Spreadsheet() s.set_cell("A1", 1) s.set_cell("B2", 2) s.set_cell("C3", 3) s.set_cell("D1", "=SUM(A1:C3)") assert s.get("D1") == pytest.approx(6.0) # B2 is inside A1:C3 -> making B2 depend on D1 creates cycle B2 -> D1 -> B2! with pytest.raises(CircularReferenceError): s.set_cell("B2", "=D1 + 1") assert s.get("B2") == 2 assert s.get("D1") == pytest.approx(6.0) # Self-inclusion in range: B2 = "=SUM(A1:C3)" with pytest.raises(CircularReferenceError): s.set_cell("B2", "=SUM(A1:C3)") assert s.get("B2") == 2 def test_11_syntax_error_rollback(): s = Spreadsheet() s.set_cell("A1", 42) s.set_cell("B1", "=A1 + 8") assert s.get("B1") == pytest.approx(50.0) for bad in ("=1 +", "=SUM(A1, )", "=((1+2)", "=1 + 2)", "=UNKNOWN_FN(1)", "=1 == == 2"): with pytest.raises(FormulaSyntaxError): s.set_cell("B1", bad) assert s.get("B1") == pytest.approx(50.0) def test_12_batch_update_dependency_swap_and_atomic_rollback(): s = Spreadsheet() s.set_cell("A1", 10) s.set_cell("B1", "=A1 + 5") s.set_cell("C1", "=B1 * 2") assert s.get("C1") == pytest.approx(30.0) # Reversing dependency direction atomically MUST succeed (no false cycle!) s.batch_update({"A1": "=B1 * 3", "B1": 4}) assert s.get("B1") == 4 assert s.get("A1") == pytest.approx(12.0) assert s.get("C1") == pytest.approx(8.0) # Batch with a cycle in the combined graph MUST roll back ALL updates including unrelated X1! s.set_cell("X1", 100) with pytest.raises(CircularReferenceError): s.batch_update({"X1": 999, "B1": "=A1 + 1"}) assert s.get("X1") == 100 assert s.get("B1") == 4 assert s.get("A1") == pytest.approx(12.0) assert s.get("C1") == pytest.approx(8.0) # Batch with a syntax error in one entry MUST roll back ALL updates! with pytest.raises(FormulaSyntaxError): s.batch_update({"X1": 555, "B1": "=1 + * 2"}) assert s.get("X1") == 100 assert s.get("B1") == 4 def test_13_diamond_dag_and_incremental_recalc_performance(): """Verifies diamond DAG evaluates accurately and incremental updates don't recompute unrelated subgraphs.""" s = Spreadsheet() # Build 1,000 unrelated formula cells in column Z s.set_cell("Y1", 1) s.batch_update({f"Z{i}": f"=Y1 + {i}" for i in range(1, 1001)}) assert s.get("Z1000") == pytest.approx(1001.0) # Build a 40-layer diamond DAG in A/B where naive recursive eval takes 2^40 steps! updates = {"A1": 1, "B1": 1} for i in range(2, 42): updates[f"A{i}"] = f"=A{i-1} + B{i-1}" updates[f"B{i}"] = f"=A{i-1} + B{i-1}" s.batch_update(updates) expected = float(2 ** 40) assert s.get("A41") == pytest.approx(expected) # Now mutate A1 50 times — must complete in well under 0.5s (proves incremental topo eval, not naive recursion or full-sheet recompute!) t0 = time.perf_counter() for k in range(1, 51): s.set_cell("A1", k) elapsed = time.perf_counter() - t0 assert s.get("A41") == pytest.approx(float((50 + 1) * (2 ** 39))) assert elapsed < 0.5, f"Incremental update too slow ({elapsed:.3f}s) — likely recomputing unrelated cells or exponential recursion!" # Check eval_count if exposed or unrelated Z1000 untouched assert s.get("Z1000") == pytest.approx(1001.0) def test_14_overwriting_formula_cleans_up_old_dependencies(): """After replacing a formula with a constant, old upstream cells must no longer block new dependencies.""" s = Spreadsheet() s.set_cell("A1", 1) s.set_cell("B1", "=A1 + 1") assert s.get("B1") == pytest.approx(2.0) # Break B1 -> A1 edge s.set_cell("B1", 10) # Now A1 -> B1 MUST succeed without false CircularReferenceError! s.set_cell("A1", "=B1 * 3") assert s.get("A1") == pytest.approx(30.0) assert s.get("B1") == 10 def test_15_string_number_coercion_and_none_clear(): s = Spreadsheet() s.set_cell("A1", "3.5") s.set_cell("A2", "-7") s.set_cell("A3", "=A1 + A2") assert s.get("A3") == pytest.approx(-3.5) s.set_cell("A1", None) assert s.get("A1") == 0 assert s.get("A3") == pytest.approx(-7.0)