Repository navigation
Expand file tree
/
Copy pathtest_method_table.py
More file actions
1308 lines (1206 loc) · 60.2 KB
/
Copy pathtest_method_table.py
File metadata and controls
1308 lines (1206 loc) · 60.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Method and column comparison capture, including nested helpers."""
import base64
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from cso_python.bindings import generate
from cso_python.execution import Execution, execute
RECTANGLE = """from typing import Annotated, TypeAlias
from cso_python import CalculationResults, calculation, section, symbol
Width: TypeAlias = Annotated[float, symbol(glyph="w", description="Width", unit="m")]
Height: TypeAlias = Annotated[float, symbol(glyph="h", description="Height", unit="m")]
Allowance: TypeAlias = Annotated[float, symbol(glyph="c", description="Allowance", unit="m")]
@calculation(id="rectangle", title="Rectangle geometry")
@section(id="geometry", title="Rectangle geometry", root=True)
def rectangle(width: Width, height: Height, allowance: Allowance = 0.0) -> CalculationResults:
area: Annotated[float, symbol(glyph="A", description="Area", unit="m^2")] = width * height
perimeter: Annotated[float, symbol(glyph="P", description="Perimeter", unit="m")] = 2 * (width + height)
return {"area": area, "perimeter": perimeter}
"""
PNG = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
)
MARGIN = '''from typing import Annotated, TypeAlias
from cso_python import CalculationResults, calculation, section, symbol, text
Length: TypeAlias = Annotated[float, symbol(glyph="L", description="Length", unit="m")]
@calculation(id="margin", title="Add a margin")
@section(id="margin-section", title="Margin")
def margin(length: Length) -> CalculationResults:
"""Add one metre of margin."""
text(id="assumption", content="The margin is one metre.")
grown: Annotated[float, symbol(glyph="G", description="Grown length", unit="m")] = length + 1.0
return {"grown": grown}
'''
PANEL = '''from typing import Annotated, TypeAlias
from cso_python import CalculationResults, calculation, document_section, figure, section, symbol, text
from _cso_bindings.margin import margin
Width: TypeAlias = Annotated[float, symbol(glyph="w", description="Width", unit="m")]
Height: TypeAlias = Annotated[float, symbol(glyph="h", description="Height", unit="m")]
@calculation(id="panel", title="Panel area")
@section(id="panel-section", title="Panel")
def panel(width: Width, height: Height) -> CalculationResults:
"""Grow each side, then multiply."""
with document_section(id="assumptions", title="Assumptions"):
text(id="note", content="Panel sides are grown independently.")
figure(id="sketch", path="sketch.png", media_type="image/png", caption="Panel sketch", alt="A rectangle")
wider = margin(length=width)
taller = margin(length=height)
product: Annotated[float, symbol(glyph="Q", description="Grown product", unit="m^2")] = wider["grown"] * taller["grown"]
area: Annotated[float, symbol(glyph="A", description="Area", unit="m^2")] = product
return {"area": area}
'''
def content_shape(content: list) -> list:
shaped = []
for item in content:
if item["kind"] == "section":
shaped.append(("section", item["title"], content_shape(item["content"])))
elif item["kind"] == "quantity":
shaped.append(("quantity", item["variableName"]))
elif item["kind"] == "call":
shaped.append(
(
"call",
item["binding"],
[
{"name": input["name"], "formulaText": input["formulaText"]}
for input in item["inputs"]
],
item["outputs"],
)
)
else:
shaped.append((item["kind"], item["localId"]))
return shaped
def compare_source(body: str) -> str:
return f"""from typing import Annotated
from cso_python import CalculationResults, calculation, method, section, symbol, table
from _cso_bindings.rectangle import rectangle
@calculation(id="compare", title="Rectangle comparison")
@section(id="comparison", title="Comparison", root=True)
def compare() -> CalculationResults:
{body}
compared: Annotated[float, symbol(glyph="R", description="Compared area", unit="m^2")] = first_panel["area"]
return {{"compared": compared}}
"""
class MethodTableCaptureTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="cso-method-table-")
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
(self.root / "rectangle.cso.py").write_text(RECTANGLE)
generate(self.root)
def write_compare(self, body: str) -> None:
(self.root / "compare.cso.py").write_text(compare_source(body))
def execution(self):
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertTrue(response["ok"], response)
return response
def external_sources(self):
(self.root / "methods.py").write_text("""from typing import Annotated, TypeAlias
from cso_python import external_function, symbol
Length: TypeAlias = Annotated[float, symbol(glyph="L_{in}", description="Length", unit="m")]
Area: TypeAlias = Annotated[float, symbol(glyph="A_{out}", description="Area", unit="m^2")]
Count: TypeAlias = Annotated[int, symbol(glyph="n_{diag}", description="Diagnostic count", unit="")]
square = external_function(path="adapter.py", function="square", inputs={"length": Length}, outputs={"area": Area, "count": Count}, description="Square the supplied length.")
""")
(self.root / "adapter.py").write_text("""calls = 0
def square(*, length):
global calls
calls += 1
return {"area": length * length, "count": calls}
""")
(self.root / "external_case.cso.py").write_text("""from typing import Annotated
from cso_python import calculation, section, symbol
from methods import Length
from _cso_bindings._external.methods import square
@calculation(id="case", title="External case")
@section(title="External case", root=True)
def external_case(length: Length):
searched = square(length=length)
doubled: Annotated[float, symbol(glyph="D_{out}", description="Double area", unit="m^2")] = searched["area"] * 2.0
return {"doubled": doubled}
""")
def test_external_method_has_static_leaf_and_distinct_equal_input_calls(self):
self.external_sources()
(self.root / "external_compare.cso.py").write_text(
"""from cso_python import calculation, section, method, table
from _cso_bindings.external_case import external_case
@calculation(id="compare", title="External comparison")
@section(title="External comparison", root=True)
def compare():
method(id="external-method", calculation=external_case, title="External method")
first_case = external_case(length=3.0)
second_case = external_case(length=3.0)
table(id="cases", method="external-method", title="Cases", cases={"First": first_case, "Second": second_case}, outputs=("doubled",))
return {"doubled": first_case["doubled"]}
"""
)
generate(self.root)
response = execute(self.root / "external_compare.cso.py", "compare", {})
self.assertTrue(response["ok"], response)
execution = response["execution"]
leaf = next(
item
for item in execution["methods"][0]["content"]
if item["kind"] == "external"
)
self.assertEqual(leaf["binding"], "searched")
self.assertEqual(leaf["outputs"], ["area", "count"])
self.assertEqual(
leaf["declaration"]["interface"]["description"],
"Square the supplied length.",
)
self.assertEqual(
[call["outputs"][1]["value"] for call in execution["externalCalls"]], [1, 2]
)
def test_empty_external_method_never_imports_adapter_and_revision_tracks_adapter(
self,
):
self.external_sources()
(self.root / "adapter.py").write_text(
'import missing_optional_library\nraise RuntimeError("must not run")\n'
)
(self.root / "empty_external.cso.py").write_text("""from typing import Annotated
from cso_python import calculation, section, method, table, symbol
from _cso_bindings.external_case import external_case
@calculation(id="empty", title="Empty external comparison")
@section(title="Empty", root=True)
def compare():
method(id="external-method", calculation=external_case, title="External method")
table(id="cases", method="external-method", title="Cases", cases={})
ready: Annotated[int, symbol(glyph="r_{ok}", description="Ready", unit="")] = 1
return {"ready": ready}
""")
generate(self.root)
first = execute(self.root / "empty_external.cso.py", "compare", {})
self.assertTrue(first["ok"], first)
self.assertEqual(first["protocolVersion"], "4")
self.assertEqual(first["execution"]["externalCalls"], [])
incompatible = execute(
self.root / "empty_external.cso.py", "compare", {}, supports_external=False
)
self.assertFalse(incompatible["ok"])
self.assertEqual(
incompatible["diagnostics"][0]["code"], "INCOMPATIBLE_CONTRACT"
)
(self.root / "adapter.py").write_text(
'import another_missing_library\nraise RuntimeError("still must not run")\n'
)
second = execute(self.root / "empty_external.cso.py", "compare", {})
self.assertTrue(second["ok"], second)
self.assertNotEqual(
first["execution"]["methods"][0]["revision"],
second["execution"]["methods"][0]["revision"],
)
def test_column_cap_limits_print_groups_without_changing_cells(self):
self.write_compare(
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
second_panel = rectangle(width=1.0, height=6.0)
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel, "Case B": second_panel}, column_cap=1)
"""
)
execution = self.execution()["execution"]
table = execution["tables"][0]
self.assertEqual(table["columnCap"], 1)
self.assertEqual(len(table["cells"]), 10)
self.assertNotIn("columnCap", execution["methods"][0])
def test_invalid_column_cap_is_rejected_before_execution(self):
self.write_compare(
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel}, column_cap=0)
"""
)
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(response["diagnostics"][0]["code"], "INVALID_METHOD")
run.assert_not_called()
def test_method_keeps_a_quantity_declared_inside_a_document_section(self):
(self.root / "grouped.cso.py").write_text(
"""from typing import Annotated, TypeAlias
from cso_python import CalculationResults, calculation, document_section, section, symbol
Width: TypeAlias = Annotated[float, symbol(glyph="w", description="Width", unit="m")]
@calculation(id="grouped", title="Grouped geometry")
@section(id="grouped-geometry", title="Grouped geometry")
def grouped(width: Width) -> CalculationResults:
with document_section(id="inner", title="Inner"):
inner: Annotated[float, symbol(glyph="I", description="Inner", unit="m")] = width
return {"inner": inner}
"""
)
(self.root / "grouped_compare.cso.py").write_text(
"""from typing import Annotated
from cso_python import CalculationResults, calculation, method, section, symbol, table
from _cso_bindings.grouped import grouped
@calculation(id="compare", title="Grouped comparison")
@section(id="comparison", title="Comparison", root=True)
def compare() -> CalculationResults:
method(id="grouped-method", calculation=grouped, title="How the grouped result is calculated")
case = grouped(width=2.0)
table(id="grouped-results", method="grouped-method", title="Grouped results", cases={"Case": case}, outputs=("inner",))
ready: Annotated[float, symbol(glyph="r", description="Ready", unit="")] = case["inner"]
return {"ready": ready}
"""
)
generate(self.root)
response = execute(self.root / "grouped_compare.cso.py", "compare", {})
self.assertTrue(response["ok"], response)
names = [
item["selectionName"]
for item in response["execution"]["methods"][0]["quantities"]
]
self.assertIn("inner", names)
def test_column_table_binds_equal_areas_without_a_representative_method_case(self):
self.write_compare(
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
second_panel = rectangle(width=1.0, height=6.0)
extra_panel = rectangle(width=4.0, height=5.0)
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel, "Case B": second_panel})
"""
)
response = self.execution()
execution = response["execution"]
self.assertEqual(response["protocolVersion"], "3")
self.assertEqual(execution["cso"]["schemaVersion"], "1.1.0")
self.assertEqual(
[item["id"] for item in execution["invocations"]],
["root", "root/first_panel", "root/second_panel", "root/extra_panel"],
)
method = execution["methods"][0]
self.assertEqual(method["localId"], "rectangle-method")
self.assertEqual(method["function"], "rectangle")
self.assertNotIn("resolvedInputs", method)
self.assertNotIn(
3,
[
node.get("literal", {}).get("value")
for quantity in method["quantities"]
for node in quantity["nodes"]
],
)
self.assertEqual(
[quantity["selectionName"] for quantity in method["quantities"]],
["width", "height", "allowance", "area", "perimeter"],
)
area = next(
quantity
for quantity in method["quantities"]
if quantity["selectionName"] == "area"
)
self.assertEqual(area["glyph"], "A")
self.assertIn("w", area["formulaText"])
self.assertIn("h", area["formulaText"])
table = execution["tables"][0]
self.assertEqual(table["casesAxis"], "columns")
self.assertEqual(table["inputs"], ["width", "height", "allowance"])
self.assertEqual(table["outputs"], ["area", "perimeter"])
self.assertEqual(
[case["heading"] for case in table["cases"]], ["Case A", "Case B"]
)
self.assertEqual(
[case["invocationId"] for case in table["cases"]],
["root/first_panel", "root/second_panel"],
)
areas = [
output
for output in execution["authoring"]["outputs"]
if output["name"] == "area"
]
self.assertEqual(sorted(output["value"] for output in areas), [6, 6, 20])
perimeters = {
output["invocationId"]: output["value"]
for output in execution["authoring"]["outputs"]
if output["name"] == "perimeter"
}
self.assertEqual(perimeters["root/first_panel"], 10)
self.assertEqual(perimeters["root/second_panel"], 14)
area_cells = [cell for cell in table["cells"] if cell["quantity"] == "area"]
self.assertEqual(
[cell["symbolId"] for cell in area_cells],
[
output["symbolId"]
for output in areas
if output["invocationId"] != "root/extra_panel"
],
)
allowance_cells = [
cell for cell in table["cells"] if cell["quantity"] == "allowance"
]
self.assertEqual([cell["unit"] for cell in allowance_cells], ["m", "m"])
root_items = execution["cso"]["sections"][0]["items"]
kinds = [item["kind"] for item in root_items]
self.assertLess(kinds.index("method"), kinds.index("table"))
self.assertEqual(kinds.count("section"), 3)
modules = {
item["moduleId"]: item["sha256"] for item in execution["sourceManifest"]
}
self.assertEqual(modules[method["moduleId"]], method["sourceHash"])
def test_empty_cases_plan_the_method_without_executing_it(self):
(self.root / "compare.cso.py").write_text("""from typing import Annotated
from cso_python import CalculationResults, calculation, method, section, symbol, table
from _cso_bindings.rectangle import rectangle
@calculation(id="compare", title="Rectangle comparison")
@section(id="comparison", title="Comparison", root=True)
def compare() -> CalculationResults:
method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={})
ready: Annotated[float, symbol(glyph="r", description="Ready", unit="")] = 1
return {"ready": ready}
""")
execution = self.execution()["execution"]
self.assertEqual(
[item["function"] for item in execution["invocations"]], ["compare"]
)
self.assertEqual(execution["tables"][0]["cases"], [])
self.assertEqual(execution["tables"][0]["cells"], [])
self.assertTrue(execution["methods"][0]["quantities"])
def test_later_slices_are_diagnosed_before_execution(self):
cases = {
"invalid axis": (
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel}, cases_axis="diagonal")
""",
"INVALID_METHOD",
),
"duplicate heading": (
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
second_panel = rectangle(width=1.0, height=6.0)
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel, "Case A": second_panel})
""",
"DUPLICATE_CASE_HEADING",
),
"forward reference": (
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel})
first_panel = rectangle(width=2.0, height=3.0)
""",
"AMBIGUOUS_CASE_REFERENCE",
),
"duplicate id": (
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
method(id="rectangle-method", calculation=rectangle, title="Repeated method")
first_panel = rectangle(width=2.0, height=3.0)
""",
"DUPLICATE_IDENTITY",
),
}
for name, (body, code) in cases.items():
with self.subTest(name=name):
self.write_compare(body)
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertFalse(response["ok"], response)
self.assertEqual(response["diagnostics"][0]["code"], code, response)
run.assert_not_called()
def test_explicit_empty_selection_and_unknown_names(self):
self.write_compare(
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel}, inputs=(), outputs=("perimeter",))
"""
)
table = self.execution()["execution"]["tables"][0]
self.assertEqual(table["inputs"], [])
self.assertEqual(table["outputs"], ["perimeter"])
self.assertEqual([cell["quantity"] for cell in table["cells"]], ["perimeter"])
self.write_compare(
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel}, outputs=("area", "area"))
"""
)
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(response["diagnostics"][0]["code"], "DUPLICATE_QUANTITY")
run.assert_not_called()
self.write_compare(
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel}, outputs=("missing",))
"""
)
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(response["diagnostics"][0]["code"], "UNKNOWN_QUANTITY")
run.assert_not_called()
def test_method_content_awaiting_later_slices_is_diagnosed(self):
source = (self.root / "rectangle.cso.py").read_text()
(self.root / "rectangle.cso.py").write_text(
source.replace(
" area:",
" with open('x'):\n pass\n area:",
)
)
(self.root / "compare.cso.py").write_text("""from typing import Annotated
from cso_python import CalculationResults, calculation, method, section, symbol, table
from _cso_bindings.rectangle import rectangle
@calculation(id="compare", title="Rectangle comparison")
@section(id="comparison", title="Comparison", root=True)
def compare() -> CalculationResults:
method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
ready: Annotated[float, symbol(glyph="r", description="Ready", unit="")] = 1
return {"ready": ready}
""")
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(
response["diagnostics"][0]["code"], "UNSUPPORTED_METHOD_CONTENT"
)
run.assert_not_called()
def test_overlapping_membership_is_rejected(self):
self.write_compare(
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
table(id="first-results", method="rectangle-method", title="First", cases={"Case A": first_panel})
table(id="second-results", method="rectangle-method", title="Second", cases={"Case A again": first_panel})
"""
)
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(response["diagnostics"][0]["code"], "OVERLAPPING_TABLE")
run.assert_not_called()
def write_composed(self, body: str) -> None:
(self.root / "sketch.png").write_bytes(PNG)
(self.root / "margin.cso.py").write_text(MARGIN)
(self.root / "panel.cso.py").write_text(PANEL)
(self.root / "compare.cso.py").write_text(f"""from typing import Annotated
from cso_python import CalculationResults, calculation, method, section, symbol, table, text
from _cso_bindings.panel import panel
@calculation(id="compare", title="Panel comparison")
@section(id="comparison", title="Comparison", root=True)
def compare() -> CalculationResults:
{body}
compared: Annotated[float, symbol(glyph="R", description="Compared area", unit="m^2")] = first_panel["area"]
return {{"compared": compared}}
""")
generate(self.root)
def test_forwarded_helper_outputs_bind_to_each_case(self):
self.write_composed(
""" method(id="panel-method", calculation=panel, title="Panel")
first_panel = panel(width=2.0, height=3.0)
second_panel = panel(width=4.0, height=5.0)
table(id="panels", method="panel-method", title="Panels", cases={"First": first_panel, "Second": second_panel})
"""
)
path = self.root / "panel.cso.py"
path.write_text(
PANEL.replace('return {"area": area}', 'return {"area": wider["grown"]}')
)
compare = self.root / "compare.cso.py"
compare.write_text(compare.read_text().replace('unit="m^2"', 'unit="m"'))
generate(self.root)
response = self.execution()
execution = response["execution"]
cells = [
cell for cell in execution["tables"][0]["cells"] if cell["role"] == "output"
]
self.assertEqual(len(cells), 2)
self.assertNotEqual(cells[0]["symbolId"], cells[1]["symbolId"])
outputs = execution["authoring"]["outputs"]
for cell in cells:
returned = next(
output
for output in outputs
if output["invocationId"] == cell["caseInvocationId"]
and output["name"] == "area"
)
self.assertEqual(cell["symbolId"], returned["symbolId"])
self.assertEqual(cell["unit"], "m")
def test_nested_helpers_keep_distinct_call_mappings(self):
self.write_composed(
""" method(id="panel-method", calculation=panel, title="How panel area is calculated")
text(id="case-a", content="Case A is the narrow panel")
first_panel = panel(width=2.0, height=3.0)
text(id="case-b", content="Case B is the wide panel")
second_panel = panel(width=1.0, height=6.0)
table(id="panel-results", method="panel-method", title="Panel comparison", cases={"Case A": first_panel, "Case B": second_panel}, inputs=(), outputs=("area",))
extra_panel = panel(width=4.0, height=5.0)
"""
)
execution = self.execution()["execution"]
method = execution["methods"][0]
self.assertEqual(
content_shape(method["content"]),
[
("quantity", "width"),
("quantity", "height"),
("section", "Assumptions", [("text", "note")]),
("figure", "sketch"),
("call", "wider", [{"name": "length", "formulaText": "w"}], ["grown"]),
("call", "taller", [{"name": "length", "formulaText": "h"}], ["grown"]),
("quantity", "product"),
("quantity", "area"),
],
)
self.assertEqual(len(method["helpers"]), 1)
helper = method["helpers"][0]
self.assertEqual(helper["function"], "margin")
self.assertEqual(
[item["helperId"] for item in method["content"] if item["kind"] == "call"],
[helper["id"], helper["id"]],
)
wider = next(
item for item in method["content"] if item.get("binding") == "wider"
)
self.assertEqual(wider["inputs"][0]["nodes"][0]["mode"], "SYMBOL")
self.assertEqual(wider["inputs"][0]["nodes"][0]["ref"]["name"], "width")
self.assertEqual(
content_shape(helper["content"]),
[
("quantity", "length"),
("text", "assumption"),
("quantity", "grown"),
],
)
self.assertEqual(helper["content"][1]["content"], "The margin is one metre.")
product = next(
item for item in method["quantities"] if item["variableName"] == "product"
)
self.assertEqual(product["formulaText"], "(wider.grown * taller.grown)")
self.assertEqual(product["role"], "intermediate")
rendered = str(method["content"])
self.assertIn("Panel sides are grown independently.", rendered)
self.assertNotIn("Case A is the narrow panel", rendered)
self.assertNotIn("The margin is one metre.", rendered)
table = execution["tables"][0]
self.assertEqual(table["inputs"], [])
self.assertEqual(table["outputs"], ["area"])
parent_text = [
item["text"]["content"]
for item in execution["cso"]["sections"][0]["items"]
if item["kind"] == "text"
]
self.assertEqual(
parent_text,
["Case A is the narrow panel", "Case B is the wide panel"],
)
self.assertIn(
"root/first_panel",
[
section["metadata"].get("invocationId")
for section in execution["cso"]["sections"]
],
)
self.assertIn(
"root/extra_panel", [item["id"] for item in execution["invocations"]]
)
self.assertTrue(
any(asset["path"] == "sketch.png" for asset in execution["assets"])
)
self.assertNotIn(
2,
[
node.get("literal", {}).get("value")
for quantity in method["quantities"]
for node in quantity["nodes"]
],
)
def test_empty_method_keeps_helper_explanation_without_executing_it(self):
(self.root / "sketch.png").write_bytes(PNG)
(self.root / "margin.cso.py").write_text(MARGIN)
(self.root / "panel.cso.py").write_text(PANEL)
(self.root / "compare.cso.py").write_text("""from typing import Annotated
from cso_python import CalculationResults, calculation, method, section, symbol, table
from _cso_bindings.panel import panel
@calculation(id="compare", title="Panel comparison")
@section(id="comparison", title="Comparison", root=True)
def compare() -> CalculationResults:
method(id="panel-method", calculation=panel, title="How panel area is calculated")
table(id="panel-results", method="panel-method", title="Panel comparison", cases={}, outputs=("area",))
ready: Annotated[float, symbol(glyph="r", description="Ready", unit="")] = 1
return {"ready": ready}
""")
generate(self.root)
execution = self.execution()["execution"]
self.assertEqual(
[item["function"] for item in execution["invocations"]], ["compare"]
)
method = execution["methods"][0]
self.assertEqual(method["helpers"][0]["function"], "margin")
self.assertEqual(
[item["binding"] for item in method["content"] if item["kind"] == "call"],
["wider", "taller"],
)
self.assertTrue(
any(asset["path"] == "sketch.png" for asset in execution["assets"])
)
def test_disjoint_tables_share_one_method(self):
self.write_compare(
""" method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
second_panel = rectangle(width=1.0, height=6.0)
table(id="left-results", method="rectangle-method", title="Left", cases={"A": first_panel})
table(id="right-results", method="rectangle-method", title="Right", cases={"B": second_panel})
"""
)
execution = self.execution()["execution"]
self.assertEqual(len(execution["methods"]), 1)
self.assertEqual(
[table["methodId"] for table in execution["tables"]],
[execution["methods"][0]["id"], execution["methods"][0]["id"]],
)
def test_inner_table_overlap_is_rejected(self):
(self.root / "leaf.cso.py").write_text(
"""from typing import Annotated, TypeAlias
from cso_python import CalculationResults, calculation, section, symbol
Width: TypeAlias = Annotated[float, symbol(glyph="w", description="Width", unit="m")]
@calculation(id="leaf", title="Leaf")
@section(id="leaf-section", title="Leaf")
def leaf(width: Width) -> CalculationResults:
value: Annotated[float, symbol(glyph="V", description="Value", unit="m")] = width
return {"value": value}
"""
)
(self.root / "wrapper.cso.py").write_text(
"""from typing import Annotated, TypeAlias
from cso_python import CalculationResults, calculation, method, section, symbol, table
from _cso_bindings.leaf import leaf
Width: TypeAlias = Annotated[float, symbol(glyph="w", description="Width", unit="m")]
@calculation(id="wrapper", title="Wrapper")
@section(id="wrapper-section", title="Wrapper")
def wrapper(width: Width) -> CalculationResults:
method(id="leaf-method", calculation=leaf, title="Leaf")
only = leaf(width=width)
table(id="inner", method="leaf-method", title="Inner", cases={"Only": only})
value: Annotated[float, symbol(glyph="V", description="Value", unit="m")] = only["value"]
return {"value": value}
"""
)
(self.root / "compare.cso.py").write_text("""from typing import Annotated
from cso_python import CalculationResults, calculation, method, section, symbol, table
from _cso_bindings.wrapper import wrapper
@calculation(id="compare", title="Outer comparison")
@section(id="comparison", title="Comparison", root=True)
def compare() -> CalculationResults:
method(id="wrap", calculation=wrapper, title="Wrapper")
first = wrapper(width=1.0)
table(id="outer", method="wrap", title="Outer", cases={"A": first})
ready: Annotated[float, symbol(glyph="r", description="Ready", unit="")] = 1
return {"ready": ready}
""")
generate(self.root)
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertFalse(response["ok"], response)
self.assertEqual(response["diagnostics"][0]["code"], "OVERLAPPING_TABLE")
self.assertTrue(
response["diagnostics"][0]["location"]["moduleId"].endswith(
"compare.cso.py"
),
response["diagnostics"][0],
)
run.assert_not_called()
def test_helper_source_edit_changes_the_dependency_hash(self):
self.write_composed(
""" method(id="panel-method", calculation=panel, title="How panel area is calculated")
first_panel = panel(width=2.0, height=3.0)
second_panel = panel(width=1.0, height=6.0)
table(id="panel-results", method="panel-method", title="Panel comparison", cases={"Case A": first_panel, "Case B": second_panel}, outputs=("area",))
"""
)
before = self.execution()["execution"]["methods"][0]["helpers"][0]["sourceHash"]
margin = self.root / "margin.cso.py"
margin.write_text(margin.read_text().replace("length + 1.0", "length + 2.0"))
after = self.execution()["execution"]["methods"][0]["helpers"][0]["sourceHash"]
self.assertNotEqual(before, after)
def _orientation_source(self, axis: str, count: int) -> str:
names = (
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
)[:count]
calls = "\n".join(
f" {name} = rectangle(width={index}.0, height=1.0)"
for index, name in enumerate(names, start=1)
)
mapping = ", ".join(f'"{name}": {name}' for name in names)
return f"""from typing import Annotated
from cso_python import CalculationResults, calculation, method, section, symbol, table
from _cso_bindings.rectangle import rectangle
@calculation(id="compare", title="Rectangle comparison")
@section(id="comparison", title="Comparison", root=True)
def compare() -> CalculationResults:
method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
{calls}
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={{{mapping}}}, inputs=("width",), outputs=("area", "perimeter"), cases_axis="{axis}")
ready: Annotated[float, symbol(glyph="r", description="Ready", unit="")] = 1
return {{"ready": ready}}
"""
def test_row_orientation_keeps_the_same_cell_inventory(self):
(self.root / "compare.cso.py").write_text(
self._orientation_source("columns", 12)
)
columns = self.execution()["execution"]
(self.root / "compare.cso.py").write_text(self._orientation_source("rows", 12))
rows = self.execution()["execution"]
self.assertEqual(columns["tables"][0]["casesAxis"], "columns")
self.assertEqual(rows["tables"][0]["casesAxis"], "rows")
self.assertEqual(rows["tables"][0]["cells"], columns["tables"][0]["cells"])
self.assertEqual(len(rows["tables"][0]["cells"]), 36)
self.assertEqual(
[item["function"] for item in rows["invocations"]],
[item["function"] for item in columns["invocations"]],
)
self.assertEqual(rows["methods"][0]["id"], columns["methods"][0]["id"])
area_cells = [
cell for cell in rows["tables"][0]["cells"] if cell["quantity"] == "area"
]
self.assertEqual(len({cell["symbolId"] for cell in area_cells}), 12)
def test_explicit_rows_selection_matches_columns(self):
body = """ method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
first_panel = rectangle(width=2.0, height=3.0)
second_panel = rectangle(width=1.0, height=6.0)
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={"Case A": first_panel, "Case B": second_panel}, inputs=(), outputs=("area",), cases_axis="AXIS")
"""
self.write_compare(body.replace("AXIS", "columns"))
columns = self.execution()["execution"]["tables"][0]
self.write_compare(body.replace("AXIS", "rows"))
rows = self.execution()["execution"]["tables"][0]
self.assertEqual(rows["cells"], columns["cells"])
self.assertEqual([cell["quantity"] for cell in rows["cells"]], ["area", "area"])
self.assertNotEqual(rows["cells"][0]["symbolId"], rows["cells"][1]["symbolId"])
def test_empty_row_table_does_not_invent_cases(self):
(self.root / "compare.cso.py").write_text("""from typing import Annotated
from cso_python import CalculationResults, calculation, method, section, symbol, table
from _cso_bindings.rectangle import rectangle
@calculation(id="compare", title="Rectangle comparison")
@section(id="comparison", title="Comparison", root=True)
def compare() -> CalculationResults:
method(id="rectangle-method", calculation=rectangle, title="How rectangle results are calculated")
table(id="rectangle-results", method="rectangle-method", title="Rectangle comparison", cases={}, cases_axis="rows")
ready: Annotated[float, symbol(glyph="r", description="Ready", unit="")] = 1
return {"ready": ready}
""")
execution = self.execution()["execution"]
self.assertEqual(
[item["function"] for item in execution["invocations"]], ["compare"]
)
self.assertEqual(execution["tables"][0]["casesAxis"], "rows")
self.assertEqual(execution["tables"][0]["cases"], [])
self.assertEqual(execution["tables"][0]["cells"], [])
def test_failed_check_keeps_the_number(self):
self.write_checked()
execution = self.execution()["execution"]
check = execution["methods"][0]["checks"][0]
self.assertEqual(check["predicateText"], "A <= 20")
self.assertEqual(check["explanation"], "Area exceeds 20 square metres.")
outcomes = [
item
for item in execution["checkOutcomes"]
if item["checkId"] == "area-limit"
]
self.assertEqual([item["value"] for item in outcomes], [True, False])
self.assertEqual(
[
symbol_result(execution, item["symbolId"])
for item in execution["tables"][0]["cells"]
if item["quantity"] == "area"
],
[6, 24],
)
def test_hidden_quantity_keeps_the_check(self):
self.write_checked(outputs="outputs=()")
execution = self.execution()["execution"]
self.assertEqual(execution["tables"][0]["outputs"], [])
self.assertEqual(len(execution["checkOutcomes"]), 4)
self.assertEqual(
[item["id"] for item in execution["methods"][0]["checks"]],
["area-limit", "perimeter-limit"],
)
def test_empty_cases_do_not_invent_check_outcomes(self):
self.write_checked(cases="{}")
execution = self.execution()["execution"]
self.assertEqual(execution["methods"][0]["checks"][0]["id"], "area-limit")
self.assertNotIn("checkOutcomes", execution)
def test_bare_check_predicate_is_diagnosed_before_execution(self):
self.write_checked()
path = self.root / "rectangle.cso.py"
path.write_text(
path.read_text().replace("predicate=area <= 20", "predicate=area")
)
generate(self.root)
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(response["diagnostics"][0]["code"], "UNSUPPORTED_SYNTAX")
run.assert_not_called()
def test_check_exception_stays_a_whole_run_failure(self):
self.write_checked()
path = self.root / "rectangle.cso.py"
path.write_text(
path.read_text().replace("predicate=area <= 20", "predicate=1 / 0 <= area")
)
generate(self.root)
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertFalse(response["ok"])
self.assertNotIn("execution", response)
self.assertNotIn("checkOutcomes", response)
def test_unknown_check_target_is_diagnosed_before_execution(self):
self.write_checked(target="volume")
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(response["diagnostics"][0]["code"], "UNKNOWN_QUANTITY")
run.assert_not_called()
def test_applicability_keeps_the_number(self):
self.write_applicable()
execution = self.execution()["execution"]
condition = execution["methods"][0]["applicability"][0]
self.assertEqual(condition["predicateText"], "A <= 20")
self.assertEqual(condition["explanation"], "Area exceeds the method limit.")
outcomes = execution["applicabilityOutcomes"]
self.assertEqual([item["value"] for item in outcomes], [True, False])
self.assertEqual(
[
symbol_result(execution, item["symbolId"])
for item in execution["tables"][0]["cells"]
if item["quantity"] == "area"
],
[6, 24],
)
def test_failed_check_does_not_create_applicability(self):
self.write_checked()
self.assertNotIn("applicabilityOutcomes", self.execution()["execution"])
def test_hidden_quantity_keeps_applicability(self):
self.write_applicable(outputs="outputs=()")
execution = self.execution()["execution"]
self.assertEqual(execution["tables"][0]["outputs"], [])
self.assertEqual(
[item["value"] for item in execution["applicabilityOutcomes"]],
[True, False],
)
def test_empty_cases_do_not_invent_applicability_outcomes(self):
self.write_applicable(cases="{}")
execution = self.execution()["execution"]
self.assertEqual(
execution["methods"][0]["applicability"][0]["id"], "area-limit"
)
self.assertNotIn("applicabilityOutcomes", execution)
def test_repeated_execution_records_the_same_applicability(self):
self.write_applicable()
first = execute(self.root / "compare.cso.py", "compare", {})
second = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(
first["execution"]["applicabilityOutcomes"],
second["execution"]["applicabilityOutcomes"],
)
def test_bare_applicability_predicate_is_diagnosed_before_execution(self):
self.write_applicable()
path = self.root / "rectangle.cso.py"
path.write_text(
path.read_text().replace("predicate=area <= 20", "predicate=area")
)
generate(self.root)
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(response["diagnostics"][0]["code"], "UNSUPPORTED_SYNTAX")
run.assert_not_called()
def test_applicability_exception_stays_a_whole_run_failure(self):
self.write_applicable()
path = self.root / "rectangle.cso.py"
path.write_text(
path.read_text().replace("predicate=area <= 20", "predicate=1 / 0 <= area")
)
generate(self.root)
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertFalse(response["ok"])
self.assertNotIn("execution", response)
self.assertNotIn("applicabilityOutcomes", response)
def test_unknown_applicability_target_is_diagnosed_before_execution(self):
self.write_applicable(target="volume")
with patch.object(Execution, "run") as run:
response = execute(self.root / "compare.cso.py", "compare", {})
self.assertEqual(response["diagnostics"][0]["code"], "UNKNOWN_QUANTITY")
run.assert_not_called()