-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_everything.py
More file actions
1464 lines (1288 loc) · 53.6 KB
/
Copy pathtest_everything.py
File metadata and controls
1464 lines (1288 loc) · 53.6 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
"""
PortusSIM self-test runner.
Programmatically exercises every major feature of the application
and reports green/red status. Run from the project root:
python test_everything.py
The tests run headlessly (no GUI window appears) and complete in under
a minute. A non-zero exit code indicates failures.
What's tested:
- Module imports
- Core simulation (default config, presets, seeds)
- Reproducibility (same seed = same results)
- 1D parameter sweep
- 2D parameter sweep with heatmap data
- Inequality metrics (Gini, top share)
- Custom layouts
- Generation/inheritance system
- Config save/load
- Summary export and reload for comparison
What's NOT tested:
- Visual layout (colors, fonts, alignment)
- Animations and transitions
- Theme switching
- Click handlers on widgets
For those, run the app and use the manual checklist in TESTING.md.
"""
import os
import sys
import json
import tempfile
import time
import copy
import traceback
# Colorized output
class C:
GREEN = "\033[92m"
RED = "\033[91m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
PASS = 0
FAIL = 0
FAILURES = []
def test(name):
"""Decorator that registers a test function."""
def decorator(fn):
def wrapped():
global PASS, FAIL
start = time.time()
try:
fn()
elapsed = time.time() - start
print(f" {C.GREEN}✓{C.RESET} {name} {C.DIM}({elapsed:.2f}s){C.RESET}")
PASS += 1
except AssertionError as e:
elapsed = time.time() - start
print(f" {C.RED}✗{C.RESET} {name} {C.DIM}({elapsed:.2f}s){C.RESET}")
print(f" {C.RED}{e}{C.RESET}")
FAIL += 1
FAILURES.append((name, str(e), None))
except Exception as e:
elapsed = time.time() - start
print(f" {C.RED}✗{C.RESET} {name} {C.DIM}({elapsed:.2f}s){C.RESET}")
tb = traceback.format_exc()
print(f" {C.RED}{type(e).__name__}: {e}{C.RESET}")
FAIL += 1
FAILURES.append((name, str(e), tb))
return wrapped
return decorator
def section(label):
print()
print(f"{C.BOLD}{C.BLUE}── {label} ──{C.RESET}")
# ============================================================================
# Tests
# ============================================================================
@test("All modules import cleanly")
def test_imports():
import simulation.engine
import simulation.world
import simulation.merchant
import simulation.town
import simulation.sweep
import simulation.metrics
import simulation.demographics
import data.config
import data.exporter
@test("Default config has required fields")
def test_default_config():
from data.config import DEFAULT_CONFIG
required = [
"num_elites", "num_middle", "num_poor",
"elite_starting_wealth", "middle_starting_wealth", "poor_starting_wealth",
"trust_max", "trust_increment", "market_pull",
"simulation_days", "num_runs",
]
for key in required:
assert key in DEFAULT_CONFIG, f"Missing key in DEFAULT_CONFIG: {key}"
@test("Single simulation runs and produces merchants")
def test_single_sim():
from simulation.engine import run_simulation
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 100
result = run_simulation(cfg)
assert "merchants" in result, "Result missing merchants"
assert len(result["merchants"]) > 0, "No merchants in result"
m = result["merchants"][0]
assert hasattr(m, "wealth"), "Merchant missing wealth attribute"
assert hasattr(m, "social_class"), "Merchant missing social_class"
assert hasattr(m, "history"), "Merchant missing history"
assert hasattr(m, "trusted_partners"), "Merchant missing trusted_partners"
@test("Reproducibility — same seed gives same result")
def test_reproducibility():
from simulation.engine import run_simulation
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 200
r1 = run_simulation(copy.deepcopy(cfg))
r2 = run_simulation(copy.deepcopy(cfg))
final1 = [m.wealth for m in r1["merchants"]]
final2 = [m.wealth for m in r2["merchants"]]
assert final1 == final2, f"Same seed produced different results: {final1[:3]} vs {final2[:3]}"
@test("Different seeds give different results")
def test_seed_variation():
from simulation.engine import run_simulation
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["simulation_days"] = 200
cfg["seed"] = 1
r1 = run_simulation(copy.deepcopy(cfg))
cfg["seed"] = 2
r2 = run_simulation(copy.deepcopy(cfg))
final1 = [m.wealth for m in r1["merchants"]]
final2 = [m.wealth for m in r2["merchants"]]
assert final1 != final2, "Different seeds should give different results"
@test("Multiple runs aggregation")
def test_multiple_runs():
from simulation.engine import run_multiple
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 100
results = run_multiple(cfg, 3)
assert len(results) == 3, f"Expected 3 results, got {len(results)}"
for r in results:
assert "merchants" in r
assert "config" in r
@test("Gini coefficient is computed correctly")
def test_gini():
from simulation.metrics import gini_coefficient
assert abs(gini_coefficient([10, 10, 10, 10])) < 0.001, "Equality should give Gini~0"
g = gini_coefficient([0, 0, 0, 100])
assert 0.7 < g < 0.8, f"Max inequality (n=4) should give Gini~0.75, got {g}"
assert gini_coefficient([]) == 0.0
assert gini_coefficient([5]) == 0.0
@test("Top-N share is computed correctly")
def test_top_share():
from simulation.metrics import top_share
assert abs(top_share([10, 10, 10, 10], 0.25) - 0.25) < 0.001
assert abs(top_share([0, 0, 0, 100], 0.25) - 1.0) < 0.001
@test("Summary metrics produces all expected keys")
def test_summary_metrics():
from simulation.engine import run_multiple
from simulation.metrics import summary_metrics
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 100
results = run_multiple(cfg, 2)
m = summary_metrics(results)
for key in ["gini", "top_10_share", "p90_p10_ratio", "gini_by_class"]:
assert key in m, f"summary_metrics missing key: {key}"
assert 0 <= m["gini"] <= 1, f"Gini out of range: {m['gini']}"
@test("1D parameter sweep runs and aggregates")
def test_1d_sweep():
from simulation.sweep import run_sweep, linspace
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 50
result = run_sweep(cfg, "trust_max", linspace(0, 0.3, 3), runs_per_value=2)
assert "results_by_value" in result
assert len(result["results_by_value"]) == 3
for v, stats in result["results_by_value"].items():
assert "elite" in stats
assert "bankruptcy_rate" in stats["elite"]
@test("2D parameter sweep runs and produces grid")
def test_2d_sweep():
from simulation.sweep import run_sweep_2d, linspace
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 50
result = run_sweep_2d(
cfg,
"trust_max", linspace(0, 0.2, 3),
"market_pull", linspace(0.3, 0.9, 2),
runs_per_cell=2,
)
assert "cells" in result
assert len(result["cells"]) == 2, f"Expected 2 Y rows, got {len(result['cells'])}"
assert len(result["cells"][0]) == 3, f"Expected 3 X cols"
# Each cell should be an aggregated stats dict
for row in result["cells"]:
for cell in row:
assert cell is not None
assert "elite" in cell
@test("All 5 presets load and have valid config")
def test_presets():
from data import exporter
from data.config import validate_config
presets_dir = exporter.get_presets_dir()
if not os.path.exists(presets_dir):
raise AssertionError(f"Presets dir not found: {presets_dir}")
files = sorted(f for f in os.listdir(presets_dir) if f.endswith(".json"))
assert len(files) >= 5, f"Expected ≥5 presets, found {len(files)}"
for f in files:
path = os.path.join(presets_dir, f)
cfg = exporter.load_config(path)
problems = validate_config(cfg)
errors = [m for sev, m in problems if sev == "error"]
assert not errors, f"Preset {f} has errors: {errors}"
@test("Save/load config round-trip preserves values")
def test_config_roundtrip():
from data import exporter
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 123
cfg["trust_max"] = 0.15
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
path = f.name
try:
exporter.save_config(cfg, path)
loaded = exporter.load_config(path)
assert loaded["seed"] == 123
assert abs(loaded["trust_max"] - 0.15) < 0.0001
finally:
os.unlink(path)
@test("Summary export and reload for comparison")
def test_summary_roundtrip():
from simulation.engine import run_simulation
from data import exporter
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 50
result = run_simulation(cfg)
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
path = f.name
try:
exporter.export_summary_json(result, path)
# Load it back for the comparison view
loaded_list = exporter.load_summary_for_comparison(path)
assert len(loaded_list) == 1
loaded = loaded_list[0]
assert "merchants" in loaded
assert "config" in loaded
# Final wealth should round-trip
original_final = sorted(m.wealth for m in result["merchants"])
loaded_final = sorted(m.wealth for m in loaded["merchants"])
assert original_final == loaded_final
finally:
os.unlink(path)
@test("Generations and inheritance produce next-generation merchants")
def test_generations():
from simulation.engine import run_simulation
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 200
cfg["generations_enabled"] = True
cfg["inheritance_fraction"] = 0.7
result = run_simulation(cfg)
# At least one merchant should have a non-1 generation OR a parent
gens = [getattr(m, "generation", 1) for m in result["merchants"]]
assert max(gens) >= 1, "Generation tracking missing"
@test("Custom layout grid validates and runs")
def test_custom_layout():
from simulation.engine import run_simulation
from simulation.world import RICH_NEIGHBORHOOD, POOR_NEIGHBORHOOD, MARKET, EMPTY
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 50
# Build a tiny custom layout
grid_size = cfg.get("grid_size", 12)
custom = [[EMPTY for _ in range(grid_size)] for _ in range(grid_size)]
# Place a market in the middle and a residential patch nearby
mid = grid_size // 2
custom[mid][mid] = MARKET
custom[0][0] = RICH_NEIGHBORHOOD
custom[grid_size - 1][grid_size - 1] = POOR_NEIGHBORHOOD
cfg["custom_layout"] = custom
result = run_simulation(cfg)
assert "merchants" in result
@test("Imports of all UI modules (no Qt window)")
def test_ui_imports():
# Make sure all UI modules can at least be imported without crashing.
# We don't construct widgets here (would need QApplication).
import importlib
modules = [
"ui.styles_v2",
"ui.design_system",
"ui.help_content",
"ui.sweep_2d_dialog",
"ui.worker",
"ui.v2.heatmap_view",
"ui.v2.trust_network_view",
"ui.v2.welcome_dialog",
"ui.v2.comparison_view",
"ui.v2.results_sidebar",
"ui.v2.chart_canvas",
"ui.v2.parameters_panel",
"ui.v2.single_run_view",
"ui.v2.sweep_view",
"ui.v2.top_nav",
"ui.v2.main_window",
"ui.v2.animations",
]
for mod in modules:
importlib.import_module(mod)
@test("App icon files exist at all required sizes")
def test_logo_assets():
sizes = [16, 24, 32, 48, 64, 128, 256, 512]
for s in sizes:
path = f"assets/logo/portussim_mark_{s}.png"
assert os.path.exists(path), f"Missing logo: {path}"
path_white = f"assets/logo/portussim_mark_white_{s}.png"
assert os.path.exists(path_white), f"Missing white logo: {path_white}"
@test("Inter font bundle exists")
def test_font_bundle():
path = "assets/fonts/Inter-Variable.ttf"
assert os.path.exists(path), f"Missing font: {path}"
size = os.path.getsize(path)
assert size > 100_000, f"Font file too small ({size} bytes), likely corrupt"
@test("Summary report builds HTML for typical run")
def test_summary_report():
from simulation.engine import run_multiple
from simulation.summary_report import build_summary_html
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 100
results = run_multiple(cfg, 2)
html = build_summary_html(results, theme="light")
assert "<style>" in html
assert "Interpretation" in html
assert "Configuration" in html
assert "Comparison to bundled findings" in html
# Should classify into one of the trust regimes
assert any(label in html for label in [
"near-zero trust", "cliff zone", "moderate trust", "high trust"
])
# Should mention all four findings
assert "Finding 1" in html
assert "Finding 2" in html
assert "Finding 3" in html
assert "Finding 4" in html
@test("Summary report classifies high-trust regime as elite collapse")
def test_summary_classification_high_trust():
from simulation.engine import run_multiple
from simulation.summary_report import build_summary_html
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 200
cfg["trust_max"] = 0.3 # high trust
results = run_multiple(cfg, 2)
html = build_summary_html(results, theme="light")
# High trust should produce elite collapse
assert "Elite class collapse" in html or "Elite class is unstable" in html, \
"High-trust regime should classify elite as collapsing or unstable"
assert "high trust" in html, "Should identify high-trust regime"
@test("Historical comparison data is well-formed")
def test_historical_data():
from simulation.historical_comparisons import (
HISTORICAL_GINI_REFERENCES, find_gini_comparisons, COMPARISON_CAVEAT
)
assert len(HISTORICAL_GINI_REFERENCES) >= 8, "Should have at least 8 references"
for ref in HISTORICAL_GINI_REFERENCES:
assert "place" in ref
assert "period" in ref
assert "gini" in ref and 0 <= ref["gini"] <= 1, f"Bad Gini for {ref.get('place')}"
assert "citation" in ref and ref["citation"], f"Missing citation for {ref.get('place')}"
assert "measure" in ref and ref["measure"] in ("income", "wealth")
assert len(COMPARISON_CAVEAT) > 100
@test("find_gini_comparisons returns sensible matches across regimes")
def test_gini_comparisons_match():
from simulation.historical_comparisons import find_gini_comparisons
low = find_gini_comparisons(0.27, top_n=3)
assert "Sweden" in low[0][0]["place"], f"Expected Sweden as closest to 0.27, got {low[0][0]['place']}"
mid = find_gini_comparisons(0.43, top_n=3, prefer_period_match="ancient")
assert any("Roman Empire" in r[0]["place"] for r in mid[:2]), \
"Roman Empire should be in top 2 matches for Gini 0.43 with ancient preference"
@test("Summary report includes historical context section")
def test_summary_includes_historical():
from simulation.engine import run_multiple
from simulation.summary_report import build_summary_html
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 42
cfg["simulation_days"] = 100
results = run_multiple(cfg, 2)
html = build_summary_html(results, theme="light")
assert "Historical context" in html
assert "Scheidel" in html or "Alfani" in html or "Kron" in html, \
"Summary should cite at least one historical source"
assert "illustrative, not calibrated" in html
@test("Debug log collector captures entries with severity levels")
def test_debug_log():
from ui.v2.debug_log import LOG
LOG.clear()
LOG.info("Test info entry", context_key=42)
LOG.warn("Test warning")
LOG.error("Test error")
entries = LOG.entries()
assert len(entries) == 3, f"Expected 3 entries, got {len(entries)}"
assert entries[0]["level"] == "INFO"
assert entries[1]["level"] == "WARN"
assert entries[2]["level"] == "ERROR"
assert entries[0]["context"]["context_key"] == 42
LOG.clear()
assert len(LOG.entries()) == 0
@test("Debug log handles exception with traceback")
def test_debug_log_exception():
from ui.v2.debug_log import LOG
LOG.clear()
try:
raise ValueError("intentional test exception")
except Exception:
LOG.exception("Caught test exception")
entries = LOG.entries()
assert len(entries) == 1
assert entries[0]["level"] == "ERROR"
assert "traceback" in entries[0]["context"]
assert "ValueError" in entries[0]["context"]["traceback"]
@test("Animated stat card survives back-to-back updates (regression)")
def test_stat_card_back_to_back():
"""Regression test for the RuntimeError users hit when running two
simulations in quick succession. After the first animation finished,
its underlying C++ QVariantAnimation was deleted by Qt, but the Python
reference remained — calling .stop() on it raised RuntimeError and
left the UI stuck on 'Running...'."""
# Needs a QApplication, but can run headless
import os as _os
_os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import QEventLoop, QTimer
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([])
from ui.v2.results_sidebar import StatCard
card = StatCard("Test", "—", "")
# First animated update
card.set_value_animated(40.0,
formatter=lambda v: f"{v:.1f}%",
subtitle="2 of 5",
duration_ms=50)
# Wait for animation to finish AND for DeleteWhenStopped to delete the
# underlying C++ object
loop = QEventLoop()
QTimer.singleShot(300, loop.quit)
loop.exec()
# Second update — this used to crash with RuntimeError
card.set_value_animated(80.0,
formatter=lambda v: f"{v:.1f}%",
subtitle="4 of 5",
duration_ms=50)
# Should not have raised
@test("Inheritance fraction is now a sweepable parameter")
def test_inheritance_in_sweep():
from simulation.sweep import SWEEPABLE_PARAMETERS
assert "inheritance_fraction" in SWEEPABLE_PARAMETERS
assert "middle_starting_wealth" in SWEEPABLE_PARAMETERS
assert "poor_starting_wealth" in SWEEPABLE_PARAMETERS
@test("Sweep produces per-seed records for CSV export")
def test_sweep_per_seed_records():
from simulation.sweep import run_sweep
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 9000
cfg["generations_enabled"] = True
cfg["simulation_days"] = 100
result = run_sweep(cfg, "inheritance_fraction", [0.0, 0.5, 1.0],
runs_per_value=2)
records = result["per_run_records"]
assert len(records) == 6, f"Expected 6 records (3 values × 2 seeds), got {len(records)}"
# Each record has the expected fields
for r in records:
assert "seed" in r and r["seed"] is not None
assert "parameter_value" in r
assert "gini" in r and 0 <= r["gini"] <= 1
assert "elite_bk_pct" in r
assert "middle_bk_pct" in r
assert "poor_bk_pct" in r
# Seeds should be unique
seeds = [r["seed"] for r in records]
assert len(set(seeds)) == len(seeds), "Seeds should be unique across runs"
@test("Per-seed CSV export produces valid file")
def test_per_seed_csv_export():
from simulation.sweep import run_sweep
from data.exporter import export_sweep_per_run_csv
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 9100
cfg["generations_enabled"] = True
cfg["simulation_days"] = 100
result = run_sweep(cfg, "inheritance_fraction", [0.0, 1.0], runs_per_value=2)
import tempfile as _t
with _t.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
path = f.name
try:
export_sweep_per_run_csv(result, filename=path)
with open(path) as f:
content = f.read()
# 1 header line + 4 data rows
lines = content.strip().split("\n")
assert len(lines) == 5, f"Expected 5 lines (header + 4 rows), got {len(lines)}"
assert "gini" in lines[0]
assert "seed" in lines[0]
assert "elite_bk_pct" in lines[0]
finally:
os.unlink(path)
@test("Configure New Sweep button wiring (regression)")
def test_configure_sweep_wiring():
"""Three bugs once lived here:
1. SweepDialog was called with base_config= but doesn't accept it
2. Caller used dialog.get_sweep_config(), which doesn't exist
3. sweep_view.display_results() called sweep_results.display_results(),
but the panel method is display_sweep()
Each was silently swallowed by Qt's signal-slot machinery, making
the Configure New Sweep button appear to do nothing.
"""
import os as _os
_os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([])
# Bug 1: SweepDialog must accept being called with just (parent)
from ui.sweep_dialog import SweepDialog
dlg = SweepDialog(None)
# Bug 2: it must expose parameter(), values(), runs_per_value()
assert hasattr(dlg, "parameter") and callable(dlg.parameter)
assert hasattr(dlg, "values") and callable(dlg.values)
assert hasattr(dlg, "runs_per_value") and callable(dlg.runs_per_value)
# Bug 3: sweep_view.display_results must work
from ui.v2.sweep_view import SweepView
sv = SweepView()
assert hasattr(sv.sweep_results, "display_sweep"), \
"sweep panel must expose display_sweep"
@test("Help content includes Reproducibility section about Python versions")
def test_reproducibility_help():
from ui import help_content
assert hasattr(help_content, "REPRODUCIBILITY"), \
"REPRODUCIBILITY help section should exist"
text = help_content.REPRODUCIBILITY
assert "Python version" in text
assert "randint" in text
assert "random()" in text
# Should explicitly mention that random.random is the stable one
assert "stable" in text.lower() or "guarantee" in text.lower()
@test("Scenario save / load round-trip preserves config and metadata")
def test_scenario_round_trip():
from data.scenario import (
build_scenario, save_scenario, load_scenario,
extract_config, extract_metadata,
)
from data.config import DEFAULT_CONFIG
import tempfile as _t, os as _os
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 4321
cfg["trust_max"] = 0.123
scenario = build_scenario(
cfg,
name="Test scenario",
description="A description.",
author="Test Author",
historical_period="Roman Imperial",
tags=["test", "demo"],
citation="Author (2026)",
)
with _t.NamedTemporaryFile(mode="w", suffix=".scenario", delete=False) as f:
path = f.name
try:
save_scenario(scenario, path)
loaded, was_scenario = load_scenario(path)
assert was_scenario, "Should detect new format"
cfg2 = extract_config(loaded)
meta2 = extract_metadata(loaded)
assert cfg2["seed"] == 4321
assert abs(cfg2["trust_max"] - 0.123) < 1e-9
assert meta2["name"] == "Test scenario"
assert meta2["author"] == "Test Author"
assert meta2["historical_period"] == "Roman Imperial"
assert meta2["tags"] == ["test", "demo"]
assert "python_version" in meta2
finally:
_os.unlink(path)
@test("Scenario loader handles legacy config files (backward compat)")
def test_scenario_legacy_compat():
from data.scenario import load_scenario, extract_config
from data.config import DEFAULT_CONFIG
import tempfile as _t, os as _os, json as _j
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 9999
with _t.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
path = f.name
_j.dump(cfg, f)
try:
loaded, was_scenario = load_scenario(path)
assert not was_scenario, "Legacy config should not be detected as new format"
cfg2 = extract_config(loaded)
assert cfg2["seed"] == 9999
finally:
_os.unlink(path)
@test("Save scenario dialog metadata extraction")
def test_scenario_dialog_metadata():
import os as _os
_os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([])
from ui.scenario_dialog import SaveScenarioDialog
dlg = SaveScenarioDialog()
dlg.name_edit.setText("My Scenario")
dlg.description_edit.setPlainText("A description.")
dlg.author_edit.setText("Author")
dlg.period_combo.setCurrentText("Roman Imperial")
dlg.tags_edit.setText("a, b, c")
meta = dlg.metadata()
assert meta["name"] == "My Scenario"
assert meta["description"] == "A description."
assert meta["author"] == "Author"
assert meta["historical_period"] == "Roman Imperial"
assert meta["tags"] == ["a", "b", "c"]
@test("ScenarioInfoDialog accepts long descriptions without breaking layout")
def test_scenario_info_dialog():
import os as _os
_os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([])
from ui.scenario_dialog import ScenarioInfoDialog
long_desc = "Lorem ipsum dolor sit amet. " * 50 # ~1500 chars
dlg = ScenarioInfoDialog(
None,
name="Test scenario",
description=long_desc,
author="Author",
historical_period="Roman Imperial",
tags=["a", "b"],
citation="Author (2026)",
python_version="3.13.9",
portussim_version="1.0",
created="2026-06-06T14:30:00+00:00",
)
# The dialog should be fixed-width, NOT expand with a very long string
assert dlg.size().width() < 800, \
"Dialog width should be capped (was the QMessageBox bug)"
assert dlg.size().height() < 800
# from_metadata should work too
dlg2 = ScenarioInfoDialog.from_metadata(None, {
"name": "X", "description": "Y", "author": "Z",
"historical_period": "", "tags": [], "citation": "",
"python_version": "", "portussim_version": "", "created": "",
})
assert dlg2 is not None
@test("Top nav Scenario button enables/disables on demand")
def test_top_nav_scenario_button():
import os as _os
_os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([])
from ui.v2.top_nav import TopNavBar
nav = TopNavBar()
assert not nav.scenario_btn.isEnabled(), \
"Scenario button should start disabled"
nav.set_scenario_active("Test scenario name")
assert nav.scenario_btn.isEnabled()
assert "Test scenario name" in nav.scenario_btn.toolTip()
nav.set_scenario_active(None)
assert not nav.scenario_btn.isEnabled()
@test("Time-series long-format export produces tidy CSV")
def test_time_series_long_export():
from simulation.engine import run_multiple
from data.exporter import export_time_series_long
from data.config import DEFAULT_CONFIG
import tempfile as _t, os as _os
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 100
cfg["simulation_days"] = 10
results = run_multiple(cfg, 1)
with _t.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
path = f.name
try:
export_time_series_long(results, path)
with open(path) as f:
lines = f.read().strip().split("\n")
# Provenance lines start with #
provenance = [l for l in lines if l.startswith("#")]
data = [l for l in lines if not l.startswith("#")]
# Header + N merchants * (days+1) rows
n_merchants = len(results[0]["merchants"])
expected_data_rows = 1 + n_merchants * 11 # header + each day 0..10
assert len(provenance) >= 7, f"Need provenance header, got {len(provenance)}"
assert len(data) == expected_data_rows, \
f"Expected {expected_data_rows} data rows, got {len(data)}"
# Header check
header = data[0]
for col in ("run", "day", "merchant_id", "social_class", "wealth"):
assert col in header
# Python version recorded
assert any("python_version" in p for p in provenance)
finally:
_os.unlink(path)
@test("Time-series wide-format export has one column per merchant")
def test_time_series_wide_export():
from simulation.engine import run_multiple
from data.exporter import export_time_series_wide
from data.config import DEFAULT_CONFIG
import tempfile as _t, os as _os
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 100
cfg["simulation_days"] = 5
results = run_multiple(cfg, 1)
with _t.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
path = f.name
try:
export_time_series_wide(results, path)
with open(path) as f:
lines = f.read().strip().split("\n")
data = [l for l in lines if not l.startswith("#")]
header_cols = data[0].split(",")
n_merchants = len(results[0]["merchants"])
# run + day + N merchants
assert len(header_cols) == n_merchants + 2, \
f"Wide format header should have run + day + {n_merchants} merchants"
# Each merchant name in the header
names = {m.name for m in results[0]["merchants"]}
for name in names:
assert name in header_cols, f"Merchant {name} missing from header"
finally:
_os.unlink(path)
@test("Events export captures trade events")
def test_events_export():
from simulation.engine import run_multiple
from data.exporter import export_events
from data.config import DEFAULT_CONFIG
import tempfile as _t, os as _os
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 100
cfg["simulation_days"] = 50 # need enough days for trades to happen
results = run_multiple(cfg, 1)
with _t.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
path = f.name
try:
export_events(results, path)
with open(path) as f:
lines = f.read().strip().split("\n")
data = [l for l in lines if not l.startswith("#")]
# At minimum should have header + some trade events
assert len(data) > 1, "Should have at least one trade event"
header_cols = data[0].split(",")
for col in ("run", "event_type", "day", "source", "target"):
assert col in header_cols, f"Missing column: {col}"
finally:
_os.unlink(path)
@test("Sweep file save/load round trip preserves all key data")
def test_sweep_file_round_trip():
from simulation.sweep import run_sweep
from data.sweep_file import build_sweep_file, save_sweep_file, load_sweep_file
from data.config import DEFAULT_CONFIG
import tempfile as _t, os as _os
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 100
cfg["simulation_days"] = 50
sweep = run_sweep(cfg, "trust_max", [0.05, 0.1], runs_per_value=3)
sweep_file = build_sweep_file(sweep, cfg, name="Test", author="Tester")
with _t.NamedTemporaryFile(mode="w", suffix=".sweep", delete=False) as f:
path = f.name
try:
save_sweep_file(sweep_file, path)
loaded = load_sweep_file(path)
assert loaded["parameter"] == "trust_max"
assert loaded["values"] == [0.05, 0.1]
assert len(loaded["per_run_records"]) == 6
assert loaded["metadata"]["name"] == "Test"
assert loaded["metadata"]["author"] == "Tester"
assert "python_version" in loaded["metadata"]
# base_config preserved
assert loaded["base_config"]["seed"] == 100
finally:
_os.unlink(path)
@test("Sweep comparison detects significant differences")
def test_sweep_comparison():
from simulation.sweep import run_sweep
from data.sweep_file import build_sweep_file
from simulation.sweep_compare import compare_sweeps
from data.config import DEFAULT_CONFIG
cfg_a = copy.deepcopy(DEFAULT_CONFIG)
cfg_a["seed"] = 200
cfg_a["simulation_days"] = 100
sweep_a = run_sweep(cfg_a, "trust_max", [0.05, 0.15], runs_per_value=5)
file_a = build_sweep_file(sweep_a, cfg_a, name="A")
# B is a copy of A with a different starting seed — should give slightly different
cfg_b = copy.deepcopy(cfg_a)
cfg_b["seed"] = 500
sweep_b = run_sweep(cfg_b, "trust_max", [0.05, 0.15], runs_per_value=5)
file_b = build_sweep_file(sweep_b, cfg_b, name="B")
result = compare_sweeps(file_a, file_b, metric_key="gini")
assert result["comparable"], "Same parameter should be comparable"
assert result["parameter"] == "trust_max"
assert len(result["rows"]) == 2 # two shared values
for row in result["rows"]:
assert row["a_n"] == 5
assert row["b_n"] == 5
assert row["t"] is not None
assert row["p"] is not None
@test("Sweep comparison flags non-comparable sweeps")
def test_sweep_comparison_incompatible():
from simulation.sweep import run_sweep
from data.sweep_file import build_sweep_file
from simulation.sweep_compare import compare_sweeps
from data.config import DEFAULT_CONFIG
cfg = copy.deepcopy(DEFAULT_CONFIG)
cfg["seed"] = 100
cfg["simulation_days"] = 50
sweep_a = run_sweep(cfg, "trust_max", [0.05, 0.1], runs_per_value=2)
sweep_b = run_sweep(cfg, "market_pull", [0.5, 0.7], runs_per_value=2)
file_a = build_sweep_file(sweep_a, cfg, name="A")
file_b = build_sweep_file(sweep_b, cfg, name="B")
result = compare_sweeps(file_a, file_b)
assert not result["comparable"]
assert "different parameters" in result["verdict"].lower()
@test("Compare view: table allows selection (regression — was NoSelection)")
def test_compare_view_table_selectable():
import os as _os
_os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication, QAbstractItemView
app = QApplication.instance() or QApplication([])
from ui.v2.sweep_compare_view import SweepCompareView
v = SweepCompareView()
mode = v.table.selectionMode()
assert mode != QAbstractItemView.SelectionMode.NoSelection, \
"Table must allow selection so users can copy"
@test("Compare view: slots accept apply_theme without errors")
def test_compare_view_slot_theme():
import os as _os
_os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([])
from ui.v2.sweep_compare_view import SweepSlot
slot = SweepSlot("a", "#0969DA", theme_name="light")
# Switching themes shouldn't crash and should change stylesheets
sheet_before = slot.title_label.styleSheet()
slot.apply_theme("dark")
sheet_after = slot.title_label.styleSheet()
assert sheet_before != sheet_after, "Title label stylesheet must change with theme"
@test("Compare view table copy produces tab-separated text")
def test_compare_view_table_copy():
import os as _os
_os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication, QTableWidgetItem
app = QApplication.instance() or QApplication([])
from ui.v2.sweep_compare_view import SweepCompareView
v = SweepCompareView()
v.table.setRowCount(2)
v.table.setItem(0, 0, QTableWidgetItem("0.05"))
v.table.setItem(0, 1, QTableWidgetItem("0.371"))
v.table.setItem(0, 2, QTableWidgetItem("0.447"))
v.table.setItem(0, 3, QTableWidgetItem("0.001 *"))
v.table.selectRow(0)
v._copy_selection()
clip = app.clipboard().text()
assert "\t" in clip
assert "0.05" in clip
assert "0.001 *" in clip
@test("Hypothesis test: clear-cut SUPPORTED case")
def test_hypothesis_supported():
from simulation.hypothesis import Hypothesis, run_test, DIRECTION_GT
h = Hypothesis(
name="H1",
condition_a_label="A", condition_b_label="B",