191 build - поправлены старые падения, проверены 3 матча и 6 агентов одновременных
This commit is contained in:
442
BUILD191_FILES.json
Normal file
442
BUILD191_FILES.json
Normal file
@@ -0,0 +1,442 @@
|
||||
{
|
||||
"build": "2026.10.21.2",
|
||||
"base": "2026.10.02.9",
|
||||
"includes": [
|
||||
"BUILD190",
|
||||
"BUILD191"
|
||||
],
|
||||
"files": [
|
||||
{
|
||||
"path": ".gitignore",
|
||||
"sha256": "d0e4125cc77ffb6fe131f51a63ef891e283c8ec752f0190171ce1ea0ffe6c3e0",
|
||||
"bytes": 2700
|
||||
},
|
||||
{
|
||||
"path": "BUILD190_FILES.json",
|
||||
"sha256": "f979a8156e98fd6dd80343af5663c66f8289865696ba4d07d7f85bfe3bc3079a",
|
||||
"bytes": 7141
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"sha256": "966ab98ed778d16dcba6142478aaa2f60d16439384951dec5a3fe6f09ba7ca57",
|
||||
"bytes": 2214
|
||||
},
|
||||
{
|
||||
"path": "UPDATE.txt",
|
||||
"sha256": "b18d17f9153eb315916c2aeae5e644c0a6529ad6f3b9ed461254e3273fc5b920",
|
||||
"bytes": 4245
|
||||
},
|
||||
{
|
||||
"path": "app.py",
|
||||
"sha256": "190701c5a8bed4aa3c8989465e3c574539e908077f7f07a5e1a12c4c2a5059ae",
|
||||
"bytes": 29271
|
||||
},
|
||||
{
|
||||
"path": "cleanup_project.py",
|
||||
"sha256": "8376ff02ee0e945dec90583f37908a33206f65426ddd2f5052e50fc095bdb895",
|
||||
"bytes": 8926
|
||||
},
|
||||
{
|
||||
"path": "deploy.sh",
|
||||
"sha256": "233ee1f9781344a4323d82f4ce2f6caf08078c235331ff16a60eaf680dbf7770",
|
||||
"bytes": 214
|
||||
},
|
||||
{
|
||||
"path": "docs/ADMIN.md",
|
||||
"sha256": "d65ac23a22eebc7306b7317bf12999bd4da0a2ba3e0ed68d96ae49dcd42f106c",
|
||||
"bytes": 12600
|
||||
},
|
||||
{
|
||||
"path": "docs/ARCHITECTURE.md",
|
||||
"sha256": "072ad6fa37d6ecd107f07fc9629f889709b9378f51f7079b6bfb2e9acad8ff93",
|
||||
"bytes": 6395
|
||||
},
|
||||
{
|
||||
"path": "docs/CHANGELOG.md",
|
||||
"sha256": "87d4933d303a956ccf1e09c4d5b9f6954806c7d1f1d8cafcec6aa1dfe9248974",
|
||||
"bytes": 8038
|
||||
},
|
||||
{
|
||||
"path": "docs/OPERATOR.md",
|
||||
"sha256": "da638c75f39d62c6c58ad58cd7aec4752f5942227feb0111ef195ad4cd42cd56",
|
||||
"bytes": 10013
|
||||
},
|
||||
{
|
||||
"path": "docs/history.zip",
|
||||
"sha256": "a7e454514a9b1b5258c8794cfa3921913151f2090cf5d1d9eca22ccbe747f766",
|
||||
"bytes": 132008
|
||||
},
|
||||
{
|
||||
"path": "docs/validation.json",
|
||||
"sha256": "e7e7a1bddf22c36e8b32f01c99654ca067bf833df6436984c7e1ccdf9989b6d3",
|
||||
"bytes": 70078
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/agent_bridge.py",
|
||||
"sha256": "01cece7c71b7a81160130f171de208def76e2e9cd9bf6e707638e0dbca333ae3",
|
||||
"bytes": 327505
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/auth_bridge.py",
|
||||
"sha256": "2fb09b52f71352aaf61988b13dfc36fa17116376d33c272013ac69b7ba1dbc1f",
|
||||
"bytes": 15480
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/auth_router.py",
|
||||
"sha256": "c13e3339af6bf7ca31449cf980ba5d6e03068663f28badd75d96ecbb77c6d05e",
|
||||
"bytes": 9201
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/client.py",
|
||||
"sha256": "bcee5981010b445d8173f6a08054c248dd2cf6b892170331afa8febef34678a6",
|
||||
"bytes": 4419
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/match_access.py",
|
||||
"sha256": "90d11f2eeefd3a4048648c6266b8b79afcbe0fa2dd678fa3093c698afbe701d5",
|
||||
"bytes": 32637
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/models.py",
|
||||
"sha256": "b6a92c2f150c04eec21146501a1ddc28fd1b9e3d6bf644e1cdd7fd9520c1611e",
|
||||
"bytes": 79958
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/program_log.py",
|
||||
"sha256": "53f67011c495036e352d195aba2bb33fa9243e72084b5f5da9e05a246e299016",
|
||||
"bytes": 27225
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/program_log_router.py",
|
||||
"sha256": "a1bd17416a6c2391a6c5edebd0ca392a22f8b1da61828bfae3d0392dbef25f0f",
|
||||
"bytes": 3184
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/service.py",
|
||||
"sha256": "d6e3d0d8cf0de1ca2b6ed35941cdfe784b52d948512c95bfd8a132a45c133fba",
|
||||
"bytes": 419779
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/snapshot_storage.py",
|
||||
"sha256": "1b09601bd2c25387e032ea12526bd8e4cef0fb11f1efd1223a4ba8386382e824",
|
||||
"bytes": 2148
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/static/admin-directories.js",
|
||||
"sha256": "dcdb45ef248ea0c6f613556e710e8656badcb3875529efb8c1d42c0eec02ffe1",
|
||||
"bytes": 302120
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/static/client-performance.js",
|
||||
"sha256": "ecc9df717aa5df5130d50b24c26f4af3679b74ea938a3ed85211bd2c4cf862a3",
|
||||
"bytes": 3138
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/static/program-log.css",
|
||||
"sha256": "25557fcb942d6e8c874f43ac0f145f1eae800d11e99593eee4cee7e3aa964c8f",
|
||||
"bytes": 7589
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/static/program-log.js",
|
||||
"sha256": "d6676a4c00380ce88c74ce6c8267098f5ffca3371fec4a97665a4aeff7b7d1a8",
|
||||
"bytes": 24733
|
||||
},
|
||||
{
|
||||
"path": "hockey_data/web_observability.py",
|
||||
"sha256": "486de25f8461b2d6576f33ff765584bd6cd8cae257b048c17482840aa229bbec",
|
||||
"bytes": 13770
|
||||
},
|
||||
{
|
||||
"path": "khl_site/khl_data_center.py",
|
||||
"sha256": "b51871d647ed6a1e1e2a97f5bb7450c1aa47cf9fbc4b4172c5bb6f387b0fb635",
|
||||
"bytes": 55045
|
||||
},
|
||||
{
|
||||
"path": "requirements.txt",
|
||||
"sha256": "bddefda981e4fa23e6de55be1dfbe6f2590f49c488dd737741db804c8984950c",
|
||||
"bytes": 242
|
||||
},
|
||||
{
|
||||
"path": "settings/README.md",
|
||||
"sha256": "d27d9d50e73c1d5acafb1cf412cb1812a6988f15b4da1c69ae1f167183db6b4c",
|
||||
"bytes": 866
|
||||
},
|
||||
{
|
||||
"path": "tests/hotfix_penalty_visibility.cjs",
|
||||
"sha256": "fbd8f826e901621859716ad65f6312a1c8c961d9fe82b43db5e19384eefe3b3a",
|
||||
"bytes": 9083
|
||||
},
|
||||
{
|
||||
"path": "tests/multi_match_harness.py",
|
||||
"sha256": "388c6f1f447a3b36dcf7a841a5c70f02ccfd4c4a0138cde1c335beab8488100e",
|
||||
"bytes": 40120
|
||||
},
|
||||
{
|
||||
"path": "tests/program_log_browser.cjs",
|
||||
"sha256": "2dd38a1fcf8bc9ed341dc29c274cf8d0fd2128bc3d80e919bc39e0bdd5bf67b4",
|
||||
"bytes": 8696
|
||||
},
|
||||
{
|
||||
"path": "tests/program_log_frontend.cjs",
|
||||
"sha256": "9c394c7e3c6dbe468f4d36933d6267cbfb0dbba11b529c79440fbc977fa05505",
|
||||
"bytes": 2328
|
||||
},
|
||||
{
|
||||
"path": "tests/runtime_timer_contracts.cjs",
|
||||
"sha256": "8582edb66e7002515f8e4f8691674dd8f8c331b52f0262357c010253494779d6",
|
||||
"bytes": 21849
|
||||
},
|
||||
{
|
||||
"path": "tests/runtime_timer_transport.cjs",
|
||||
"sha256": "c9291c28982f1ff861b00ae2c23376f150f7e5d24fddfeb1a656d3bf892fbc13",
|
||||
"bytes": 15417
|
||||
},
|
||||
{
|
||||
"path": "tests/test_agent_bridge.py",
|
||||
"sha256": "c0d3e563a48f1803db4afb5a3a308973a094f4d2f44b3863c6c28865e835b798",
|
||||
"bytes": 34276
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build101_simple_timer_runtime.py",
|
||||
"sha256": "15dcb9bab6c3b27cdcccf01c8bfb732cbf77a3a9b3380067eb18a5cefab35962",
|
||||
"bytes": 1449
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build103_space_timer_fast_transport.py",
|
||||
"sha256": "2c475c7ea8e28e0d53723c84d042dec4fede3f8cb4ec3a5c05daad23a47e875c",
|
||||
"bytes": 5047
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build104_timer_stop_no_rollback.py",
|
||||
"sha256": "5242c3769449348b3e9e55cce2367ead178cc6ab3194a5ad188b0c5ab69b3d45",
|
||||
"bytes": 1047
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build105_suspend_countdown_pause.py",
|
||||
"sha256": "7e3c098b2fbeaf145a0220fc7a00ffcaac634e7b6be94a40e1e22f1bd0f63616",
|
||||
"bytes": 1051
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build106_runtime_authoritative_timer.py",
|
||||
"sha256": "7a86b6e35bf15be01c55a53972afaf69947cc39009cc699febf6cfd118b974bc",
|
||||
"bytes": 3977
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build107_pause_change_countdown.py",
|
||||
"sha256": "40d5939a69ab8db155f7abb8ace9c66dda381feca7428f6c23c131c9a69b889b",
|
||||
"bytes": 1161
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build108_native_pause_no_resync.py",
|
||||
"sha256": "6eb175812f75c64d4a1bccaa7fed6ee25a0c82cc8acec76abfbf15059ae5f3c4",
|
||||
"bytes": 1253
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build110_match_roster_atomic_switch.py",
|
||||
"sha256": "c4e4e3c25a0624c8623a2a2ba5226ce5db7714d68b8699727476042c87c612eb",
|
||||
"bytes": 1975
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build111_agent_match_handoff.py",
|
||||
"sha256": "c28248e1b4faa9a78f3ab4e3081a7ffa6d0f8cb8e365e52f58374299613be720",
|
||||
"bytes": 3593
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build190_mapping_delivery.py",
|
||||
"sha256": "5c108ea9701fa9ec76df1009a8a688bd1746a8bcc1d2686d16f4bb8df011da77",
|
||||
"bytes": 13334
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build44_strength_vmix_sync.py",
|
||||
"sha256": "6d09821a237ca6205f8dfba200468fb45b9241e2edf8c4bbca65baedca51b621",
|
||||
"bytes": 1648
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build47_team_state_scoreboard_overlays.py",
|
||||
"sha256": "00629a64af079ad365185a36f99abebfb7a7f64e1907677f2c48676828cbdefc",
|
||||
"bytes": 2268
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build48_broadcast_states.py",
|
||||
"sha256": "edefc5c8205b3f0ca012f38b2217fde782b7d88ae9e70c128f9db3ed284dac11",
|
||||
"bytes": 4484
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build55_agent_and_account_events.py",
|
||||
"sha256": "8e2ec9426d37757d5055c84dce4e59fea0093c1709161fca449657a972df1d7b",
|
||||
"bytes": 2479
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build56_trigger_save_onair.py",
|
||||
"sha256": "24a985ccea0fa6f23598e854a122aeb274d55cc408f45fcd74bd64755f9663e7",
|
||||
"bytes": 1134
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build57_quick_panel_parameters.py",
|
||||
"sha256": "cfb79c3f0c20eabee6b2e160d1432da8877e3bbb90d3d272d1ffcc7884c55a64",
|
||||
"bytes": 3556
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build58_onair_target_matching.py",
|
||||
"sha256": "1172386e7ab3d91e22b88dcf3d884c52710ced85b3cb65b6fc2a0dda5de9658b",
|
||||
"bytes": 1133
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build59_toasts_and_adaptive_runtime.py",
|
||||
"sha256": "3273d58e9443d6a3a61f0954991af2b7c79617fa38857dd781c64a44f2e06120",
|
||||
"bytes": 1416
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build62_quick_panel_onair_reconcile.py",
|
||||
"sha256": "63e04eb974112351ef98784843b5482293f87c77563c2ae49ea6b080b428fbae",
|
||||
"bytes": 1472
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build69_runtime_entry_admin_editor.py",
|
||||
"sha256": "05224179ad589e201f60b4b0745c7e9580b932b57b8f138aedb5ff137d0b3d28",
|
||||
"bytes": 4134
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build72_portable_mapping_transfer.py",
|
||||
"sha256": "db805a5313835323d48d70f8fc245b8b9eb08fa96d5ee205d4c28829b092c94b",
|
||||
"bytes": 8788
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build75_mapping_collapsed_rescan.py",
|
||||
"sha256": "0f37304936eb3cd4fb51d31567f3d811d718b6c5635750dee5cba1fad9c90164",
|
||||
"bytes": 6964
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build76_mapping_compact_copy.py",
|
||||
"sha256": "635438d45f133e9215a68c455d9f6c214e3e35a112f43c22d76da4c6460d169c",
|
||||
"bytes": 8134
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build78_penalty_mapping_context_auto_sync.py",
|
||||
"sha256": "10d892d3edcd9b02198a300fd35ff76e5e647617c9f6cf10e0b163eec0eccc8c",
|
||||
"bytes": 1278
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build86_penalty_context_prepared_titles.py",
|
||||
"sha256": "2778c2ef13ce60dec9ab41fad51587e71e4819eea9b9d1f5234bd511bf371ea1",
|
||||
"bytes": 4209
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build93_countdown_reseed_on_start.py",
|
||||
"sha256": "0ec4c080dbb5003bbfd5a21365afbafabc3087d9f58785f4146f45d4d2e3baa8",
|
||||
"bytes": 1059
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build95_countdown_explicit_start_stop_sync.py",
|
||||
"sha256": "a35e05fe67e6fea2eb4e9a6e5dbe7c6f706fc809ad55a3bbdd2fbc97a706be10",
|
||||
"bytes": 1443
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build96_penalty_strength_transition_state_machine.py",
|
||||
"sha256": "be1814d23a2657a5caaf8e13f11fce3232dda5139e22c4f667ea6aba9d05b89d",
|
||||
"bytes": 5539
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build97_mapping_chunked_transport.py",
|
||||
"sha256": "b831b49c10ba9e17a12d2b9346cf36e8a902e634b7e1185046b7adcec2fa8627",
|
||||
"bytes": 7986
|
||||
},
|
||||
{
|
||||
"path": "tests/test_build98_timer_countdown_sync_fixed_pin.py",
|
||||
"sha256": "5c201d43439b25f85d6eba9fd205a0c8c5fa344b1106d65cf6a37eb13385588d",
|
||||
"bytes": 2016
|
||||
},
|
||||
{
|
||||
"path": "tests/test_hotfix_mapping_transport.py",
|
||||
"sha256": "ae0d1d8fd390b677162aefdebaab24793345063b76bdd536afc089ee5cc7633a",
|
||||
"bytes": 5717
|
||||
},
|
||||
{
|
||||
"path": "tests/test_hotfix_penalty_visibility.py",
|
||||
"sha256": "d222c210166e5067060953a3e908278294b4034c0e45fd1deada1c75ab91d0e3",
|
||||
"bytes": 564
|
||||
},
|
||||
{
|
||||
"path": "tests/test_khl_refresh_and_career.py",
|
||||
"sha256": "11ec4abb200586ba4b02f5e5e58d7a4c3569cb153c1f4e4cb0edfccb58d50ba1",
|
||||
"bytes": 18143
|
||||
},
|
||||
{
|
||||
"path": "tests/test_khl_site_module.py",
|
||||
"sha256": "94950e623ee6b02e57291a8227ecdafe501d9a9dcc4d728f61820d5577ce9473",
|
||||
"bytes": 1655
|
||||
},
|
||||
{
|
||||
"path": "tests/test_mapping_admin_visibility.py",
|
||||
"sha256": "76085e0a7dae3312315fe109a2f7f3d50665aefa1c71456f2fd3e83f40b1a99a",
|
||||
"bytes": 3547
|
||||
},
|
||||
{
|
||||
"path": "tests/test_mapping_publications.py",
|
||||
"sha256": "830547cb6e0efd9e38e944dc9ce91b21049ead59f4dd36b3c5fb517980f7302a",
|
||||
"bytes": 16185
|
||||
},
|
||||
{
|
||||
"path": "tests/test_multi_agent_mapping_recovery.py",
|
||||
"sha256": "34512d80c328f76e7973942ec46ada0d25cfbbf8f7d8e90aea14992a0f81507f",
|
||||
"bytes": 8963
|
||||
},
|
||||
{
|
||||
"path": "tests/test_program_log.py",
|
||||
"sha256": "b7003aaeecbf6404ac6e87ab673e732e6c317f7705455e81a4876cfb4eae54da",
|
||||
"bytes": 9158
|
||||
},
|
||||
{
|
||||
"path": "tests/test_shortcut_sequences.py",
|
||||
"sha256": "9365ceb023c950710b7c8502e9cc5f2c01b0b8666eaede5a759e721517b45fb7",
|
||||
"bytes": 10544
|
||||
},
|
||||
{
|
||||
"path": "tests/test_stable_vmix_input_identity.py",
|
||||
"sha256": "479e8d12bc01b38461ee50f9ea2286bd84b19dc09ee52639a71c65240b286f51",
|
||||
"bytes": 5711
|
||||
},
|
||||
{
|
||||
"path": "tests/test_storage_maintenance.py",
|
||||
"sha256": "45e6424437df347531bd446969d01ac482ae29eba2c72da8b25fbe862b651d52",
|
||||
"bytes": 10519
|
||||
},
|
||||
{
|
||||
"path": "tests/test_web_observability.py",
|
||||
"sha256": "b9e34be6ee80559510caf2030d05a3d44ad29d6de02635501ce48fc2bd9e01d9",
|
||||
"bytes": 9073
|
||||
},
|
||||
{
|
||||
"path": "tests/timer_contract_support.py",
|
||||
"sha256": "88285cec8118a37a2fbe25db47b076725318baa67ac9d341bdd8ce68a592aa9c",
|
||||
"bytes": 2403
|
||||
},
|
||||
{
|
||||
"path": "tests/ui_contract_support.py",
|
||||
"sha256": "e3a64451071235f8c1e916c9163f36cf10c28aa487c0db903ec259f4a63b13c4",
|
||||
"bytes": 596
|
||||
},
|
||||
{
|
||||
"path": "tests/ui_legacy_contracts.cjs",
|
||||
"sha256": "e2025c7b1844fd8f5e9c43ae47b26f114d1d0e3efac4d84a0b303a037a9a2b47",
|
||||
"bytes": 26212
|
||||
},
|
||||
{
|
||||
"path": "ui_builder/manager.py",
|
||||
"sha256": "feae7f08d88ce744d03e5ad3b76dd8b869f0a96494d08fb6378b4625aea446f7",
|
||||
"bytes": 37976
|
||||
},
|
||||
{
|
||||
"path": "ui_builder/static/app.js",
|
||||
"sha256": "4bd4b6f96eb7074a22889015e3652100b7e06e512fbf654999cc47adfb5437d4",
|
||||
"bytes": 1003282
|
||||
},
|
||||
{
|
||||
"path": "ui_builder/storage.py",
|
||||
"sha256": "e80da2f3b98f98bbdbd1022a08eb14b914acf763149219d16fd290a57b0c5f2e",
|
||||
"bytes": 3823
|
||||
}
|
||||
],
|
||||
"agent_executable_changed": false,
|
||||
"preserved_user_files_verified": 1215
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# Хоккейное управление для vMix
|
||||
|
||||
BUILD190 · `2026.10.21.1`
|
||||
BUILD191 · `2026.10.21.2`
|
||||
|
||||
Операторская панель: матчи и составы Stat2TV/КХЛ, таймеры, удаления, статистика,
|
||||
SQL/Mapping и передача титров в vMix через персональные Agent.
|
||||
|
||||
85
UPDATE.txt
85
UPDATE.txt
@@ -1,57 +1,48 @@
|
||||
BUILD190 · 2026.10.21.1
|
||||
BUILD191 · 2026.10.21.2
|
||||
|
||||
Для обновления существующей VM используйте hockey_BUILD190_update.zip.
|
||||
Распакуйте его В КОРЕНЬ существующего проекта с заменой файлов.
|
||||
Пакет не содержит .env, действующие настройки, пароли, базы, карточки КХЛ
|
||||
и Agent.exe. Они остаются в вашем проекте.
|
||||
ОБНОВЛЕНИЕ СУЩЕСТВУЮЩЕЙ VM
|
||||
hockey_BUILD191_update.zip содержит накопленные изменения BUILD190 и BUILD191.
|
||||
Он подходит для исходной BUILD189 и уже установленной BUILD190.
|
||||
Пакет не содержит .env, действующие настройки, пароли, базы, данные КХЛ,
|
||||
снимки XML и Agent.exe. Полный архив — снимок присланной VM, не заменяйте
|
||||
им более новые действующие настройки.
|
||||
|
||||
1. Остановите службу приложения в удобное время. Сохраните резервную копию
|
||||
проекта и PostgreSQL. Существующие настройки после изготовления присланного
|
||||
архива могут быть новее: не заменяйте их файлами из полного архива.
|
||||
2. Распакуйте пакет изменённых файлов в корень проекта.
|
||||
3. Из активного Python/venv приложения установите зависимости:
|
||||
1. Остановите приложение, сохраните резервную копию проекта и PostgreSQL.
|
||||
2. Распакуйте hockey_BUILD191_update.zip в корень существующего проекта
|
||||
с заменой файлов.
|
||||
3. Из Python/venv приложения выполните:
|
||||
python -m pip install -r requirements.txt
|
||||
Linux с .venv: .venv/bin/python -m pip install -r requirements.txt
|
||||
4. Посмотрите план очистки и при необходимости примените его:
|
||||
4. Очистку можно сначала посмотреть, затем применить:
|
||||
python cleanup_project.py --dry-run
|
||||
python cleanup_project.py --apply
|
||||
Исторические документы удалятся только при точном совпадении с копиями
|
||||
в docs/history.zip. Изменённые вами файлы и рабочие данные сохраняются.
|
||||
Изменённые вами файлы и рабочие данные сохраняются.
|
||||
5. Перезапустите существующую службу. Для ручного запуска:
|
||||
python -m uvicorn app:app --host 0.0.0.0 --port 8000 --workers 1
|
||||
Windows: START.bat. Не используйте --reload и несколько workers для эфира.
|
||||
6. Проверьте /api/health: build 2026.10.21.1. Откройте панель, выберите нужный
|
||||
Agent/матч, проверьте счёт, игрока, удаление и численный состав на vMix.
|
||||
При первом запуске существующие привязки Mapping фиксируются автоматически.
|
||||
Windows: START.bat. Для эфира один процесс без --reload.
|
||||
6. Проверьте /api/health: build 2026.10.21.2. Откройте выбранный матч и Agent,
|
||||
проверьте счёт, игрока, удаление, численный состав, паузу/старт таймера.
|
||||
|
||||
СОХРАНЕНИЕ MAPPING
|
||||
Сохранение меняет шаблон. Для обновления выбранного Agent нажмите ▶/↻ рядом
|
||||
с конфигом. Остальные Agent сохраняют свою опубликованную версию. ✓ означает
|
||||
актуальную публикацию; ↻ — что есть новая версия. Общие SQL-источники остаются
|
||||
общими: изменения SQL проверяйте вне эфира.
|
||||
BUILD191
|
||||
Исправлена отправка таймера при пустом выборе Agent: команда больше не может
|
||||
уйти на ранее выбранное устройство сессии. Отсутствующее поле старого API
|
||||
сохраняет совместимость, явно пустое поле отклоняется сервером.
|
||||
Проверки приведены к действующим контрактам без skip/xfail. Полный набор:
|
||||
565 passed, 0 failed. Итоги, ограничения и сценарии — docs/validation.json.
|
||||
Дополнительно пройден локальный сценарий трёх матчей с шестью Agents:
|
||||
60 циклов по 64 поля на устройство, ошибки ACK, медленный источник,
|
||||
переподключение и передача управления. CLI для повторения включён в tests/.
|
||||
|
||||
ЖУРНАЛ
|
||||
Кнопка «Журнал» находится в верхней панели и доступна администратору.
|
||||
С телефона/другого компьютера: адрес вашего сервера + /logs, например
|
||||
http://АДРЕС_СЕРВЕРА:8000/logs. Вход под учётной записью администратора.
|
||||
Периоды: сегодня / 7 дней / месяц / все доступные / произвольные даты.
|
||||
Есть поиск, участник, матч, Agent, уровень, раздел, сортировка, TXT/JSONL.
|
||||
Скачивается весь выбранный период. Хранятся текущий и предыдущий календарные
|
||||
месяцы по Москве, более старые удаляются автоматически.
|
||||
Логи — logs/ или HOCKEY_LOG_DIR; секреты маскируются.
|
||||
MAPPING И ЖУРНАЛ (BUILD190)
|
||||
Mapping считается применённым после подтверждения Agent. Сохранение меняет
|
||||
шаблон; кнопка ▶/↻ публикует его выбранному Agent. Другие устройства сохраняют
|
||||
свою опубликованную версию. Повтор после разрыва не сбрасывает native Countdown.
|
||||
Журнал доступен администратору: кнопка «Журнал» или /logs с любого компьютера
|
||||
или телефона, который имеет доступ к серверу. Есть даты, 7 дней, месяц,
|
||||
участник, матч, Agent, поиск, сортировка и скачивание TXT/JSONL.
|
||||
Хранятся текущий и предыдущий календарные месяцы по Москве; старые удаляются.
|
||||
Секреты маскируются. Замеры загрузки интерфейса записываются как browser.ready.
|
||||
|
||||
СКОРОСТЬ ИНТЕРФЕЙСА
|
||||
Сжатие и кэширование скриптов/стилей, параллельная загрузка и меньше
|
||||
перерисовок. В журнале browser.ready видны замеры конкретного компьютера.
|
||||
|
||||
ПРОВЕРКИ
|
||||
Новые сценарии mapping/участников/журнала и браузер проверены локально.
|
||||
91 проверка финального поведенческого набора прошла, дополнительные проверки
|
||||
входа с телефона/выхода при недоступной авторизации тоже прошли.
|
||||
В исходном архиве уже было 59 падающих тестов; список и точные итоги находятся
|
||||
в docs/validation.json. Полный набор после последних правок не перезапускался.
|
||||
Рабочий PostgreSQL, Stat2TV, Windows Agent.exe и живой vMix при разработке
|
||||
не подключались: полную эфирную проверку выполните после установки.
|
||||
|
||||
Основные инструкции: README.md и docs/OPERATOR.md, ADMIN.md, ARCHITECTURE.md,
|
||||
CHANGELOG.md. Прежние 46 документов доступны в docs/history.zip.
|
||||
Проверки локальные: без рабочего PostgreSQL, Stat2TV, Windows Agent.exe и vMix.
|
||||
Проверку на реальной VM выполните после установки перед эфиром.
|
||||
Инструкции: README.md, docs/OPERATOR.md, ADMIN.md, ARCHITECTURE.md, CHANGELOG.md.
|
||||
История прежних документов: docs/history.zip.
|
||||
|
||||
2
app.py
2
app.py
@@ -42,7 +42,7 @@ from hockey_data.program_log_router import create_program_log_router
|
||||
from hockey_data.web_observability import WebAuditMiddleware, apply_web_cache_policy, create_browser_event_router, install_runtime_audit
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
BUILD_VERSION = "2026.10.21.1"
|
||||
BUILD_VERSION = "2026.10.21.2"
|
||||
# compatibility: BUILD_VERSION = "2026.09.24.2"
|
||||
# compatibility: BUILD_VERSION = "2026.09.23.8"
|
||||
# compatibility: BUILD_VERSION = "2026.09.23.7"
|
||||
|
||||
@@ -50,7 +50,7 @@ Stat2TV также может использовать существующий
|
||||
Для BUILD190 обязательно повторите установку `python -m pip install -r requirements.txt`:
|
||||
добавлена база часовых поясов `tzdata` для Windows. Agent.exe заменять не требуется.
|
||||
Три целочисленных поля публикации Mapping добавляются существующим механизмом
|
||||
миграции схемы. После запуска проверьте `/api/health`: версия `2026.10.21.1`.
|
||||
миграции схемы. После запуска проверьте `/api/health`: версия `2026.10.21.2`.
|
||||
Для обновления существующей VM используйте пакет только изменённых файлов;
|
||||
полный архив содержит снимок настроек из присланной копии и предназначен для
|
||||
восстановления/новой установки. Не заменяйте им более свежие настройки эфира.
|
||||
@@ -132,6 +132,15 @@ XML не удаляются по возрасту: на них ссылаетс
|
||||
|
||||
После обновления выполните целевые проверки mapping/прав/нескольких матчей и
|
||||
`python -m pytest tests/test_build190_mapping_delivery.py tests/test_mapping_publications.py tests/test_program_log.py tests/test_web_observability.py tests/test_storage_maintenance.py tests/test_stage1_match_access.py tests/test_stage2_ui_storage.py`.
|
||||
Старые тесты с жёстко заданными историческими номерами сборок требуют отдельной
|
||||
актуализации; результат такого теста сам по себе не доказывает сбой эфира.
|
||||
Полный набор для разработки: `python -m pytest -q` в отдельной тестовой копии.
|
||||
Дополнительно к зависимостям приложения нужны pytest и Node.js: проверки интерфейса
|
||||
исполняют настоящие функции JavaScript. Исторические тесты таймеров и интерфейса
|
||||
актуализированы в BUILD191; номера в именах файлов сохраняют историю появления.
|
||||
Живой vMix и рабочая PostgreSQL должны проверяться на отдельном прогоне перед эфиром.
|
||||
|
||||
Совместную работу трёх матчей и шести Agents можно повторить командой
|
||||
`python tests/multi_match_harness.py --run --ticks 60 --fields 64 --phase-timeout 900 --output multi-match-result.json`.
|
||||
Без `--run` скрипт только показывает план. Он использует временную SQLite,
|
||||
локальные API и поддельные WebSocket, проверяет ACK, переподключение, медленный
|
||||
источник и передачу управления. Производительность PostgreSQL и настоящего
|
||||
vMix проверяется отдельно на рабочем оборудовании.
|
||||
|
||||
@@ -1,5 +1,24 @@
|
||||
# Изменения и история
|
||||
|
||||
## BUILD191 — 21 октября 2026 · 2026.10.21.2
|
||||
|
||||
- Пустой выбор Agent больше не отправляет команды таймера на прежнее устройство сессии.
|
||||
- Сервер отклоняет явно пустой `device_id`; старые клиенты без этого поля проходят прежние проверки доступа.
|
||||
- Неотправленные назначения удалений удаляются из оптимистичного кэша, локальный таймер сохраняет своё состояние.
|
||||
- Устаревшие проверки GUID/номеров Inputs, пакетного транспорта и противоречивых протоколов таймеров заменены исполняемыми проверками действующих контрактов.
|
||||
- Проверки КХЛ используют отдельные настройки: выбор числа потоков на VM не меняется ради тестов.
|
||||
- Проверяются порядок ACK, ограниченные повторы, изоляция устройств, пауза/продолжение native Countdown, готовые удаления, права и переключение матчей.
|
||||
- Проверки JavaScript требуют явного завершения сценария: завершение Node с незавершённым Promise не считается успехом.
|
||||
|
||||
Полный прогон: **565 passed, 0 failed**, без skip/xfail, 272,9 с. Для всех
|
||||
59 прежних падений проверено соответствие реально прошедшим сценариям.
|
||||
Все 11 намеренно внесённых ошибочных вариантов обнаружены проверками.
|
||||
Совместный локальный прогон трёх матчей и шести Agents: 60 циклов по 64 поля,
|
||||
24 196 команд и 1425 запросов зрителей. Итоговые значения, изоляция, восстановление
|
||||
после ошибок ACK/разрыва и передача управления прошли; очереди завершились пустыми.
|
||||
Подробные результаты и ограничения находятся в [validation.json](validation.json).
|
||||
Живые PostgreSQL, Stat2TV, Windows Agent.exe и vMix в локальном прогоне не подключались.
|
||||
|
||||
## BUILD190 — 21 октября 2026 · 2026.10.21.1
|
||||
|
||||
- Mapping кэшируется только после ACK; ограниченные безопасные повторы и защита от старых подтверждений.
|
||||
|
||||
1208
docs/validation.json
1208
docs/validation.json
File diff suppressed because it is too large
Load Diff
@@ -5777,6 +5777,10 @@ def create_hockey_agent_router(
|
||||
request: Request,
|
||||
user: HockeyUser = Depends(auth_dependency),
|
||||
) -> dict[str, Any]:
|
||||
if "device_id" in payload.model_fields_set and not payload.device_id.strip():
|
||||
# Explicitly clearing this browser's selection must not silently
|
||||
# reuse a previous session binding. Omission keeps legacy clients.
|
||||
raise HTTPException(status_code=409, detail="Выберите Agent в этом браузере")
|
||||
game_id = await run_db(match_access.game_for_session, payload.session_token, user)
|
||||
await run_db(match_access.require_controller, request, user, game_id)
|
||||
await run_db(match_access.protect_session, request, user, payload.session_token)
|
||||
|
||||
@@ -6,33 +6,44 @@ const names=['currentHockeyPenaltyEntries','activeHockeyPenaltyEntries','hockeyP
|
||||
'penaltyMirrorKey','vmixCountdownValue','vmixGameCountdownControlCommands','vmixPenaltyCountdownControlCommands',
|
||||
'rebalanceVmixPenaltyTargets','emitHockeyEventUpdated','hockeyEventReady','hockeyScoreboardIsLive',
|
||||
'shortcutSequenceIsOnAir','sequenceMatchesRuntimeOverlay','runtimeOverlayMatchesInput',
|
||||
'normalizeRuntimeVmixInputRef','runtimeOverlayInputRefs'];
|
||||
'normalizeRuntimeVmixInputRef','runtimeOverlayInputRefs',
|
||||
'hockeyScoreboardSequenceIsLive','hockeyScoreboardPrimaryOverlayTargets','hockeyTeamStateSequenceStep',
|
||||
'buildShortcutRuntimeContext','isTimerComponent','getByPath','formatValue','templateValue','templateSequenceValue',
|
||||
'vmixOverlayLayer','vmixInputByRef','vmixInventoryInputs','hockeyStoreGameControl',
|
||||
'hockeyReadyPenaltyCounts','hockeyHasPendingPenaltyInteractions','hockeyFlushPendingPenaltyInteractions',
|
||||
'hockeyStrengthMappingSignature','hockeyTeamStateFlagSignature'];
|
||||
const definitions=names.map(name=>{const start=source.search(new RegExp(' (?:async )?function '+name+'\\('));
|
||||
assert.ok(start>=0,name);return source.slice(start,source.indexOf('\n }',start)+4);}).join('\n');
|
||||
const target={id:'home-slot',input:'home-penalty',selected_name:'Time.Text',overlay:'2'};
|
||||
const step={id:'timers',type:'hockey_vmix_timers_start',sync_vmix_penalties:true,home_penalty_targets:[target],away_penalty_targets:[]};
|
||||
const scoreboard={id:'score',is_scoreboard_sequence:true};
|
||||
const scoreboard={id:'score',is_scoreboard_sequence:true,steps:[{type:'vmix_command',function:'OverlayInput1In',input:'score-input'}]};
|
||||
const component={type:'hockey_penalty_dashboard',action_id:'penalties'};
|
||||
const event={id:'p1',side:'away',player:{side:'away'},infraction:null,preset:'2',durationMs:120000,
|
||||
remainingMs:120000,startedOnce:false,running:false,finished:false};
|
||||
const board={penalties:[event]};
|
||||
const sent=[];let allowed=true;
|
||||
const sent=[], timeline=[];let allowed=true;
|
||||
const state={config:{components:[component],shortcut_sequences:[scoreboard,{id:'space',steps:[step]}]},
|
||||
data:{},hockeyPenaltyAdvantageCycle:{},activeHockeyVmixTimerSteps:new Set(),
|
||||
data:{},formValues:{},hockeyGameControl:{},hockeyPenaltyAdvantageCycle:{},activeHockeyVmixTimerSteps:new Set(),
|
||||
vmixPenaltyTargetAssignments:new Map(),vmixPenaltyMirrors:new Map(),vmixOverlayTallyAuthoritative:true,
|
||||
vmixOverlayRuntime:new Map([['1',{input:'score-input'}]]),shortcutSequenceOverlayState:new Map(),
|
||||
quickPanelServerOnAirSequences:new Set(),quickPanelOnAirSequences:new Set()};
|
||||
const noop=()=>{};
|
||||
const ctx={console,state,performance,Date,ensureHockeyBoardState:()=>board,hockeyCanControl:()=>allowed,
|
||||
const ctx={console,state,performance,Date,window:{UIBuilderRuntime:{patchData:noop},dispatchEvent:noop},clone:value=>JSON.parse(JSON.stringify(value)),ensureHockeyBoardState:()=>board,hockeyCanControl:()=>allowed,
|
||||
padTimer:n=>String(n).padStart(2,'0'),sequencePenaltyTargets:(s,side)=>s[side+'_penalty_targets'],
|
||||
getByPath:()=>({}),rememberPenaltyAdvantagePlan:noop,emitInteraction:noop,hockeyPenaltyContext:()=>({}),
|
||||
getByPath:()=>({}),rememberPenaltyAdvantagePlan:noop,emitInteraction:(_component,name)=>timeline.push(name),hockeyPenaltyContext:()=>({}),
|
||||
addHockeyHistory:noop,hockeyInfractionWebLabel:()=>'',hockeySyncPenaltySideMappingContext:()=>Promise.resolve(),
|
||||
sendRuntimeVmixTimerSequence:commands=>{sent.push(...commands);return Promise.resolve({ok:true});},
|
||||
sendRuntimeVmixTimerSequence:commands=>{timeline.push('countdown-transport');sent.push(...commands);return Promise.resolve({ok:true});},
|
||||
hockeyApplyTimerRules:noop,hockeyBackupPlayerSelectionValues:noop,persistHockeyBoard:noop,
|
||||
hockeyRefreshVmixMappingForStrength:async()=>{timeline.push('strength-mapping-confirmed');return true;},
|
||||
hockeyTeamStateScoreboardIsLive:()=>false,hockeySyncScoreboardConditionalSteps:async()=>0,
|
||||
shortcutSequenceById:id=>state.config.shortcut_sequences.find(s=>s.id===id),
|
||||
shortcutSequenceOverlayTargets:s=>s?.id==='score'?[{layer:'1',input:'score-input'}]:[],
|
||||
shortcutSequencePreviewTargets:()=>[],sequenceStillOwnsRuntimeOverlay:()=>false};
|
||||
vm.createContext(ctx);vm.runInContext(definitions,ctx);
|
||||
const functions=()=>sent.map(c=>c.Function);
|
||||
const settle=async()=>{for(let i=0;i<12;i++)await Promise.resolve();};
|
||||
const serverState=()=>({current_period:'1',strength:{home_penalties:0,away_penalties:1}});
|
||||
const afterSave=async()=>{ctx.hockeyStoreGameControl('g',serverState(),{render:false,dispatch:false});await settle();};
|
||||
(async()=>{
|
||||
// No local ON AIR latch, only authoritative vMix tally (e.g. after reload).
|
||||
assert.equal(ctx.hockeyScoreboardIsLive(),true);
|
||||
@@ -40,14 +51,20 @@ const functions=()=>sent.map(c=>c.Function);
|
||||
assert.deepEqual(functions(),[],'an incomplete draft must not display');
|
||||
event.infraction={id:'trip'};
|
||||
ctx.emitHockeyEventUpdated(component,event,'infraction');
|
||||
assert.deepEqual(functions(),[],'newly prepared penalty waits for authoritative strength and Mapping');
|
||||
assert.equal(event.readyPending,true);
|
||||
await afterSave();
|
||||
assert.ok(timeline.indexOf('strength-mapping-confirmed')<timeline.indexOf('countdown-transport'));
|
||||
assert.ok(timeline.indexOf('countdown-transport')<timeline.indexOf('penalty_ready'));
|
||||
assert.deepEqual(functions(),['SetCountdown','StopCountdown','OverlayInput2In']);
|
||||
assert.equal(sent[0].Value,'00:02:00');
|
||||
assert.ok(sent.every(c=>c.Input==='home-penalty'));
|
||||
assert.equal(event.running,false);assert.equal(event.startedOnce,false);
|
||||
sent.length=0;ctx.emitHockeyEventUpdated(component,event,'player');
|
||||
sent.length=0;ctx.emitHockeyEventUpdated(component,event,'player');await afterSave();
|
||||
assert.deepEqual(functions(),[],'duplicate ready notification must not reseed or redisplay');
|
||||
event.durationMs=event.remainingMs=240000;
|
||||
ctx.emitHockeyEventUpdated(component,event,'preset');
|
||||
await ctx.rebalanceVmixPenaltyTargets({editedEventKey:ctx.penaltyMirrorKey(component,event)});
|
||||
assert.deepEqual(functions(),['SetCountdown','StopCountdown']);assert.equal(sent[0].Value,'00:04:00');
|
||||
// Before F1, off-air preparation sends nothing. Showing the scorebug displays
|
||||
// the penalty even if its target was assigned previously but hidden later.
|
||||
@@ -56,6 +73,7 @@ const functions=()=>sent.map(c=>c.Function);
|
||||
assert.equal(ctx.hockeyScoreboardIsLive(),false,'authoritative OUT wins over stale local latch');
|
||||
event.durationMs=event.remainingMs=300000;
|
||||
ctx.emitHockeyEventUpdated(component,event,'preset');
|
||||
await ctx.rebalanceVmixPenaltyTargets({editedEventKey:ctx.penaltyMirrorKey(component,event)});
|
||||
assert.deepEqual(functions(),['SetCountdown','StopCountdown'],'editing a previously assigned hidden Input updates its stopped time');
|
||||
assert.equal(sent[0].Value,'00:05:00');
|
||||
sent.length=0;state.vmixPenaltyTargetAssignments.clear();state.activeHockeyVmixTimerSteps.clear();
|
||||
|
||||
719
tests/multi_match_harness.py
Normal file
719
tests/multi_match_harness.py
Normal file
@@ -0,0 +1,719 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline multi-match integration harness. Planning is the default; --run opts in.
|
||||
|
||||
Use a disposable SQLite database with the project's actual routers, Mapping SQL,
|
||||
context, scheduler, authority and ACK handlers. No production application import,
|
||||
real network, production PostgreSQL or vMix process is used.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
PHASES = [
|
||||
"bootstrap: 3 matches, 6 accounts/participants, 6 Agents, one shared Mapping and real SQL",
|
||||
"steady load: independent context mutations, automatic SQL ticks and concurrent spectator reads",
|
||||
"negative ACK: two rejections of one field; unconfirmed value excluded from cache; later tick restores it",
|
||||
"slow source: block match M1 in DB workers; M2/M3 and health must finish before release",
|
||||
"reconnect: old ACK cannot confirm a new generation; new inventory restores values without manual apply",
|
||||
"handoff: old inflight result is fenced, former controller writes rejected, new controller continues",
|
||||
"final: no foreign match/user/device payload, no pending ACK or recovery jobs",
|
||||
]
|
||||
|
||||
|
||||
def percentile(values, quantile):
|
||||
if not values:
|
||||
return None
|
||||
ordered = sorted(values)
|
||||
return round(ordered[min(len(ordered) - 1, int((len(ordered) - 1) * quantile))], 3)
|
||||
|
||||
|
||||
class Scenario:
|
||||
def __init__(self, project, directory, args):
|
||||
# Imports are delayed until --run so inspecting this plan never starts code.
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
# FastAPI resolves postponed dependency annotations in module globals.
|
||||
globals()["Request"] = Request
|
||||
import httpx
|
||||
from sqlalchemy import event
|
||||
from hockey_data.agent_bridge import VmixAgentHub, create_hockey_agent_router, _stable_vmix_inventory_fingerprint
|
||||
from hockey_data.auth_bridge import HockeyUser
|
||||
from hockey_data.config import HockeySettingsStore
|
||||
from hockey_data.match_access import MatchAccess
|
||||
from hockey_data.router import create_hockey_router
|
||||
from hockey_data.service import HockeyDataService
|
||||
|
||||
spec = importlib.util.spec_from_file_location("hockey_harness_support", project / "tests/support.py")
|
||||
support = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(support)
|
||||
self.args, self.directory = args, directory
|
||||
self.db = support.LocalTestDatabase(directory / "integration.sqlite3")
|
||||
self.db.create_all()
|
||||
with self.db.engine.connect() as connection:
|
||||
connection.exec_driver_sql("PRAGMA journal_mode=WAL")
|
||||
self.sql = Counter()
|
||||
self.sql_lock = threading.Lock()
|
||||
def count_sql(_connection, _cursor, statement, _parameters, _context, _many):
|
||||
with self.sql_lock:
|
||||
self.sql[statement.lstrip().split(None, 1)[0].lower()] += 1
|
||||
event.listen(self.db.engine, "before_cursor_execute", count_sql)
|
||||
self.settings = HockeySettingsStore(directory / "settings")
|
||||
self.service = HockeyDataService(base_dir=directory, database=self.db, settings=self.settings)
|
||||
self.hub = VmixAgentHub(self.db, settings=self.settings)
|
||||
self.access = MatchAccess(self.db)
|
||||
self.users, self.people, self.sockets, self.tokens = {}, {}, {}, {}
|
||||
self.frames, self.ack_ms, self.read_ms, self.phase_results = [], [], [], []
|
||||
self.source_calls = Counter()
|
||||
self.source_contexts = []
|
||||
self.source_errors = []
|
||||
self.source_gate_observations = []
|
||||
self.background_mapping_failures = []
|
||||
self.expected_background_mapping_failures = 0
|
||||
self.transport_contract_errors = []
|
||||
self.expected_selections = {}
|
||||
self.ticks = {f"M{i}": 0 for i in range(1, 4)}
|
||||
self.health_requests = self.viewer_reads = self.viewer_rejections = 0
|
||||
self.heartbeat_requests = 0
|
||||
self.expected_old_controller_heartbeat_rejections = 0
|
||||
self.last_heartbeat = 0.0
|
||||
self.controllers = {f"M{i}": f"op{i}" for i in range(1, 4)}
|
||||
self.current_phase = ""
|
||||
self.health_ms, self.loop_lag_ms, self.pending_ack_ages_ms = [], [], []
|
||||
self.max_pending_acks = 0
|
||||
self.request_started = {}
|
||||
self.control_tasks = set()
|
||||
self.polling_errors = []
|
||||
self.stop_polling = asyncio.Event()
|
||||
self.slow_entered = asyncio.Event()
|
||||
self.slow_release = threading.Event()
|
||||
self.slow_release.set()
|
||||
self.slow_match = ""
|
||||
self.loop = asyncio.get_running_loop()
|
||||
for i in range(1, 4):
|
||||
for prefix in ("op", "view"):
|
||||
name = f"{prefix}{i}"
|
||||
# Account eligibility permits an explicit handoff. Until then
|
||||
# viewN has a server-enforced viewer lease role, not controller.
|
||||
self.users[name] = HockeyUser(id=name, login=name, display_name=name, role="operator")
|
||||
self.people[name] = {"game": f"M{i}", "device": f"GFX-LOAD-{prefix.upper()}-{i}",
|
||||
"participant": uuid.uuid4().hex, "secret": (prefix + str(i) + "x" * 40)}
|
||||
async def auth(request: Request):
|
||||
user = self.users.get(request.headers.get("X-Harness-User", ""))
|
||||
if user is None:
|
||||
raise HTTPException(401)
|
||||
return user
|
||||
async def admin(request: Request):
|
||||
await auth(request)
|
||||
raise HTTPException(403)
|
||||
# MatchAccess captures this hook while the routers are constructed,
|
||||
# matching app.py's production initialization order.
|
||||
def control_change(game):
|
||||
def start():
|
||||
task = asyncio.create_task(self.hub.invalidate_match_mapping(game))
|
||||
self.control_tasks.add(task)
|
||||
task.add_done_callback(self.control_tasks.discard)
|
||||
self.loop.call_soon_threadsafe(start)
|
||||
self.db.on_match_control_change = control_change
|
||||
self.app = FastAPI()
|
||||
self.app.include_router(create_hockey_router(self.service, auth_dependency=auth, admin_dependency=admin, agent_hub=self.hub))
|
||||
self.app.include_router(create_hockey_agent_router(self.hub, auth_dependency=auth, admin_dependency=admin))
|
||||
@self.app.get("/harness-health")
|
||||
async def health():
|
||||
self.health_requests += 1
|
||||
return {"ok": True}
|
||||
self.http = httpx.AsyncClient(transport=httpx.ASGITransport(app=self.app), base_url="http://offline.invalid")
|
||||
self.inventory = {"inputs": [{"key": "shared-score-guid", "number": "1", "title": "Shared Score",
|
||||
"type": "GT", "fields": [{"name": f"Payload{n:03}.Text", "type": "text", "index": str(n)}
|
||||
for n in range(args.fields)]}]}
|
||||
self.fingerprint = _stable_vmix_inventory_fingerprint(self.inventory["inputs"])
|
||||
self.original_run_source = self.hub.mapping_data._run_source
|
||||
def observed_source(source, context, **kwargs):
|
||||
if source.code == "probe":
|
||||
identity = tuple(str(context.get(key) or "") for key in ("game_id", "device_id", "account_id", "assignment_id"))
|
||||
with self.sql_lock:
|
||||
self.source_calls[identity[0]] += 1
|
||||
self.source_contexts.append(identity)
|
||||
if identity[0] == self.slow_match and not self.slow_release.is_set():
|
||||
gate_started = time.perf_counter()
|
||||
self.loop.call_soon_threadsafe(self.slow_entered.set)
|
||||
released = self.slow_release.wait(timeout=8)
|
||||
with self.sql_lock:
|
||||
self.source_gate_observations.append({"game": identity[0], "device": identity[1],
|
||||
"wait_ms": round((time.perf_counter() - gate_started) * 1000, 3),
|
||||
"released": released, "timed_out": not released})
|
||||
if not released:
|
||||
with self.sql_lock:
|
||||
self.source_errors.append({"game": identity[0], "exception": "source_gate_timeout"})
|
||||
raise AssertionError("Harness slow-source gate was not released")
|
||||
try:
|
||||
result = self.original_run_source(source, context, **kwargs)
|
||||
except Exception as error:
|
||||
if source.code == "probe":
|
||||
with self.sql_lock:
|
||||
self.source_errors.append({"game": context.get("game_id"), "exception": repr(error)})
|
||||
raise
|
||||
if source.code == "probe" and (not result.get("ok") or result.get("skipped")):
|
||||
with self.sql_lock:
|
||||
self.source_errors.append({"game": context.get("game_id"), "result": result})
|
||||
return result
|
||||
self.hub.mapping_data._run_source = observed_source
|
||||
original_job_done = self.hub._auto_refresh_job_done
|
||||
def observed_job_done(device, task):
|
||||
if not task.cancelled():
|
||||
try:
|
||||
result = task.result()
|
||||
failed = not result.get("ok", True) or bool(result.get("errors"))
|
||||
except Exception as error:
|
||||
result, failed = {"exception": repr(error)}, True
|
||||
if failed:
|
||||
if (self.current_phase == "negative_ack" and device == self.people["op2"]["device"]
|
||||
and "injected HTTP 500" in str(result)):
|
||||
self.expected_background_mapping_failures += 1
|
||||
else:
|
||||
self.background_mapping_failures.append({"phase": self.current_phase,
|
||||
"device": device, "result": result})
|
||||
original_job_done(device, task)
|
||||
self.hub._auto_refresh_job_done = observed_job_done
|
||||
async def forbidden_feed(*_args, **_kwargs):
|
||||
raise AssertionError("Harness attempted a real Stat2TV fetch")
|
||||
self.service.client.fetch_xml = forbidden_feed
|
||||
|
||||
def basic_headers(self, name):
|
||||
person = self.people[name]
|
||||
return {"X-Harness-User": name, "X-Hockey-Participant": person["participant"],
|
||||
"X-Hockey-Game": person["game"], "X-Hockey-Session": self.tokens.get(name, "")}
|
||||
|
||||
async def headers(self, name):
|
||||
response = await self.http.get(f"/api/hockey/games/{self.people[name]['game']}/access", headers=self.basic_headers(name))
|
||||
assert response.status_code == 200, response.text
|
||||
access = response.json()
|
||||
return {**self.basic_headers(name), "X-Hockey-Control-Generation": str(access["generation"]),
|
||||
"X-Hockey-Revision": str(access["revision"]), "X-Hockey-Command-Id": uuid.uuid4().hex}
|
||||
|
||||
def hello(self, name):
|
||||
person = self.people[name]
|
||||
return {"device_id": person["device"], "device_secret": person["secret"],
|
||||
"device_name": person["device"], "agent_version": "1.5.3", "vmix": {"connected": True}}
|
||||
|
||||
async def bootstrap(self):
|
||||
from hockey_data.async_work import run_db
|
||||
from hockey_data.models import Game, MappingSqlDataSource, OperatorSession, Tournament, VmixMappingField, VmixMappingProfile
|
||||
def seed():
|
||||
self.hub.mapping_data.ensure_defaults()
|
||||
with self.db.session() as session:
|
||||
session.add(Tournament(external_id="T", season_part="regular", level="khl", name_ru="Offline Harness"))
|
||||
for game in self.ticks:
|
||||
session.add(Game(external_id=game, tournament_external_id="T", home_team_external_id=game + "-H",
|
||||
away_team_external_id=game + "-A", home_team_name_ru=game + " HOME",
|
||||
away_team_name_ru=game + " AWAY", changes=0))
|
||||
profile = VmixMappingProfile(name="SHARED-HARNESS", project_fingerprint=self.fingerprint,
|
||||
inventory_json=json.dumps(self.inventory), version=1, active=True, created_by="harness", updated_by="harness")
|
||||
session.add(profile)
|
||||
session.flush()
|
||||
for n in range(self.args.fields):
|
||||
session.add(VmixMappingField(profile_id=profile.id, graphic="probe", data_key="probe.payload",
|
||||
vmix_input_key="shared-score-guid", vmix_input_number="1", vmix_input_title="Shared Score",
|
||||
vmix_field=f"Payload{n:03}.Text", field_type="text", enabled=True, sort_order=n))
|
||||
session.add(MappingSqlDataSource(code="probe", name="Identity probe", sql_text=(
|
||||
"SELECT :game_id || '|' || :device_id || '|' || :account_id || '|' || CAST(changes AS TEXT) AS payload "
|
||||
"FROM hockey_games WHERE external_id = :game_id"), enabled=True, auto_refresh_enabled=True,
|
||||
refresh_interval_ms=1000, field_metadata_json="{}", created_by="harness", updated_by="harness"))
|
||||
await run_db(seed)
|
||||
for name, person in self.people.items():
|
||||
ws = HarnessSocket(self, name)
|
||||
self.sockets[name] = ws
|
||||
await self.hub.register(ws, self.hello(name))
|
||||
await self.hub.pair_device(person["device"], self.users[name])
|
||||
token = "channel-" + name
|
||||
self.tokens[name] = token
|
||||
def session_seed(name=name, person=person, token=token):
|
||||
with self.db.session() as session:
|
||||
session.add(OperatorSession(session_token=token, wfl_user_id=name, login_snapshot=name,
|
||||
tournament_external_id="T", game_external_id=person["game"], status="active",
|
||||
browser_participant_id=person["participant"], vmix_device_uuid=person["device"]))
|
||||
await run_db(session_seed)
|
||||
response = await self.http.post(f"/api/hockey/games/{person['game']}/access/join",
|
||||
headers=self.basic_headers(name), json={"device_id": person["device"]})
|
||||
assert response.status_code == 200, response.text
|
||||
if name.startswith("op"):
|
||||
response = await self.http.post(f"/api/hockey/games/{person['game']}/access/claim",
|
||||
headers=await self.headers(name), json={"force": False})
|
||||
assert response.status_code == 200, response.text
|
||||
assigned = await self.hub.assign_match(wfl_user_id=name, tournament_external_id="T",
|
||||
game_external_id=person["game"], device_id=person["device"], operator_session_token=token,
|
||||
wait_for_mapping=False)
|
||||
assert assigned and assigned["game_id"] == person["game"]
|
||||
person["assignment"] = assigned["assignment_id"]
|
||||
await self.hub.receive_inventory(person["device"], {"type": "vmix.inventory",
|
||||
"inventory": {**self.inventory, "fingerprint": self.fingerprint}})
|
||||
await self.drain()
|
||||
await self.tick()
|
||||
self.verify_all_current()
|
||||
for i in range(1, 4):
|
||||
await self.reject_viewer_write(f"view{i}")
|
||||
|
||||
async def drain(self):
|
||||
for _ in range(25):
|
||||
await asyncio.sleep(0)
|
||||
jobs = [task for task in [*self.control_tasks, *self.hub._mapping_recovery_jobs.values(),
|
||||
*self.hub._auto_refresh_jobs.values()] if not task.done()]
|
||||
if not jobs:
|
||||
return
|
||||
# This is a completion guard, not a production latency/SLA limit.
|
||||
# Large field sets and an overloaded local runner can exceed 15s.
|
||||
await asyncio.wait_for(asyncio.gather(*jobs), timeout=min(60, self.args.phase_timeout))
|
||||
raise AssertionError("Background jobs did not become idle")
|
||||
|
||||
async def bump(self, games=None):
|
||||
from sqlalchemy import select
|
||||
from hockey_data.async_work import run_db
|
||||
from hockey_data.models import Game
|
||||
games = list(games or self.ticks)
|
||||
def update():
|
||||
with self.db.session() as session:
|
||||
for game in games:
|
||||
row = session.scalar(select(Game).where(Game.external_id == game))
|
||||
row.changes += 1
|
||||
self.ticks[game] = row.changes
|
||||
await run_db(update)
|
||||
|
||||
async def tick(self, *, wait=True):
|
||||
# Accelerated logical source ticks; no claim is made about real-time RPS.
|
||||
for key in list(self.hub._auto_refresh_next):
|
||||
self.hub._auto_refresh_next[key] = 0
|
||||
return await self.hub.auto_refresh_once(wait=wait)
|
||||
|
||||
def expected(self, name):
|
||||
person = self.people[name]
|
||||
return f"{person['game']}|{person['device']}|{name}|{self.ticks[person['game']]}"
|
||||
|
||||
def verify_all_current(self, names=None):
|
||||
for name in names or self.people:
|
||||
assert self.sockets[name].values, f"No acknowledged values for {name}"
|
||||
assert len(self.sockets[name].values) == self.args.fields
|
||||
assert set(self.sockets[name].values.values()) == {self.expected(name)}, (name, self.sockets[name].values)
|
||||
|
||||
async def reject_viewer_write(self, name):
|
||||
response = await self.http.post("/api/hockey/context/batch", headers=await self.headers(name),
|
||||
json={"values": {"selected_player_id": "FORBIDDEN"}, "context": {"game_id": self.people[name]["game"],
|
||||
"device_id": self.people[name]["device"], "session_token": self.tokens[name]}})
|
||||
assert response.status_code == 403, response.text
|
||||
self.viewer_rejections += 1
|
||||
|
||||
async def update_selection(self, name, suffix):
|
||||
person = self.people[name]
|
||||
response = await self.http.post("/api/hockey/context/batch", headers=await self.headers(name),
|
||||
json={"values": {"selected_player_id": person["game"] + "-PLAYER-" + suffix},
|
||||
"context": {"game_id": person["game"], "device_id": person["device"], "session_token": self.tokens[name]}})
|
||||
assert response.status_code == 200, response.text
|
||||
self.expected_selections[name] = person["game"] + "-PLAYER-" + suffix
|
||||
assert (response.json().get("mapping_apply") or {}).get("ok", True), response.text
|
||||
return response.json()
|
||||
|
||||
async def verify_context_scopes(self):
|
||||
from hockey_data.async_work import run_db
|
||||
def inspect():
|
||||
for name, person in self.people.items():
|
||||
context, _ = self.hub.mapping_data.resolve_context(self.users[name], {
|
||||
"game_id": person["game"], "device_id": person["device"], "session_token": self.tokens[name]})
|
||||
assert context.get("selected_player_id", "") == self.expected_selections.get(name, ""), (name, context)
|
||||
await run_db(inspect)
|
||||
|
||||
async def poll_viewers(self):
|
||||
try:
|
||||
while not self.stop_polling.is_set():
|
||||
async def read(name):
|
||||
start = time.perf_counter()
|
||||
response = await self.http.get(f"/api/hockey/games/{self.people[name]['game']}/control",
|
||||
headers=self.basic_headers(name))
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json()["control_access"]["game_id"] == self.people[name]["game"]
|
||||
self.read_ms.append((time.perf_counter() - start) * 1000)
|
||||
self.viewer_reads += 1
|
||||
await asyncio.gather(*(read(f"view{i}") for i in range(1, 4)))
|
||||
await asyncio.wait_for(self.health_probe(), timeout=2)
|
||||
try:
|
||||
await asyncio.wait_for(self.stop_polling.wait(), timeout=0.05)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
except Exception as error:
|
||||
self.polling_errors.append(repr(error))
|
||||
raise
|
||||
|
||||
async def health_probe(self):
|
||||
started = time.perf_counter()
|
||||
response = await self.http.get("/harness-health")
|
||||
assert response.status_code == 200 and response.json()["ok"], response.text
|
||||
self.health_ms.append((time.perf_counter() - started) * 1000)
|
||||
return response
|
||||
|
||||
async def observe_event_loop(self):
|
||||
while not self.stop_polling.is_set():
|
||||
expected = time.perf_counter() + .1
|
||||
await asyncio.sleep(.1)
|
||||
now = time.perf_counter()
|
||||
self.loop_lag_ms.append(max(0.0, (now - expected) * 1000))
|
||||
pending = self.hub._pending_commands
|
||||
self.max_pending_acks = max(self.max_pending_acks, len(pending))
|
||||
for request in pending:
|
||||
self.pending_ack_ages_ms.append(max(0.0, (now - self.request_started.get(request, now)) * 1000))
|
||||
|
||||
async def steady_load(self):
|
||||
for n in range(self.args.ticks):
|
||||
await self.refresh_leases()
|
||||
await self.bump()
|
||||
await asyncio.gather(*(self.update_selection(f"op{i}", str(n)) for i in range(1, 4)))
|
||||
await self.tick()
|
||||
self.verify_all_current()
|
||||
if n % 5 == 0:
|
||||
await asyncio.gather(*(self.reject_viewer_write(f"view{i}") for i in range(1, 4)))
|
||||
if (n + 1) % 10 == 0 or n + 1 == self.args.ticks:
|
||||
print(f"harness steady_load tick={n + 1}/{self.args.ticks} frames={len(self.frames)} reads={self.viewer_reads}",
|
||||
file=sys.stderr, flush=True)
|
||||
|
||||
async def refresh_leases(self, *, force=False):
|
||||
# Browser clients renew the 90-second control lease. Long offline load
|
||||
# must exercise that same API rather than bypass expiry in the fixture.
|
||||
if not force and time.monotonic() - self.last_heartbeat < 15:
|
||||
return
|
||||
for game, name in self.controllers.items():
|
||||
response = await self.http.post(f"/api/hockey/games/{game}/access/heartbeat",
|
||||
headers=await self.headers(name), json={})
|
||||
assert response.status_code == 200, (name, response.text)
|
||||
self.heartbeat_requests += 1
|
||||
self.last_heartbeat = time.monotonic()
|
||||
|
||||
async def negative_ack(self):
|
||||
name = "op2"
|
||||
ws = self.sockets[name]
|
||||
ws.reject_next = 2 # Exhaust one bounded SetText retry for the same field.
|
||||
await self.bump(["M2"])
|
||||
await self.tick()
|
||||
device = self.people[name]["device"]
|
||||
assert ws.negative_acks == 2
|
||||
cache = self.hub._mapping_value_cache
|
||||
assert not any(key[0] == device and key[4] == "Payload000.Text" and value == self.expected(name)
|
||||
for key, value in cache.items()), "Negative ACK incorrectly populated confirmed cache"
|
||||
assert ws.values["Payload000.Text"] != self.expected(name)
|
||||
await self.tick()
|
||||
self.verify_all_current()
|
||||
|
||||
async def slow_source(self):
|
||||
self.slow_match = "M1"
|
||||
self.slow_entered.clear()
|
||||
self.slow_release.clear()
|
||||
await self.bump()
|
||||
try:
|
||||
await self.tick(wait=False)
|
||||
other_jobs = [task for device, task in self.hub._auto_refresh_jobs.items()
|
||||
if not device.endswith("-1")]
|
||||
assert other_jobs, "Other matches were not dispatched"
|
||||
await asyncio.wait_for(self.slow_entered.wait(), timeout=3)
|
||||
await asyncio.wait_for(asyncio.gather(*other_jobs), timeout=3)
|
||||
assert not self.slow_release.is_set()
|
||||
self.verify_all_current(["op2", "view2", "op3", "view3"])
|
||||
response = await asyncio.wait_for(self.health_probe(), timeout=1)
|
||||
assert response.json()["ok"]
|
||||
finally:
|
||||
self.slow_release.set()
|
||||
self.slow_match = ""
|
||||
await self.drain()
|
||||
self.verify_all_current()
|
||||
|
||||
async def reconnect(self):
|
||||
name = "view3"
|
||||
old = self.sockets[name]
|
||||
old.hold_next = True
|
||||
await self.bump(["M3"])
|
||||
task = asyncio.create_task(self.hub.apply_mapping_to_device(self.people[name]["device"],
|
||||
source_codes={"probe"}, only_changed=True, reason="sql_auto_refresh"))
|
||||
await asyncio.wait_for(old.held_arrived.wait(), timeout=3)
|
||||
packet = old.held[0]
|
||||
# A response from another Agent must not release this request.
|
||||
await self.hub.receive_command_ack(self.people["op2"]["device"], {
|
||||
"request_id": packet["request_id"], "ok": True,
|
||||
"assignment_id": packet["assignment_id"], "match_id": packet["match_id"]})
|
||||
await asyncio.sleep(0)
|
||||
assert not task.done(), "Wrong-device ACK accepted"
|
||||
await self.hub.unregister(self.people[name]["device"], old)
|
||||
new = HarnessSocket(self, name)
|
||||
self.sockets[name] = new
|
||||
await self.hub.register(new, self.hello(name))
|
||||
await self.hub.reconcile_device(self.people[name]["device"])
|
||||
assert not new.command_packets, "Reconnect sent values before fresh inventory"
|
||||
await old.release_held()
|
||||
stale = await asyncio.wait_for(task, timeout=5)
|
||||
assert not stale["ok"] and stale["applied"] == 0, stale
|
||||
await self.hub.receive_inventory(self.people[name]["device"], {"type": "vmix.inventory",
|
||||
"inventory": {**self.inventory, "fingerprint": self.fingerprint}})
|
||||
await self.drain()
|
||||
await self.tick()
|
||||
self.verify_all_current()
|
||||
|
||||
async def handoff(self):
|
||||
name = "op1"
|
||||
old = self.sockets[name]
|
||||
old.hold_next = True
|
||||
old.held_arrived.clear()
|
||||
await self.bump(["M1"])
|
||||
pending = asyncio.create_task(self.hub.apply_mapping_to_device(self.people[name]["device"],
|
||||
source_codes={"probe"}, only_changed=True, reason="sql_auto_refresh"))
|
||||
await asyncio.wait_for(old.held_arrived.wait(), timeout=3)
|
||||
before = {f"M{i}": (await self.headers(f"op{i}"))["X-Hockey-Control-Generation"] for i in (2, 3)}
|
||||
response = await self.http.post("/api/hockey/games/M1/access/transfer", headers=await self.headers(name),
|
||||
json={"participant_id": self.people["view1"]["participant"]})
|
||||
assert response.status_code == 200, response.text
|
||||
self.controllers["M1"] = "view1"
|
||||
for _ in range(25):
|
||||
if self.hub._mapping_generations.get(self.people[name]["device"], 0) > old.held_generation:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
assert self.hub._mapping_generations.get(self.people[name]["device"], 0) > old.held_generation
|
||||
await old.release_held()
|
||||
stale = await asyncio.wait_for(pending, timeout=5)
|
||||
assert not stale["ok"] and stale["applied"] == 0, stale
|
||||
await self.reject_viewer_write("op1")
|
||||
old_heartbeat = await self.http.post("/api/hockey/games/M1/access/heartbeat",
|
||||
headers=await self.headers("op1"), json={})
|
||||
assert old_heartbeat.status_code == 403, old_heartbeat.text
|
||||
self.expected_old_controller_heartbeat_rejections += 1
|
||||
await self.refresh_leases(force=True) # M1 now renews only through view1.
|
||||
await self.update_selection("view1", "AFTER-HANDOFF")
|
||||
await self.drain()
|
||||
await self.tick()
|
||||
self.verify_all_current()
|
||||
for i in (2, 3):
|
||||
assert (await self.headers(f"op{i}"))["X-Hockey-Control-Generation"] == before[f"M{i}"]
|
||||
|
||||
def assert_isolation(self):
|
||||
for game, device, account, assignment in self.source_contexts:
|
||||
assert account in self.people and self.people[account]["game"] == game
|
||||
assert self.people[account]["device"] == device and assignment == self.people[account]["assignment"]
|
||||
assert not self.polling_errors
|
||||
assert not self.source_errors, self.source_errors
|
||||
assert not self.background_mapping_failures, self.background_mapping_failures
|
||||
assert not self.transport_contract_errors, self.transport_contract_errors
|
||||
assert not self.hub._pending_commands, "Leaked command ACK futures"
|
||||
assert not any(not task.done() for task in self.hub._auto_refresh_jobs.values())
|
||||
assert not any(not task.done() for task in self.hub._mapping_recovery_jobs.values())
|
||||
|
||||
async def run(self):
|
||||
poller = observer = None
|
||||
try:
|
||||
for name in ("bootstrap", "steady_load", "negative_ack", "slow_source", "reconnect", "handoff"):
|
||||
started = time.perf_counter()
|
||||
self.current_phase = name
|
||||
print(f"harness phase={name} started", file=sys.stderr, flush=True)
|
||||
if name != "bootstrap":
|
||||
await self.refresh_leases(force=True)
|
||||
await asyncio.wait_for(getattr(self, name)(), timeout=self.args.phase_timeout)
|
||||
self.phase_results.append({"phase": name, "ok": True,
|
||||
"seconds": round(time.perf_counter() - started, 3)})
|
||||
print(f"harness phase={name} passed seconds={self.phase_results[-1]['seconds']}", file=sys.stderr, flush=True)
|
||||
if name == "bootstrap":
|
||||
poller = asyncio.create_task(self.poll_viewers())
|
||||
observer = asyncio.create_task(self.observe_event_loop())
|
||||
self.stop_polling.set()
|
||||
if poller is not None:
|
||||
await poller
|
||||
if observer is not None:
|
||||
await observer
|
||||
await self.drain()
|
||||
await self.verify_context_scopes()
|
||||
self.assert_isolation()
|
||||
assert self.viewer_reads > 0 and self.health_requests > 0
|
||||
return self.report(True)
|
||||
finally:
|
||||
self.slow_release.set()
|
||||
self.stop_polling.set()
|
||||
if poller is not None and not poller.done():
|
||||
await asyncio.gather(poller, return_exceptions=True)
|
||||
if observer is not None and not observer.done():
|
||||
await asyncio.gather(observer, return_exceptions=True)
|
||||
await self.hub.stop_auto_refresh()
|
||||
await self.service.stop_live_refreshes()
|
||||
await self.service.client.aclose()
|
||||
await self.http.aclose()
|
||||
self.db.engine.dispose()
|
||||
|
||||
def report(self, ok):
|
||||
source_identity_errors = sum(1 for game, device, account, assignment in self.source_contexts
|
||||
if account not in self.people or self.people[account]["game"] != game
|
||||
or self.people[account]["device"] != device or assignment != self.people[account].get("assignment"))
|
||||
unexpected = (len(self.source_errors) + len(self.transport_contract_errors)
|
||||
+ len(self.polling_errors) + source_identity_errors + len(self.background_mapping_failures))
|
||||
return {"ok": ok, "offline": True, "instrumentation": "source_exceptions_and_background_results_v2",
|
||||
"matches": 3, "accounts": 6, "agents": 6,
|
||||
"shared_mapping_profiles": 1, "logical_ticks": self.args.ticks, "fields_per_agent": self.args.fields,
|
||||
"phases": self.phase_results, "command_frames": len(self.frames),
|
||||
"negative_acks": sum(ws.negative_acks for ws in self.sockets.values()),
|
||||
"expected_negative_acks": 2,
|
||||
"unexpected_failures": unexpected + (0 if ok else 1),
|
||||
"isolation_violations": source_identity_errors + len(self.transport_contract_errors),
|
||||
"after_drain": {"pending_ack_futures": len(self.hub._pending_commands),
|
||||
"unfinished_refresh_jobs": sum(not task.done() for task in self.hub._auto_refresh_jobs.values()),
|
||||
"unfinished_recovery_jobs": sum(not task.done() for task in self.hub._mapping_recovery_jobs.values()),
|
||||
"continuous_scheduler_started": False,
|
||||
"observation": "after_successful_drain" if ok else "after_failure_cleanup"},
|
||||
"source_calls_by_match": dict(self.source_calls), "sql_statements": dict(self.sql),
|
||||
"expected_background_mapping_failures": self.expected_background_mapping_failures,
|
||||
"source_gate_observations": self.source_gate_observations,
|
||||
"health_latency_ms": {"p95": percentile(self.health_ms, .95),
|
||||
"max": round(max(self.health_ms), 3) if self.health_ms else None},
|
||||
"loop_lag_ms": {"p95": percentile(self.loop_lag_ms, .95),
|
||||
"max": round(max(self.loop_lag_ms), 3) if self.loop_lag_ms else None},
|
||||
"pending_ack_observations": {"peak_count": self.max_pending_acks,
|
||||
"max_age_ms": round(max(self.pending_ack_ages_ms), 3) if self.pending_ack_ages_ms else 0},
|
||||
"viewer_reads": self.viewer_reads, "viewer_write_rejections": self.viewer_rejections,
|
||||
"health_requests": self.health_requests,
|
||||
"controller_lease_heartbeats": self.heartbeat_requests,
|
||||
"expected_old_controller_heartbeat_rejections": self.expected_old_controller_heartbeat_rejections,
|
||||
"read_latency_ms": {"p50": percentile(self.read_ms, .5), "p95": percentile(self.read_ms, .95),
|
||||
"max": round(max(self.read_ms), 3) if self.read_ms else None},
|
||||
"simulated_ack_ms": {"p50": percentile(self.ack_ms, .5), "p95": percentile(self.ack_ms, .95)},
|
||||
"isolation_checked_frames": len(self.frames), "limits": [
|
||||
"SQLite fixture, not PostgreSQL locks or production throughput",
|
||||
"in-process ASGI and WebSocket doubles, not TCP/proxy/TLS or Windows Agent execution",
|
||||
"synthetic identity SQL and logical ticks, not real Stat2TV/KHL rate limits or timing",
|
||||
"no browser UI/JavaScript or real native Countdown validation"],
|
||||
"error_counters": {"unexpected_sql_source_errors": len(self.source_errors),
|
||||
"unexpected_background_mapping_failures": len(self.background_mapping_failures),
|
||||
"transport_contract_errors": len(self.transport_contract_errors), "viewer_poll_errors": len(self.polling_errors),
|
||||
"source_identity_errors": source_identity_errors}}
|
||||
|
||||
|
||||
class HarnessSocket:
|
||||
def __init__(self, scenario, name):
|
||||
self.scenario, self.name = scenario, name
|
||||
self.client = SimpleNamespace(host="127.0.0.1")
|
||||
self.sent, self.command_packets, self.held = [], [], []
|
||||
self.values = {}
|
||||
self.reject_next = self.negative_acks = 0
|
||||
self.hold_next = self.closed = False
|
||||
self.held_arrived = asyncio.Event()
|
||||
self.held_generation = 0
|
||||
|
||||
async def send_json(self, message):
|
||||
packet = json.loads(json.dumps(message))
|
||||
self.sent.append(packet)
|
||||
if packet.get("type") != "vmix.command":
|
||||
return
|
||||
scenario = self.scenario
|
||||
person = scenario.people[self.name]
|
||||
scenario.frames.append(packet)
|
||||
scenario.request_started[packet["request_id"]] = time.perf_counter()
|
||||
command = packet["command"]
|
||||
parts = str(command["Value"]).split("|")
|
||||
valid = (packet["device_id"] == person["device"] and packet["match_id"] == person["game"]
|
||||
and packet["assignment_id"] == person.get("assignment")
|
||||
and command["Function"] == "SetText"
|
||||
and parts[:3] == [person["game"], person["device"], self.name]
|
||||
and command["SelectedName"].startswith("Payload"))
|
||||
if not valid:
|
||||
scenario.transport_contract_errors.append({"recipient": self.name, "frame": packet})
|
||||
raise AssertionError((self.name, packet))
|
||||
self.command_packets.append(packet)
|
||||
pending = [item for item in scenario.hub._pending_commands.values() if item[0] == person["device"]]
|
||||
if len(pending) != 1:
|
||||
scenario.transport_contract_errors.append({"recipient": self.name, "pending": len(pending)})
|
||||
raise AssertionError("More than one Mapping command in flight for one Agent")
|
||||
if self.hold_next:
|
||||
self.hold_next = False
|
||||
self.held.append(packet)
|
||||
self.held_generation = scenario.hub._mapping_generations.get(person["device"], 0)
|
||||
self.held_arrived.set()
|
||||
return
|
||||
success = self.reject_next <= 0
|
||||
if not success:
|
||||
self.reject_next -= 1
|
||||
self.negative_acks += 1
|
||||
await self.ack(packet, success)
|
||||
|
||||
async def ack(self, packet, success=True):
|
||||
started = time.perf_counter()
|
||||
await asyncio.sleep(self.scenario.args.ack_delay_ms / 1000)
|
||||
if success:
|
||||
self.values[packet["command"]["SelectedName"]] = packet["command"]["Value"]
|
||||
await self.scenario.hub.receive_command_ack(self.scenario.people[self.name]["device"], {
|
||||
"type": "command.ack", "request_id": packet["request_id"], "assignment_id": packet["assignment_id"],
|
||||
"match_id": packet["match_id"], "ok": success, "reason": "" if success else "injected HTTP 500"})
|
||||
self.scenario.ack_ms.append((time.perf_counter() - started) * 1000)
|
||||
self.scenario.request_started.pop(packet["request_id"], None)
|
||||
|
||||
async def release_held(self):
|
||||
packets, self.held = self.held, []
|
||||
for packet in packets:
|
||||
await self.ack(packet)
|
||||
|
||||
async def close(self, **_kwargs):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--project", type=Path, default=Path(__file__).resolve().parents[1],
|
||||
help="Project root (defaults to the parent of tests/ when installed)")
|
||||
modes = parser.add_mutually_exclusive_group()
|
||||
modes.add_argument("--run", action="store_true", help="Run only after the main suite is green")
|
||||
modes.add_argument("--plan", action="store_true", help="Print plan only (default)")
|
||||
parser.add_argument("--ticks", type=int, default=30)
|
||||
parser.add_argument("--fields", type=int, default=24)
|
||||
parser.add_argument("--ack-delay-ms", type=float, default=1)
|
||||
parser.add_argument("--phase-timeout", type=float, default=180)
|
||||
parser.add_argument("--db-workers", type=int, default=4)
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args()
|
||||
project = args.project.resolve()
|
||||
if not (project / "tests/support.py").is_file():
|
||||
parser.error("--project must contain the Hockey source and tests/support.py")
|
||||
if not 1 <= args.ticks <= 10000 or not 2 <= args.fields <= 200 or not 4 <= args.db_workers <= 32:
|
||||
parser.error("ticks 1..10000, fields 2..200, db-workers 4..32 (M1 blocks two source workers)")
|
||||
if not args.run:
|
||||
print(json.dumps({"status": "prepared_not_run", "phases": PHASES,
|
||||
"ticks": args.ticks, "fields_per_agent": args.fields,
|
||||
"estimated_base_commands": args.ticks * args.fields * 6}, indent=2))
|
||||
return
|
||||
sys.path.insert(0, str(project))
|
||||
def denied(*_args, **_kwargs):
|
||||
raise AssertionError("External sockets are disabled by the offline harness")
|
||||
socket.socket.connect = denied
|
||||
socket.socket.connect_ex = denied
|
||||
socket.create_connection = denied
|
||||
os.environ["HOCKEY_DB_WORKERS"] = str(args.db_workers)
|
||||
with tempfile.TemporaryDirectory(prefix="hockey-multi-match-") as temp:
|
||||
directory = Path(temp)
|
||||
os.environ["HOCKEY_UI_DATA_DIR"] = str(directory / "settings/local")
|
||||
scenario = None
|
||||
async def run():
|
||||
nonlocal scenario
|
||||
scenario = Scenario(project, directory, args)
|
||||
return await scenario.run()
|
||||
try:
|
||||
report = asyncio.run(run())
|
||||
except Exception as error:
|
||||
report = scenario.report(False) if scenario else {"ok": False}
|
||||
report.update(error=repr(error), traceback=traceback.format_exc())
|
||||
rendered = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(rendered + "\n", encoding="utf-8")
|
||||
print(rendered)
|
||||
raise SystemExit(0 if report["ok"] else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
308
tests/runtime_timer_contracts.cjs
Normal file
308
tests/runtime_timer_contracts.cjs
Normal file
@@ -0,0 +1,308 @@
|
||||
// Run actual production functions in a VM; mocks cover I/O and DOM only.
|
||||
// vMix29: SuspendCountdown pauses only; StopCountdown resets; PauseCountdown toggles.
|
||||
// https://www.vmix.com/help29/ShortcutFunctionReference.html
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const path = require('node:path');
|
||||
const assert = require('node:assert/strict');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../ui_builder/static/app.js'), 'utf8');
|
||||
function extract(name) {
|
||||
const start = source.search(new RegExp('^ (?:async )?function ' + name + '\\(', 'm'));
|
||||
assert.ok(start >= 0, `missing production function ${name}`);
|
||||
const end = source.indexOf('\n }', start);
|
||||
assert.ok(end > start, `missing function end ${name}`);
|
||||
return source.slice(start, end + 4);
|
||||
}
|
||||
function runtime(extra = []) {
|
||||
const noop = () => {};
|
||||
const game = { action_id:'hockey_game_timer', type:'timer', props:{mode:'count_down',startTime:'20:00'} };
|
||||
const boardComponent = { action_id:'penalties', type:'hockey_penalty_dashboard', props:{} };
|
||||
const main = { currentMs:1200000, running:false, paused:true, startedOnce:false, finished:false,
|
||||
reached:{}, lastTimestamp:1000 };
|
||||
const board = { penalties:[], selectedEventId:null };
|
||||
const target = {id:'home-slot',input:'Penalty Home',selected_name:'Penalty.Text',overlay:'2'};
|
||||
const step = {id:'clock-step',enabled:true,type:'hockey_vmix_timers_start',sync_vmix_game:true,
|
||||
game_timer_action_id:game.action_id,game_vmix_input:'Score',game_vmix_selected_name:'Clock.Text',
|
||||
game_vmix_mode:'countdown',sync_vmix_penalties:false,start_web_game:true,start_web_penalties:false,
|
||||
hockey_timer_command:'toggle',home_penalty_targets:[target],away_penalty_targets:[]};
|
||||
const sequence = {id:'clock-sequence',enabled:true,steps:[step]};
|
||||
const sent = [], events = [], order = [];
|
||||
const state = {config:{components:[game,boardComponent],shortcut_sequences:[sequence]},
|
||||
activeHockeyVmixTimerSteps:new Set(),vmixGameCountdownSeededTargets:new Set(),
|
||||
vmixPenaltyTargetAssignments:new Map(),vmixPenaltyMirrors:new Map(),vmixTimerMirrors:new Map(),
|
||||
hockeyPenaltyAdvantageCycle:{hadAdvantage:false,lastAdvantageSide:''},vmixOverlayRuntime:new Map(),
|
||||
runningShortcutSequences:new Set(),pendingShortcutSequenceRuns:new Map(),data:{}};
|
||||
let allowed = true;
|
||||
const compact = raw => Object.fromEntries(Object.entries(raw).map(([key,value])=>[key,typeof value==='function'?value():value]));
|
||||
const context = {console,performance:{now:()=>1000},state,boot:{mode:'runtime'},
|
||||
padTimer:value=>String(value).padStart(2,'0'),clamp:(n,l,h)=>Math.max(l,Math.min(h,n)),
|
||||
hockeyCanControl:()=>allowed,componentByActionId:id=>id===game.action_id?game:id===boardComponent.action_id?boardComponent:null,
|
||||
isTimerComponent:c=>c===game,ensureTimerState:()=>main,
|
||||
ensureHockeyBoardState:()=>board,hockeyEventReady:event=>Boolean(event.ready!==false && event.durationMs>0),
|
||||
currentHockeyPenaltyEntries:()=>board.penalties.filter(event=>!event.finished && context.hockeyEventReady(event)).map(event=>({component:boardComponent,event,side:event.side})),
|
||||
sequencePenaltyTargets:(s,side)=>s[side+'_penalty_targets'],
|
||||
penaltyDisplayEntriesByTargetSide:()=>({home:context.currentHockeyPenaltyEntries(),away:[]}),
|
||||
rememberPenaltyAdvantagePlan:noop,hockeyScoreboardIsLive:()=>false,
|
||||
emitInteraction:(component,event,detail)=>{events.push({component,event,detail});order.push('event:'+event);},
|
||||
updateTimerNodes:noop,formatTimerValue:()=>String(main.currentMs),persistTimer:noop,
|
||||
timerInitialMilliseconds:c=>context.parseTimerMilliseconds(c.props.startTime),
|
||||
persistHockeyBoard:noop,refreshHockeyBoardNodes:noop,emitHockeyEventUpdated:noop,
|
||||
hockeyPenaltyContext:()=>({}),fireConfiguredTimerFinishActions:noop,
|
||||
timerEndMilliseconds:()=>null,timerMilestones:()=>[],
|
||||
hockeyScheduleTimerSave:noop,addHockeyHistory:noop,hockeyInfractionWebLabel:()=>'',
|
||||
hockeySyncPenaltySideMappingContext:async()=>true,
|
||||
buildShortcutRuntimeContext:()=>({}),sequenceConditionMatches:()=>true,
|
||||
currentRuntimeVmixDeviceId:()=> 'OUTPUT-A',currentRuntimeHockeySessionToken:()=> 'session-a',
|
||||
hockeyMainTimerComponent:()=>game,
|
||||
penaltyFullStrengthSide:()=> 'home',resetPenaltyAdvantageCycle:()=>{state.hockeyPenaltyAdvantageCycle.hadAdvantage=false;state.hockeyPenaltyAdvantageCycle.lastAdvantageSide='';},
|
||||
hockeyClearSelectedPenaltyMappingContext:async()=>true,updateHockeyBoardTickerNodes:noop,
|
||||
getByPath:(object,key)=>key.split('.').reduce((value,part)=>value?.[part],object),
|
||||
hockeyGameClockSnapshot:()=>({formatted:'18:42',milliseconds:1122000}),
|
||||
uid:()=> 'draft-id',clone:value=>JSON.parse(JSON.stringify(value)),closeHockeyInfractionDropdown:noop,
|
||||
applyPresetToHockeyEvent:(_component,event,preset)=>{event.preset=preset;event.durationMs=event.remainingMs=120000;},
|
||||
sendRuntimeVmixTimerSequence:commands=>{order.push('transport');sent.push(commands.map(compact));return new Promise(()=>{});},
|
||||
};
|
||||
const names = ['parseTimerMilliseconds','vmixCountdownValue','vmixGameCountdownControlCommands',
|
||||
'vmixPenaltyCountdownControlCommands','vmixGameCountdownTargetKey','markVmixGameCountdownSeeded',
|
||||
'isVmixGameCountdownSeeded','hockeyTimerSyncStepById','syncActiveVmixGameCountdown',
|
||||
'configuredHockeyVmixGameCountdownTargets','syncConfiguredScoreboardCountdownsToRuntime',
|
||||
'emitTimerEvent','controlTimer','runShortcutSequenceStep','updateSingleTimer',
|
||||
'penaltyMirrorKey','penaltyTargetAssignmentKey','activateConfiguredPenaltyCountdowns',
|
||||
'rebalanceVmixPenaltyTargets','controlHockeyPenalty','hockeyApplyTimerRules',...extra];
|
||||
vm.createContext(context);
|
||||
vm.runInContext([...new Set(names)].map(extract).join('\n'),context);
|
||||
return {context,game,main,board,boardComponent,step,sequence,target,state,sent,events,order,
|
||||
allow:value=>{allowed=value;},clear:()=>{sent.length=events.length=order.length=0;},
|
||||
functions:()=>sent.flat().map(command=>command.Function)};
|
||||
}
|
||||
function functions(commands) {return Array.from(commands,command=>command.Function);}
|
||||
function seededCommands(h,action,value=125000) {
|
||||
return h.context.vmixGameCountdownControlCommands(' Score ',' Clock.Text ',()=>value,action);
|
||||
}
|
||||
const cases = {};
|
||||
cases.first_start = async()=>{
|
||||
const h=runtime();
|
||||
const commands=seededCommands(h,'start',1200000);
|
||||
assert.deepEqual(functions(commands),['SetCountdown','StartCountdown']);
|
||||
assert.equal(commands[0].Value,'00:20:00');
|
||||
assert.ok(commands.every(c=>c.Input==='Score' && c.SelectedName==='Clock.Text'));
|
||||
assert.deepEqual(Array.from(h.context.vmixGameCountdownControlCommands('','Clock.Text',1000,'start')),[]);
|
||||
assert.deepEqual(Array.from(h.context.vmixGameCountdownControlCommands('Score','',1000,'start')),[]);
|
||||
};
|
||||
cases.pause_freezes = async()=>{
|
||||
const h=runtime();
|
||||
for(const action of ['pause','stop']) {
|
||||
let reads=0;
|
||||
const commands=h.context.vmixGameCountdownControlCommands('Score','Clock.Text',()=>{reads++;return 940000;},action);
|
||||
assert.deepEqual(functions(commands),['SuspendCountdown']);
|
||||
assert.equal(reads,0,'pause cannot read/write browser time or reset native duration');
|
||||
assert.ok(commands.every(c=>!('Value' in c)));
|
||||
}
|
||||
};
|
||||
cases.resume_preserves_native = async()=>{
|
||||
const h=runtime();let reads=0;
|
||||
const commands=h.context.vmixGameCountdownControlCommands('Score','Clock.Text',()=>{reads++;return 1200000;},'resume');
|
||||
assert.deepEqual(functions(commands),['StartCountdown']);assert.equal(reads,0);
|
||||
const native={position:83,running:false};
|
||||
for(const c of commands) if(c.Function==='StartCountdown')native.running=true;
|
||||
assert.equal(native.position,83,'resume must keep the native paused position');
|
||||
};
|
||||
cases.explicit_edit = async()=>{
|
||||
const h=runtime();
|
||||
assert.equal(h.context.controlTimer(h.game.action_id,'set_time','16:01'),true);
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StopCountdown']);
|
||||
assert.equal(h.sent[0][0].Value,'00:16:01');assert.equal(h.main.currentMs,961000);
|
||||
h.clear();h.main.running=true;
|
||||
h.context.controlTimer(h.game.action_id,'set_time','05:17');
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StopCountdown','StartCountdown']);
|
||||
assert.equal(h.sent[0][0].Value,'00:05:17');assert.equal(h.main.running,true);
|
||||
};
|
||||
cases.first_edit_before_activation = async()=>{
|
||||
const h=runtime();assert.equal(h.state.activeHockeyVmixTimerSteps.size,0);
|
||||
for(const [event,value] of [['timer_set_time',300000],['timer_reset',1200000],['timer_add_time',1210000],['timer_subtract_time',1190000]]) {
|
||||
h.clear();h.main.currentMs=value;
|
||||
assert.equal(await h.context.syncActiveVmixGameCountdown(h.game,h.main,event),true);
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StopCountdown']);
|
||||
assert.equal(h.sent[0][0].Value,h.context.vmixCountdownValue(value));
|
||||
}
|
||||
};
|
||||
cases.native_events = async()=>{
|
||||
const h=runtime();h.state.activeHockeyVmixTimerSteps.add(h.step.id);
|
||||
await h.context.syncActiveVmixGameCountdown(h.game,h.main,'timer_start',{wasStartedOnce:false});
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StartCountdown']);
|
||||
for(const name of ['timer_pause','timer_stop','timer_finished']) {
|
||||
h.clear();await h.context.syncActiveVmixGameCountdown(h.game,h.main,name);
|
||||
assert.deepEqual(h.functions(),['SuspendCountdown']);
|
||||
}
|
||||
for(const [name,detail] of [['timer_resume',{}],['timer_start',{wasStartedOnce:true}]]) {
|
||||
h.clear();await h.context.syncActiveVmixGameCountdown(h.game,h.main,name,detail);
|
||||
assert.deepEqual(h.functions(),['StartCountdown']);
|
||||
}
|
||||
h.clear();await h.context.syncActiveVmixGameCountdown(h.game,h.main,'timer_restart');
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StartCountdown']);
|
||||
};
|
||||
cases.no_tick_transport = async()=>{
|
||||
const h=runtime();h.state.activeHockeyVmixTimerSteps.add(h.step.id);
|
||||
h.main.running=true;h.main.lastTimestamp=1000;
|
||||
h.main.lastWholeSecond=1200;
|
||||
for(let second=1;second<=60;second++) h.context.updateSingleTimer(h.game,h.main,1000+1000*second);
|
||||
assert.equal(h.main.currentMs,1140000,'web countdown still advances');
|
||||
assert.equal(h.events.filter(e=>e.event==='timer_tick').length,60,'UI receives every second');
|
||||
assert.deepEqual(h.functions(),[],'native vMix clock receives no per-second packets');
|
||||
assert.equal(await h.context.syncActiveVmixGameCountdown(h.game,h.main,'timer_tick'),false);
|
||||
};
|
||||
cases.web_first = async()=>{
|
||||
const h=runtime();
|
||||
const promise=h.context.runShortcutSequenceStep(h.sequence,h.step);
|
||||
assert.equal(h.main.running,true,'web state changes before caller awaits');
|
||||
assert.ok(h.order.indexOf('event:timer_start')<h.order.indexOf('transport'));
|
||||
const result=await promise;assert.equal(result.ok,true);
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StartCountdown']);
|
||||
h.clear();await h.context.runShortcutSequenceStep(h.sequence,h.step);
|
||||
assert.equal(h.main.running,false);assert.deepEqual(h.functions(),['SuspendCountdown']);
|
||||
assert.ok(h.order.indexOf('event:timer_pause')<h.order.indexOf('transport'));
|
||||
};
|
||||
cases.shortcut_resume = async()=>{
|
||||
const h=runtime();h.step.sync_vmix_penalties=true;h.step.start_web_penalties=true;
|
||||
h.board.penalties.push({id:'p1',side:'home',durationMs:120000,remainingMs:120000,running:false,startedOnce:false});
|
||||
await h.context.runShortcutSequenceStep(h.sequence,h.step);
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StartCountdown','SetCountdown','StopCountdown','StartCountdown']);
|
||||
h.clear();await h.context.runShortcutSequenceStep(h.sequence,h.step);
|
||||
assert.deepEqual(h.functions(),['SuspendCountdown','SuspendCountdown']);
|
||||
h.clear();h.main.currentMs=1182000;h.board.penalties[0].remainingMs=102000;
|
||||
await h.context.runShortcutSequenceStep(h.sequence,h.step);
|
||||
assert.deepEqual(h.functions(),['StartCountdown','StartCountdown']);
|
||||
assert.ok(h.sent.flat().every(c=>!('Value'in c)),'resume cannot reseed from delayed web values');
|
||||
};
|
||||
cases.period_base = async()=>{
|
||||
const h=runtime();
|
||||
for(const [minutes,expected] of [[20,'00:20:00'],[5,'00:05:00'],[20,'00:20:00']]) {
|
||||
h.clear();h.main.currentMs=47000;h.main.startedOnce=true;h.main.running=true;
|
||||
h.context.hockeyApplyTimerRules({timer_rules:{minutes}});
|
||||
h.context.controlTimer(h.game.action_id,'reset');
|
||||
assert.equal(h.main.currentMs,minutes*60000);assert.equal(h.main.startedOnce,false);
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StopCountdown']);
|
||||
h.clear();await h.context.runShortcutSequenceStep(h.sequence,h.step);
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StartCountdown']);assert.equal(h.sent[0][0].Value,expected);
|
||||
}
|
||||
};
|
||||
cases.scoreboard_seed = async()=>{
|
||||
const h=runtime();let sent=false;let release;
|
||||
h.context.sendRuntimeVmixTimerSequence=commands=>{sent=true;h.sent.push(commands);return new Promise(r=>{release=r;});};
|
||||
const pending=h.context.syncConfiguredScoreboardCountdownsToRuntime();
|
||||
assert.equal(sent,true);assert.deepEqual(h.functions(),['SetCountdown','StopCountdown']);
|
||||
let finished=false;pending.then(()=>{finished=true;});await Promise.resolve();assert.equal(finished,false);
|
||||
release({ok:true});await pending;assert.equal(finished,true);
|
||||
h.clear();h.main.running=true;
|
||||
await h.context.syncConfiguredScoreboardCountdownsToRuntime();assert.deepEqual(h.functions(),[],'showing scoreboard cannot disturb running native clock');
|
||||
};
|
||||
cases.prepared_penalty = async()=>{
|
||||
const h=runtime();h.step.sync_vmix_penalties=true;h.state.activeHockeyVmixTimerSteps.add(h.step.id);
|
||||
const penalty={id:'p1',side:'home',durationMs:120000,remainingMs:120000,running:false,startedOnce:false};h.board.penalties.push(penalty);
|
||||
await h.context.rebalanceVmixPenaltyTargets({scoreboardActive:true});
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StopCountdown','OverlayInput2In']);
|
||||
assert.equal(penalty.startedOnce,false);assert.equal(penalty.running,false);
|
||||
h.clear();h.context.controlHockeyPenalty(h.boardComponent,penalty.id,'start');
|
||||
assert.equal(penalty.startedOnce,true);assert.deepEqual(h.functions(),['SetCountdown','StopCountdown','StartCountdown']);
|
||||
};
|
||||
cases.penalty_pause = async()=>{
|
||||
const h=runtime();h.step.sync_vmix_penalties=true;h.state.activeHockeyVmixTimerSteps.add(h.step.id);
|
||||
const penalty={id:'p1',side:'home',durationMs:120000,remainingMs:120000,running:false,startedOnce:false};h.board.penalties.push(penalty);
|
||||
h.context.controlHockeyPenalty(h.boardComponent,'p1','start');h.clear();
|
||||
penalty.remainingMs=89000;h.context.controlHockeyPenalty(h.boardComponent,'p1','pause');
|
||||
assert.deepEqual(h.functions(),['SuspendCountdown']);
|
||||
h.clear();h.context.controlHockeyPenalty(h.boardComponent,'p1','start');
|
||||
assert.deepEqual(h.functions(),['StartCountdown']);
|
||||
assert.ok(h.sent.flat().every(c=>!('Value'in c)));
|
||||
};
|
||||
cases.penalty_edit_reset = async()=>{
|
||||
const h=runtime();h.step.sync_vmix_penalties=true;h.state.activeHockeyVmixTimerSteps.add(h.step.id);
|
||||
const penalty={id:'p1',side:'home',durationMs:120000,remainingMs:120000,running:false,startedOnce:false};h.board.penalties.push(penalty);
|
||||
h.context.controlHockeyPenalty(h.boardComponent,'p1','start');h.clear();
|
||||
h.context.controlHockeyPenalty(h.boardComponent,'p1','set_time','01:11');
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StopCountdown','StartCountdown']);assert.equal(h.sent[0][0].Value,'00:01:11');
|
||||
h.clear();h.context.controlHockeyPenalty(h.boardComponent,'p1','reset');
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StopCountdown']);assert.equal(penalty.remainingMs,120000);assert.equal(penalty.running,false);
|
||||
};
|
||||
cases.no_legacy_text_packets = async()=>{
|
||||
const h=runtime();h.step.game_vmix_mode='text';h.step.penalty_vmix_mode='text';
|
||||
await h.context.runShortcutSequenceStep(h.sequence,h.step);
|
||||
assert.deepEqual(h.functions(),['SetCountdown','StartCountdown']);
|
||||
assert.equal(h.state.vmixTimerMirrors.size,0);assert.equal(h.state.vmixPenaltyMirrors.size,0);
|
||||
h.clear();h.context.emitTimerEvent(h.game,'timer_tick',h.main);assert.deepEqual(h.functions(),[]);
|
||||
};
|
||||
cases.target_scope = async()=>{
|
||||
const h=runtime();
|
||||
h.sequence.steps.push({...h.step,id:'same-target'});
|
||||
h.sequence.steps.push({...h.step,id:'disabled-target',enabled:false,game_vmix_input:'Wrong'});
|
||||
h.sequence.steps.push({...h.step,id:'other-timer',game_timer_action_id:'other',game_vmix_input:'Other'});
|
||||
await h.context.syncActiveVmixGameCountdown(h.game,h.main,'timer_set_time');
|
||||
assert.equal(h.sent.flat().length,2);assert.ok(h.sent.flat().every(c=>c.Input==='Score'&&c.SelectedName==='Clock.Text'));
|
||||
h.clear();h.step.game_vmix_selected_name='';h.sequence.steps=[h.step];
|
||||
assert.equal(await h.context.syncActiveVmixGameCountdown(h.game,h.main,'timer_set_time'),false);assert.deepEqual(h.functions(),[]);
|
||||
};
|
||||
cases.busy_timer = async()=>{
|
||||
const h=runtime(['shortcutSequenceTimerControlSteps','runShortcutTimerControlsWhileBusy']);
|
||||
h.main.running=true;h.main.startedOnce=true;
|
||||
h.sequence.steps.push({id:'title-step',enabled:true,type:'vmix_command',function:'Cut'});
|
||||
assert.equal(h.context.runShortcutTimerControlsWhileBusy(h.sequence,{queued:true}),true);
|
||||
assert.equal(h.main.running,false,'busy title sequence cannot delay the next Space pause');
|
||||
assert.deepEqual(h.functions(),['SuspendCountdown']);
|
||||
assert.equal(h.context.shortcutSequenceTimerControlSteps(h.sequence).length,1,'non-timer steps cannot run twice');
|
||||
};
|
||||
cases.penalty_priority = async()=>{
|
||||
const h=runtime(['hockeyPenaltyHasStarted','activeHockeyPenaltyEntries','sortedPenaltyEntries',
|
||||
'penaltyLocalAdvantageSide','penaltyDisplayEntriesByTargetSide']);
|
||||
h.board.penalties.push(
|
||||
{id:'paused',side:'home',durationMs:120000,remainingMs:20000,running:false,startedOnce:true},
|
||||
{id:'running',side:'home',durationMs:120000,remainingMs:80000,running:true,startedOnce:true},
|
||||
{id:'prepared',side:'home',durationMs:120000,remainingMs:120000,running:false,startedOnce:false});
|
||||
assert.deepEqual(Array.from(h.context.sortedPenaltyEntries('home'),entry=>entry.event.id),['running','paused']);
|
||||
const display=h.context.penaltyDisplayEntriesByTargetSide(h.step);
|
||||
assert.equal(display.transitionEntry.event.id,'running');assert.equal(display.away.length,1);assert.equal(display.home.length,0);
|
||||
h.board.penalties[1].running=false;
|
||||
assert.equal(h.context.sortedPenaltyEntries('home')[0].event.id,'paused');
|
||||
};
|
||||
cases.prepared_emission = async()=>{
|
||||
const h=runtime(['createHockeyPenaltyDraft','emitHockeyEventUpdated']);h.step.sync_vmix_penalties=true;
|
||||
const event=h.context.createHockeyPenaltyDraft(h.boardComponent);
|
||||
assert.equal(event.startedOnce,false);assert.equal(event.running,false);assert.equal(event.durationMs,0);
|
||||
assert.equal(event.readyPending,undefined);assert.deepEqual(h.functions(),[]);
|
||||
event.durationMs=event.remainingMs=120000;event.side='home';event.infraction={id:'minor'};event.preset='2';
|
||||
h.context.emitHockeyEventUpdated(h.boardComponent,event,'preset');
|
||||
assert.equal(event.readyPending,true);assert.equal(event.assignedPending,true);
|
||||
assert.equal(event.startedOnce,false);assert.equal(event.running,false);
|
||||
assert.equal(h.state.activeHockeyVmixTimerSteps.has(h.step.id),true);
|
||||
assert.ok(!h.events.some(e=>e.event==='penalty_ready'||e.event==='penalty_assigned'));
|
||||
assert.deepEqual(h.functions(),[],'ready triggers and plate wait for saved authoritative strength');
|
||||
};
|
||||
cases.strength_plate_cycle = async()=>{
|
||||
const h=runtime(['hockeyPenaltyHasStarted','activeHockeyPenaltyEntries','sortedPenaltyEntries',
|
||||
'penaltyLocalAdvantageSide','penaltyDisplayEntriesByTargetSide','rememberPenaltyAdvantagePlan']);
|
||||
const entry=(id,side,remaining=120000)=>({id,side,durationMs:120000,remainingMs:remaining,running:false,startedOnce:false});
|
||||
h.board.penalties.push(entry('h1','home'));let display=h.context.penaltyDisplayEntriesByTargetSide(h.step);
|
||||
assert.equal(display.advantageSide,'away');assert.equal(display.away.length,1,'ready, not started penalty already owns a plate');
|
||||
h.context.rememberPenaltyAdvantagePlan(display);assert.equal(h.state.hockeyPenaltyAdvantageCycle.hadAdvantage,true);
|
||||
h.board.penalties.push(entry('a1','away'));
|
||||
display=h.context.penaltyDisplayEntriesByTargetSide(h.step);
|
||||
assert.equal(display.holdingEqualStrength,true);assert.equal(display.away.length,1);assert.equal(display.home.length,0);
|
||||
h.state.hockeyPenaltyAdvantageCycle={hadAdvantage:false,lastAdvantageSide:''};
|
||||
display=h.context.penaltyDisplayEntriesByTargetSide(h.step);
|
||||
assert.equal(display.holdingEqualStrength,false);assert.equal(display.home.length+display.away.length,0);
|
||||
};
|
||||
cases.full_strength_waits_ready = async()=>{
|
||||
for(const method of ['manual','tick'])for(const ready of [true,false]){
|
||||
const h=runtime(['updateHockeyPenaltyBoards']);const completed=[];
|
||||
h.context.fireConfiguredTimerFinishActions=(_source,detail)=>completed.push(detail);
|
||||
h.state.hockeyPenaltyAdvantageCycle={hadAdvantage:true,lastAdvantageSide:'away'};
|
||||
h.board.penalties.push({id:'ending',side:'home',durationMs:120000,remainingMs:100,running:true,startedOnce:true,lastTimestamp:1000},
|
||||
{id:'waiting',side:'home',durationMs:ready?120000:0,remainingMs:ready?120000:0,running:false,startedOnce:false,ready});
|
||||
if(method==='manual')assert.equal(h.context.controlHockeyPenalty(h.boardComponent,'ending','finish'),true);
|
||||
else h.context.updateHockeyPenaltyBoards(1200);
|
||||
for(let turn=0;turn<5;turn++)await Promise.resolve();
|
||||
assert.equal(completed.length,1,method);
|
||||
assert.equal(completed[0].remaining_total,ready?1:0,`${method}: complete prepared penalty counts; incomplete draft does not`);
|
||||
assert.equal(h.state.hockeyPenaltyAdvantageCycle.hadAdvantage,ready,method);
|
||||
}
|
||||
};
|
||||
(async()=>{const scenario=process.argv[2];assert.ok(cases[scenario],`unknown timer scenario ${scenario}`);await cases[scenario]();console.log(`PASS: ${scenario}`);})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
263
tests/runtime_timer_transport.cjs
Normal file
263
tests/runtime_timer_transport.cjs
Normal file
@@ -0,0 +1,263 @@
|
||||
// Behavioral timer contracts using the actual browser functions, offline only.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../ui_builder/static/app.js'), 'utf8');
|
||||
const plain = value => JSON.parse(JSON.stringify(value));
|
||||
function definition(name) {
|
||||
const start = source.search(new RegExp('^ (?:async )?function ' + name + '\\(', 'm'));
|
||||
assert.ok(start >= 0, `Production function missing: ${name}`);
|
||||
const end = source.indexOf('\n }', start);
|
||||
assert.ok(end > start, `Production function boundary missing: ${name}`);
|
||||
return source.slice(start, end + 4);
|
||||
}
|
||||
function runtime(names, extra = {}) {
|
||||
const state = {
|
||||
config: { components: [], shortcut_sequences: [] },
|
||||
pressedShortcutKeys: new Set(), pressedShortcutModifiers: new Set(),
|
||||
activeHockeyVmixTimerSteps: new Set(), vmixPenaltyTargetAssignments: new Map(),
|
||||
vmixPenaltyMirrors: new Map(), vmixGameCountdownSeededTargets: new Set(),
|
||||
runningShortcutSequences: new Set(), pendingShortcutSequenceRuns: new Map(),
|
||||
vmixCommandQueue: new Promise(() => {}),
|
||||
};
|
||||
const context = {
|
||||
state, console: { warn() {}, error() {} },
|
||||
Promise, setTimeout, clearTimeout, queueMicrotask,
|
||||
padTimer: value => String(value).padStart(2, '0'), hockeyCanControl: () => true,
|
||||
currentRuntimeVmixDeviceId: () => 'LIVE-DEVICE',
|
||||
currentRuntimeHockeySessionToken: () => 'match-session',
|
||||
trackRuntimeOverlayCommands() {}, applyServerRuntimeOverlayState() {},
|
||||
...extra,
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(names.map(definition).join('\n'), context);
|
||||
return context;
|
||||
}
|
||||
const nativeNames = ['vmixCountdownValue', 'vmixGameCountdownControlCommands'];
|
||||
const scenarios = {
|
||||
async key_edges_web_first() {
|
||||
const game = { running: false, startedOnce: false, currentMs: 1200000 };
|
||||
const component = { action_id: 'game' };
|
||||
const step = { id: 'timer', type: 'hockey_vmix_timers_start', enabled: true,
|
||||
hockey_timer_command: 'toggle', game_timer_action_id: 'game', start_web_game: true,
|
||||
sync_vmix_game: true, game_vmix_input: 'SCORE', game_vmix_selected_name: 'CLOCK.Text',
|
||||
sync_vmix_penalties: false, start_web_penalties: false };
|
||||
const sequence = { id: 'space', combo: 'Space', enabled: true, steps: [step] };
|
||||
const sends = [], runs = [];
|
||||
const c = runtime([...nativeNames, 'normalizeShortcutCombo', 'shortcutModifierFromEvent',
|
||||
'shortcutKeyFromEvent', 'shortcutPhysicalKeyToken', 'shortcutFromKeyboardEvent',
|
||||
'handleConfiguredShortcuts', 'handleConfiguredShortcutCombo', 'runShortcutSequenceStep'], {
|
||||
shortcutModifierOrder: ['Ctrl', 'Alt', 'Shift', 'Meta'],
|
||||
buildShortcutRuntimeContext: () => ({}), sequenceConditionMatches: () => true,
|
||||
componentByActionId: () => component, isTimerComponent: () => true, ensureTimerState: () => game,
|
||||
sequencePenaltyTargets: () => [], currentHockeyPenaltyEntries: () => [],
|
||||
shortcutSequenceAllowed: () => true,
|
||||
controlTimer: (_id, command, _value, options) => {
|
||||
assert.equal(options.syncVmix, false, 'web transition must not recursively send vMix');
|
||||
game.running = command !== 'pause'; game.startedOnce = true; return true;
|
||||
},
|
||||
sendRuntimeVmixTimerSequence: commands => {
|
||||
sends.push({ commands: plain(commands), running: game.running, started: game.startedOnce });
|
||||
return new Promise(() => {}); // A slow Agent must not block the next physical press.
|
||||
},
|
||||
});
|
||||
c.state.config.shortcut_sequences = [sequence];
|
||||
c.runShortcutSequence = (seq, meta) => {
|
||||
runs.push(meta);
|
||||
return c.runShortcutSequenceStep(seq, step);
|
||||
};
|
||||
const keyUpStart = source.indexOf('window.addEventListener("keyup", (event) => {');
|
||||
assert.ok(keyUpStart >= 0);
|
||||
const keyUpEnd = source.indexOf('\n }, true);', keyUpStart);
|
||||
let keyUp;
|
||||
c.window = { addEventListener: (_type, listener) => { keyUp = listener; } };
|
||||
vm.runInContext(source.slice(keyUpStart, keyUpEnd + '\n }, true);'.length), c);
|
||||
let swallowed = 0;
|
||||
const key = (repeat = false) => ({ key: ' ', code: 'Space', repeat,
|
||||
preventDefault() { swallowed++; }, stopPropagation() {}, stopImmediatePropagation() {} });
|
||||
assert.equal(c.handleConfiguredShortcuts(key()), true);
|
||||
assert.equal(runs.length, 1);
|
||||
assert.equal(game.running, true);
|
||||
assert.equal(sends[0].running, true, 'web state must change before any transport');
|
||||
assert.deepEqual(sends[0].commands.map(row => row.Function), ['SetCountdown', 'StartCountdown']);
|
||||
assert.equal(sends[0].commands[0].Value, '00:20:00');
|
||||
assert.equal(c.handleConfiguredShortcuts(key()), true, 'duplicate physical keydown is swallowed');
|
||||
assert.equal(c.handleConfiguredShortcuts(key(true)), true, 'browser repeat is swallowed');
|
||||
assert.equal(runs.length, 1);
|
||||
keyUp(key());
|
||||
assert.equal(c.state.pressedShortcutKeys.size, 0, 'actual production keyup releases the latch');
|
||||
assert.equal(c.handleConfiguredShortcuts(key()), true);
|
||||
assert.equal(runs.length, 2);
|
||||
assert.equal(game.running, false);
|
||||
assert.equal(sends[1].running, false, 'pause changes web state before transport');
|
||||
assert.deepEqual(sends[1].commands.map(row => row.Function), ['SuspendCountdown']);
|
||||
keyUp(key());
|
||||
assert.equal(c.handleConfiguredShortcuts(key(true)), false, 'orphan auto-repeat cannot trigger a shortcut');
|
||||
assert.equal(runs.length, 2);
|
||||
assert.ok(swallowed >= 4);
|
||||
},
|
||||
async ordered_transport() {
|
||||
const calls = [];
|
||||
let release;
|
||||
const pending = new Promise(resolve => { release = resolve; });
|
||||
const c = runtime(['compactVmixCommand', 'sendRuntimeVmixTimerSequence'], {
|
||||
fetch: (url, options) => { calls.push({ url, options, body: JSON.parse(options.body) }); return pending; },
|
||||
});
|
||||
let value = '00:18:42';
|
||||
const transport = c.sendRuntimeVmixTimerSequence(() => [
|
||||
{ Function: 'SetCountdown', Input: 'SCORE', SelectedName: 'CLOCK.Text', Value: () => value },
|
||||
{ Function: 'StartCountdown', Input: 'SCORE', SelectedName: 'CLOCK.Text' },
|
||||
]);
|
||||
assert.equal(calls.length, 1, 'timer must dispatch without waiting for the permanently blocked generic queue');
|
||||
const sent = calls[0];
|
||||
assert.equal(sent.url, '/api/hockey/vmix/sequence');
|
||||
assert.equal(sent.options.keepalive, true);
|
||||
assert.equal(sent.body.delivery_mode, 'timer-fast-ordered');
|
||||
assert.equal(sent.body.device_id, 'LIVE-DEVICE');
|
||||
assert.equal(sent.body.session_token, 'match-session');
|
||||
assert.equal('sequence_id' in sent.body, false);
|
||||
assert.equal('button_id' in sent.body, false);
|
||||
assert.deepEqual(sent.body.commands.map(row => row.Function), ['SetCountdown', 'StartCountdown']);
|
||||
assert.equal(sent.body.commands[0].Value, value);
|
||||
release({ ok: true, json: async () => ({ ok: true, results: [{ ok: true }, { ok: true }] }) });
|
||||
assert.equal((await transport).ok, true);
|
||||
},
|
||||
async blank_device_fails_closed() {
|
||||
let fetchCount = 0;
|
||||
const web = { running: false, startedOnce: false, currentMs: 1200000 };
|
||||
const component = { action_id: 'game' };
|
||||
const step = { id: 'timer', type: 'hockey_vmix_timers_start', enabled: true,
|
||||
hockey_timer_command: 'toggle', game_timer_action_id: 'game', start_web_game: true,
|
||||
sync_vmix_game: true, game_vmix_input: 'SCORE', game_vmix_selected_name: 'CLOCK.Text',
|
||||
sync_vmix_penalties: false, start_web_penalties: false };
|
||||
const c = runtime([...nativeNames, 'compactVmixCommand', 'sendRuntimeVmixTimerSequence', 'runShortcutSequenceStep'], {
|
||||
currentRuntimeVmixDeviceId: () => '',
|
||||
currentRuntimeHockeySessionToken: () => 'stale-session-with-old-device',
|
||||
fetch: async () => { fetchCount++; return { ok: true, json: async () => ({ ok: true }) }; },
|
||||
buildShortcutRuntimeContext: () => ({}), sequenceConditionMatches: () => true,
|
||||
componentByActionId: () => component, isTimerComponent: () => true, ensureTimerState: () => web,
|
||||
sequencePenaltyTargets: () => [], currentHockeyPenaltyEntries: () => [],
|
||||
controlTimer: (_id, action) => { web.running = action !== 'pause'; web.startedOnce = true; return true; },
|
||||
});
|
||||
const unsent = { input: 'SCORE', eventKey: 'unsent-penalty' };
|
||||
const unrelated = { input: 'OTHER', eventKey: 'unrelated-penalty' };
|
||||
c.state.vmixPenaltyTargetAssignments.set('unsent', unsent);
|
||||
c.state.vmixPenaltyTargetAssignments.set('unrelated', unrelated);
|
||||
const result = await c.sendRuntimeVmixTimerSequence([{ Function: 'StartCountdown', Input: 'SCORE', SelectedName: 'CLOCK.Text' }]);
|
||||
assert.equal(c.state.vmixPenaltyTargetAssignments.has('unsent'), false, 'blank output cannot confirm an unsent target');
|
||||
assert.equal(c.state.vmixPenaltyTargetAssignments.get('unrelated'), unrelated, 'unrelated targets remain intact');
|
||||
assert.equal(fetchCount, 0, 'blank Agent selection must never fall back through the session');
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.reason, 'device_selection_required');
|
||||
await c.runShortcutSequenceStep({ id: 'space' }, step);
|
||||
assert.equal(web.running, true, 'blank output target cannot roll back a local start');
|
||||
assert.equal(web.currentMs, 1200000);
|
||||
await c.runShortcutSequenceStep({ id: 'space' }, step);
|
||||
assert.equal(web.running, false, 'the next local pause must remain usable');
|
||||
assert.equal(fetchCount, 0);
|
||||
},
|
||||
async failed_assignment_cleanup_preserves_newer_delivery() {
|
||||
let reject;
|
||||
const c = runtime(['compactVmixCommand', 'sendRuntimeVmixTimerSequence'], {
|
||||
fetch: () => new Promise((_resolve, fail) => { reject = fail; }),
|
||||
});
|
||||
const older = { input: 'PENALTY', eventKey: 'old' };
|
||||
const newer = { input: 'PENALTY', eventKey: 'new' };
|
||||
c.state.vmixPenaltyTargetAssignments.set('slot', older);
|
||||
const pending = c.sendRuntimeVmixTimerSequence([{ Function: 'SetCountdown', Input: 'PENALTY', SelectedName: 'Clock.Text', Value: '00:02:00' }]);
|
||||
c.state.vmixPenaltyTargetAssignments.set('slot', newer);
|
||||
reject(new Error('older network request failed'));
|
||||
assert.equal((await pending).ok, false);
|
||||
assert.equal(c.state.vmixPenaltyTargetAssignments.get('slot'), newer);
|
||||
},
|
||||
async queued_values_sampled_at_dispatch() {
|
||||
let release;
|
||||
const blocker = new Promise(resolve => { release = resolve; });
|
||||
const calls = [];
|
||||
const c = runtime(['compactVmixCommand', 'sendRuntimeVmixSequence'], {
|
||||
AbortController, window: { setTimeout },
|
||||
fetch: async (url, options) => {
|
||||
calls.push({ url, body: JSON.parse(options.body) });
|
||||
return { ok: true, json: async () => ({ ok: true, results: [{ ok: true }] }) };
|
||||
},
|
||||
});
|
||||
c.state.vmixCommandQueue = blocker;
|
||||
c.state.vmixCommandQueueDepth = 0;
|
||||
let commandReads = 0, valueReads = 0, liveValue = '00:20:00';
|
||||
const target = { Input: 'SCORE', SelectedName: 'CLOCK.Text' };
|
||||
const result = c.sendRuntimeVmixSequence(() => {
|
||||
commandReads++;
|
||||
return [{ Function: 'SetCountdown', ...target, Value: () => { valueReads++; return liveValue; } }];
|
||||
});
|
||||
await Promise.resolve();
|
||||
assert.equal(commandReads, 0, 'command factories must wait for their actual queue turn');
|
||||
assert.equal(valueReads, 0, 'countdown values must not be sampled before dispatch');
|
||||
assert.equal(calls.length, 0);
|
||||
liveValue = '00:19:55';
|
||||
release();
|
||||
assert.equal((await result).ok, true);
|
||||
assert.equal(commandReads, 1);
|
||||
assert.equal(valueReads, 1);
|
||||
assert.deepEqual(calls[0].body.commands, [{ Function: 'SetCountdown', ...target, Value: liveValue }]);
|
||||
assert.equal(c.state.vmixCommandQueueDepth, 0);
|
||||
},
|
||||
async native_first_start() {
|
||||
const c = runtime(nativeNames);
|
||||
let reads = 0;
|
||||
const commands = c.vmixGameCountdownControlCommands('SCORE', 'CLOCK.Text', () => { reads++; return 1200000; }, 'start');
|
||||
assert.deepEqual(plain(commands), [
|
||||
{ Function: 'SetCountdown', Input: 'SCORE', SelectedName: 'CLOCK.Text', Value: '00:20:00' },
|
||||
{ Function: 'StartCountdown', Input: 'SCORE', SelectedName: 'CLOCK.Text' },
|
||||
]);
|
||||
assert.equal(reads, 1);
|
||||
},
|
||||
async native_pause_resume() {
|
||||
const c = runtime(nativeNames);
|
||||
let reads = 0;
|
||||
const provider = () => { reads++; return 999000; };
|
||||
for (const action of ['pause', 'stop']) {
|
||||
const commands = c.vmixGameCountdownControlCommands('SCORE', 'CLOCK.Text', provider, action);
|
||||
assert.deepEqual(plain(commands), [{ Function: 'SuspendCountdown', Input: 'SCORE', SelectedName: 'CLOCK.Text' }]);
|
||||
}
|
||||
assert.deepEqual(plain(c.vmixGameCountdownControlCommands('SCORE', 'CLOCK.Text', provider, 'resume')),
|
||||
[{ Function: 'StartCountdown', Input: 'SCORE', SelectedName: 'CLOCK.Text' }]);
|
||||
assert.equal(reads, 0, 'native pause/resume must not even read or reseed browser time');
|
||||
},
|
||||
async scoreboard_before_overlay() {
|
||||
const game = { running: false, currentMs: 1200000 }, component = { action_id: 'game' };
|
||||
const timerStep = { id: 'timer', enabled: true, type: 'hockey_vmix_timers_start', sync_vmix_game: true,
|
||||
game_vmix_mode: 'countdown', game_timer_action_id: 'game', game_vmix_input: 'SCORE', game_vmix_selected_name: 'CLOCK.Text' };
|
||||
const sequence = { id: 'scoreboard', name: 'Scoreboard', enabled: true, is_scoreboard_sequence: true,
|
||||
steps: [{ id: 'overlay', enabled: true, type: 'vmix_command' }] };
|
||||
const order = [];
|
||||
const c = runtime([...nativeNames, 'vmixGameCountdownTargetKey', 'markVmixGameCountdownSeeded',
|
||||
'configuredHockeyVmixGameCountdownTargets', 'syncConfiguredScoreboardCountdownsToRuntime', 'runShortcutSequence'], {
|
||||
shortcutSequenceIsOnAir: () => false, clone: plain,
|
||||
window: { dispatchEvent() {} }, CustomEvent: class { constructor(type, args) { this.type = type; this.detail = args.detail; } },
|
||||
componentByActionId: () => component, isTimerComponent: () => true, ensureTimerState: () => game,
|
||||
runShortcutSequenceStep: async () => { order.push('overlay'); return { ok: true }; },
|
||||
sendRuntimeVmixTimerSequence: async commands => { order.push(plain(commands)); return { ok: true }; },
|
||||
reconcileShortcutSequenceOnAir() {}, activateConfiguredPenaltyCountdowns() {},
|
||||
rebalanceVmixPenaltyTargets: async () => {}, hockeySyncScoreboardConditionalSteps: async () => {},
|
||||
hockeyTitleMappingNotice: () => '', toast() {},
|
||||
});
|
||||
c.state.config.shortcut_sequences = [{ enabled: true, steps: [timerStep] }];
|
||||
assert.equal(await c.runShortcutSequence(sequence), true);
|
||||
assert.deepEqual(order[0].map(row => row.Function), ['SetCountdown', 'StopCountdown']);
|
||||
assert.equal(order[0][0].Value, '00:20:00');
|
||||
assert.equal(order[1], 'overlay', 'stopped clock seed must reach timer transport before OverlayIn');
|
||||
order.length = 0; game.running = true;
|
||||
assert.equal(await c.runShortcutSequence(sequence), true);
|
||||
assert.deepEqual(order, ['overlay'], 'showing scoreboard cannot rewrite a running native timer');
|
||||
},
|
||||
};
|
||||
module.exports = { definition, runtime, scenarios };
|
||||
if (require.main === module) {
|
||||
(async () => {
|
||||
const scenario = process.argv[2];
|
||||
assert.ok(scenarios[scenario], `Unknown scenario: ${scenario}`);
|
||||
await scenarios[scenario]();
|
||||
console.log(`PASS: ${scenario}`);
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
}
|
||||
@@ -10,6 +10,7 @@ from hockey_data.agent_bridge import VmixAgentHub
|
||||
from hockey_data.auth_bridge import HockeyUser
|
||||
from hockey_data.models import OperatorSession, VmixAssignment, VmixDevice
|
||||
from tests.support import LocalTestDatabase
|
||||
from tests.test_stage1_match_access import env # actual HTTP authority/session fixture
|
||||
|
||||
|
||||
class FakeWebSocket:
|
||||
@@ -373,10 +374,15 @@ def test_saved_mapping_is_resolved_and_pushed_to_vmix(tmp_path: Path) -> None:
|
||||
assert command is not None
|
||||
assert command["command"] == {
|
||||
"Function": "SetText",
|
||||
"Input": "score-key",
|
||||
"Input": "Scorebug",
|
||||
"SelectedName": "HomeTeam.Text",
|
||||
"Value": "СКА",
|
||||
}
|
||||
assert not task.done(), "Saving applied values must wait for this Agent's ACK"
|
||||
assert not hub._mapping_value_cache
|
||||
await hub.receive_command_ack("GFX-UNRELATED", {
|
||||
"type": "command.ack", "request_id": command["request_id"], "ok": True})
|
||||
assert not task.done() and not hub._mapping_value_cache
|
||||
await hub.receive_command_ack(
|
||||
"GFX-MAPPING-APPLY",
|
||||
{
|
||||
@@ -386,6 +392,10 @@ def test_saved_mapping_is_resolved_and_pushed_to_vmix(tmp_path: Path) -> None:
|
||||
)
|
||||
saved = await task
|
||||
assert saved["version"] == 2
|
||||
assert saved["fields"][0]["vmix_input_title"] == "Scorebug"
|
||||
assert saved["fields"][0]["vmix_input_number"] == ""
|
||||
assert any(key[3:5] == ("Scorebug", "HomeTeam.Text") and value == "СКА"
|
||||
for key, value in hub._mapping_value_cache.items())
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
@@ -784,3 +794,44 @@ def test_build90_runtime_shortcut_sequence_uses_one_batch_on_modern_agent(tmp_pa
|
||||
assert result["overlay_state"]["overlays"]["2"]["input"] == "53"
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_explicit_blank_sequence_device_never_reuses_previous_session_binding(env, monkeypatch):
|
||||
from hockey_data.models import MatchControlLease
|
||||
|
||||
assert env.claim().status_code == 200
|
||||
channel = env.service.open_session(wfl_user_id='a', tournament_external_id='t', game_external_id='g')
|
||||
with env.db.session() as session:
|
||||
operator = session.scalar(select(OperatorSession).where(OperatorSession.session_token == channel['token']))
|
||||
operator.vmix_device_uuid = 'GFX-PREVIOUS'
|
||||
device = VmixDevice(device_uuid='GFX-PREVIOUS', device_secret_hash='x', wfl_user_id='a',
|
||||
is_active_for_account=True, current_match_external_id='g', current_assignment_key='previous-assignment')
|
||||
session.add(device)
|
||||
session.flush()
|
||||
session.add(VmixAssignment(device_id=device.id, assignment_key='previous-assignment',
|
||||
wfl_user_id='a', operator_session_token=channel['token'], game_external_id='g', active=True))
|
||||
session.get(MatchControlLease, 'g').owner_device_id = device.device_uuid
|
||||
calls = []
|
||||
|
||||
async def send(user, commands, **kwargs):
|
||||
calls.append((commands, kwargs))
|
||||
return {'ok': True, 'applied': len(commands)}
|
||||
|
||||
monkeypatch.setattr(env.hub, 'run_vmix_sequence_for_user', send)
|
||||
body = {'session_token': channel['token'], 'delivery_mode': 'timer-fast-ordered',
|
||||
'commands': [{'Function': 'StartCountdown', 'Input': 'Score', 'SelectedName': 'Clock.Text'}]}
|
||||
for blank in ('', ' ', '\t\n'):
|
||||
denied = env.client.post('/api/hockey/vmix/sequence', headers=env.headers(), json={**body, 'device_id': blank})
|
||||
assert denied.status_code == 409, denied.text
|
||||
assert denied.json()['detail'] == 'Выберите Agent в этом браузере'
|
||||
assert calls == [], 'A cleared browser selection must never send to its old session Agent'
|
||||
# The previous binding is deliberately retained for older clients that omit
|
||||
# this field. All ordinary session and device permission checks still run.
|
||||
legacy = env.client.post('/api/hockey/vmix/sequence', headers=env.headers(), json=body)
|
||||
assert legacy.status_code == 200, legacy.text
|
||||
assert calls[-1][1]['device_id'] == 'GFX-PREVIOUS'
|
||||
selected = env.client.post('/api/hockey/vmix/sequence', headers=env.headers(), json={**body, 'device_id': 'GFX-PREVIOUS'})
|
||||
assert selected.status_code == 200, selected.text
|
||||
assert len(calls) == 2 and calls[-1][1]['device_id'] == 'GFX-PREVIOUS'
|
||||
foreign = env.client.post('/api/hockey/vmix/sequence', headers=env.headers(), json={**body, 'device_id': 'GFX-FOREIGN'})
|
||||
assert foreign.status_code == 403 and len(calls) == 2
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -10,50 +11,31 @@ def _block(start: str, end: str) -> str:
|
||||
|
||||
|
||||
def test_timer_transport_is_independent_from_generic_vmix_queue():
|
||||
block = _block("function sendRuntimeVmixTimerSequence", "function splitVmixInputs")
|
||||
assert 'fetch("/api/hockey/vmix/sequence"' in block
|
||||
assert 'keepalive: true' in block
|
||||
assert 'state.vmixCommandQueue' not in block
|
||||
assert 'sequence_id' not in block.split('body: JSON.stringify({', 1)[1]
|
||||
assert 'Runtime continues locally' in block
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('web_first')
|
||||
|
||||
|
||||
def test_timer_start_stop_protocol_is_minimal():
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
assert 'if (action === "stop" || action === "pause")' in helper
|
||||
stop_branch = helper.split('if (action === "stop" || action === "pause")', 1)[1].split('return [', 1)[1].split('];', 1)[0]
|
||||
assert 'Function: "SuspendCountdown"' in stop_branch
|
||||
assert 'Function: "StopCountdown"' not in stop_branch
|
||||
assert 'Function: "SetCountdown"' not in stop_branch
|
||||
start_branch = helper.rsplit('return [', 1)[1]
|
||||
assert start_branch.index('Function: "SetCountdown"') < start_branch.index('Function: "StartCountdown"')
|
||||
assert 'PauseCountdown' not in helper
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('first_start')
|
||||
run_timer_contract('pause_freezes')
|
||||
|
||||
|
||||
def test_combined_hockey_timer_shortcut_never_waits_for_agent():
|
||||
block = APP_JS.split('case "hockey_vmix_timers_start":', 1)[1].split('case "delay":', 1)[0]
|
||||
assert 'sendRuntimeVmixTimerSequence(commands);' in block
|
||||
assert 'await sendRuntimeVmixSequence(commands' not in block
|
||||
assert 'fire-and-forget' in block
|
||||
# Local state changes remain ahead of any vMix transport.
|
||||
assert block.index('if (step.start_web_game)') < block.index('if (commands.length) sendRuntimeVmixTimerSequence(commands);')
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('web_first')
|
||||
|
||||
|
||||
def test_main_and_penalty_resync_do_not_use_generic_queue():
|
||||
game = _block("async function syncActiveVmixGameCountdown", "function penaltyMirrorKey")
|
||||
penalty = _block("async function rebalanceVmixPenaltyTargets", "function finishActionMatchesSource")
|
||||
assert 'sendRuntimeVmixTimerSequence(commands);' in game
|
||||
assert 'await sendRuntimeVmixSequence(commands)' not in game
|
||||
assert 'sendRuntimeVmixTimerSequence(commands);' in penalty
|
||||
assert 'await sendRuntimeVmixSequence(commands)' not in penalty
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('native_events')
|
||||
run_timer_contract('penalty_pause')
|
||||
|
||||
|
||||
def test_busy_shortcut_can_toggle_timer_without_waiting_for_title_ack():
|
||||
block = _block("function shortcutSequenceTimerControlSteps", "function handleConfiguredShortcutCombo")
|
||||
assert 'runShortcutTimerControlsWhileBusy(sequence, meta)' in block
|
||||
assert 'timer controls are never queued behind title/Agent ACK traffic' in block
|
||||
assert '["timer_command", "hockey_vmix_timers_start"]' in block
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('busy_timer')
|
||||
|
||||
|
||||
def test_build101_runtime_version():
|
||||
assert 'BUILD_VERSION = "2026.08.24.4"' in APP
|
||||
assert_current_build_contract()
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from hockey_data.agent_bridge import VmixAgentHub
|
||||
from hockey_data.auth_bridge import HockeyUser
|
||||
from tests.support import LocalTestDatabase
|
||||
from tests.timer_contract_support import assert_current_build_contract
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
APP_JS = (ROOT / "ui_builder" / "static" / "app.js").read_text(encoding="utf-8")
|
||||
@@ -26,17 +28,15 @@ class FakeWebSocket:
|
||||
return None
|
||||
|
||||
|
||||
def test_space_edge_is_single_fire_and_local_timer_changes_before_transport() -> None:
|
||||
# One physical Space press fires once; repeats are swallowed until keyup.
|
||||
assert "state.pressedShortcutKeys.has(physicalKey)" in APP_JS
|
||||
assert "if (event.repeat) return false;" in APP_JS
|
||||
assert "state.pressedShortcutKeys.add(physicalKey)" in APP_JS
|
||||
assert "state.pressedShortcutKeys.delete(physicalKey)" in APP_JS
|
||||
assert 'combo: "Space"' in APP_JS
|
||||
def run_transport_contract(scenario: str) -> None:
|
||||
result = subprocess.run(["node", str(ROOT / "tests/runtime_timer_transport.cjs"), scenario],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=15)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert f"PASS: {scenario}" in result.stdout
|
||||
|
||||
block = APP_JS.split('case "hockey_vmix_timers_start":', 1)[1].split('case "delay":', 1)[0]
|
||||
assert block.index("if (step.start_web_game)") < block.index("if (commands.length) sendRuntimeVmixTimerSequence(commands);")
|
||||
assert 'delivery_mode: "timer-fast"' in APP_JS
|
||||
|
||||
def test_space_edge_is_single_fire_and_local_timer_changes_before_transport() -> None:
|
||||
run_transport_contract("key_edges_web_first")
|
||||
|
||||
|
||||
def test_timer_fast_backend_uses_one_no_ack_batch_and_bypasses_mapping_lock(tmp_path: Path) -> None:
|
||||
@@ -117,8 +117,13 @@ def test_timer_fast_backend_uses_one_no_ack_batch_and_bypasses_mapping_lock(tmp_
|
||||
|
||||
|
||||
def test_timer_fast_contract_and_build_version() -> None:
|
||||
assert 'delivery_mode: str = Field(default="", max_length=32)' in BRIDGE
|
||||
assert 'fast_timer = delivery_mode == "timer-fast"' in BRIDGE
|
||||
assert 'transport = "timer-batch-no-ack" if supports_batch else "timer-no-ack"' in BRIDGE
|
||||
assert '"type": "vmix.batch"' in BRIDGE
|
||||
assert 'BUILD_VERSION = "2026.08.24.6"' in APP
|
||||
run_transport_contract("ordered_transport")
|
||||
assert_current_build_contract()
|
||||
|
||||
|
||||
def test_blank_selected_device_cannot_fall_back_to_an_older_session_agent() -> None:
|
||||
run_transport_contract("blank_device_fails_closed")
|
||||
|
||||
|
||||
def test_older_timer_delivery_failure_cannot_clear_newer_penalty_assignment() -> None:
|
||||
run_transport_contract("failed_assignment_cleanup_preserves_newer_delivery")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -10,29 +11,20 @@ def _block(start: str, end: str) -> str:
|
||||
|
||||
|
||||
def test_pause_stop_sends_only_pause_only_command():
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
branch = helper.split('if (action === "stop" || action === "pause")', 1)[1].split('if (action === "set")', 1)[0]
|
||||
assert 'Function: "SuspendCountdown"' in branch
|
||||
assert 'Function: "StopCountdown"' not in branch
|
||||
assert 'Function: "SetCountdown"' not in branch
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('pause_freezes')
|
||||
|
||||
|
||||
def test_explicit_edit_still_can_seed_stopped_clock():
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
branch = helper.split('if (action === "set")', 1)[1].split('return [', 2)[1]
|
||||
assert 'Function: "StopCountdown"' in branch
|
||||
assert 'Function: "SetCountdown"' in branch
|
||||
sync = _block("async function syncActiveVmixGameCountdown", "function penaltyMirrorKey")
|
||||
assert 'timerState.running ? "start" : "set"' in sync
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('explicit_edit')
|
||||
run_timer_contract('first_edit_before_activation')
|
||||
|
||||
|
||||
def test_penalty_pause_preserves_native_vmix_frozen_value():
|
||||
rebalance = _block("async function rebalanceVmixPenaltyTargets", "function finishActionMatchesSource")
|
||||
assert "preservePausedCountdown = false" in rebalance
|
||||
assert "if (!preservePausedCountdown || assignmentChanged)" in rebalance
|
||||
control = _block("function controlHockeyPenalty", "function formatHockeyPenaltyTime")
|
||||
assert 'preservePausedCountdown: command === "pause"' in control
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('penalty_pause')
|
||||
|
||||
|
||||
def test_build104_runtime_version():
|
||||
assert 'BUILD_VERSION = "2026.08.24.7"' in APP
|
||||
assert_current_build_contract()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -10,25 +11,21 @@ def _block(start: str, end: str) -> str:
|
||||
|
||||
|
||||
def test_space_pause_uses_suspend_not_stop_reset():
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
branch = helper.split('if (action === "stop" || action === "pause")', 1)[1].split('if (action === "set")', 1)[0]
|
||||
assert 'Function: "SuspendCountdown"' in branch
|
||||
assert 'Function: "StopCountdown"' not in branch
|
||||
assert 'Function: "SetCountdown"' not in branch
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('web_first')
|
||||
run_timer_contract('pause_freezes')
|
||||
|
||||
|
||||
def test_explicit_reset_set_path_keeps_stop_then_set():
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
set_branch = helper.split('if (action === "set")', 1)[1].split('return [', 2)[1]
|
||||
assert 'Function: "StopCountdown"' in set_branch
|
||||
assert 'Function: "SetCountdown"' in set_branch
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('explicit_edit')
|
||||
run_timer_contract('period_base')
|
||||
|
||||
|
||||
def test_penalty_normal_pause_uses_suspend():
|
||||
block = _block("async function rebalanceVmixPenaltyTargets", "function finishActionMatchesSource")
|
||||
assert 'if (preservePausedCountdown && !assignmentChanged)' in block
|
||||
assert 'stopCommands.push({ Function: "SuspendCountdown"' in block
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('penalty_pause')
|
||||
|
||||
|
||||
def test_build105_runtime_version():
|
||||
assert 'BUILD_VERSION = "2026.08.24.8"' in APP
|
||||
assert_current_build_contract()
|
||||
|
||||
@@ -7,6 +7,8 @@ from types import SimpleNamespace
|
||||
from hockey_data.agent_bridge import VmixAgentHub
|
||||
from hockey_data.auth_bridge import HockeyUser
|
||||
from tests.support import LocalTestDatabase
|
||||
from tests.timer_contract_support import assert_current_build_contract
|
||||
from tests.test_build103_space_timer_fast_transport import run_transport_contract
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
APP_JS = (ROOT / "ui_builder/static/app.js").read_text(encoding="utf-8")
|
||||
@@ -25,38 +27,18 @@ class FakeWebSocket:
|
||||
return None
|
||||
|
||||
|
||||
def _block(start: str, end: str) -> str:
|
||||
return APP_JS.split(start, 1)[1].split(end, 1)[0]
|
||||
|
||||
|
||||
def test_countdown_start_hard_reseeds_before_start() -> None:
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
assert 'Function: "PauseRender"' in helper
|
||||
assert 'Function: "StopCountdown"' in helper
|
||||
assert 'Function: "SetCountdown"' in helper
|
||||
assert 'Function: "ResumeRender"' in helper
|
||||
assert 'Function: "StartCountdown"' in helper
|
||||
assert helper.index('Function: "StopCountdown"') < helper.index('Function: "SetCountdown"')
|
||||
assert helper.rindex('Function: "SetCountdown"') < helper.rindex('Function: "StartCountdown"')
|
||||
"""Keep the historical test ID; a fresh start now seeds once without render/reset wrappers."""
|
||||
run_transport_contract("native_first_start")
|
||||
|
||||
|
||||
def test_pause_is_reseeded_from_runtime_not_native_clock() -> None:
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
branch = helper.split('if (action === "stop" || action === "pause" || action === "set")', 1)[1].split('return reseedStopped;', 1)[0]
|
||||
assert "Runtime value" in branch
|
||||
reseed = helper.split("const reseedStopped = [", 1)[1].split("];", 1)[0]
|
||||
assert 'Function: "StopCountdown"' in reseed
|
||||
assert 'Function: "SetCountdown"' in reseed
|
||||
assert 'Value: currentValue' in reseed
|
||||
"""Keep the historical ID; BUILD159 replaces reseeding with native pause/resume."""
|
||||
run_transport_contract("native_pause_resume")
|
||||
|
||||
|
||||
def test_scoreboard_show_syncs_timer_before_overlay_steps() -> None:
|
||||
runner = _block("async function runShortcutSequence", "function handleConfiguredShortcutCombo")
|
||||
assert "if (sequence.is_scoreboard_sequence)" in runner
|
||||
assert runner.index("await syncConfiguredScoreboardCountdownsToRuntime()") < runner.index("const stepErrors = []")
|
||||
helper = _block("async function syncConfiguredScoreboardCountdownsToRuntime", "function penaltyMirrorKey")
|
||||
assert 'timerState.running ? "start" : "set"' in helper
|
||||
assert "await sendRuntimeVmixTimerSequence(commands)" in helper
|
||||
run_transport_contract("scoreboard_before_overlay")
|
||||
|
||||
|
||||
def test_ordered_timer_transport_sends_individual_frames_without_ack(tmp_path: Path) -> None:
|
||||
@@ -89,11 +71,11 @@ def test_ordered_timer_transport_sends_individual_frames_without_ack(tmp_path: P
|
||||
hub.run_vmix_sequence_for_user(
|
||||
user,
|
||||
[
|
||||
{"Function": "PauseRender", "Input": "SCORE"},
|
||||
{"Function": "StopCountdown", "Input": "SCORE", "SelectedName": "TIME.Text"},
|
||||
{"Function": "SetCountdown", "Input": "SCORE", "SelectedName": "TIME.Text", "Value": "00:16:01"},
|
||||
{"Function": "ResumeRender", "Input": "SCORE"},
|
||||
{"Function": "SetCountdown", "Input": "SCORE", "SelectedName": "TIME.Text", "Value": "00:20:00"},
|
||||
{"Function": "StartCountdown", "Input": "SCORE", "SelectedName": "TIME.Text"},
|
||||
{"Function": "SetCountdown", "Input": "PENALTY", "SelectedName": "TIME.Text", "Value": "00:02:00"},
|
||||
{"Function": "StopCountdown", "Input": "PENALTY", "SelectedName": "TIME.Text"},
|
||||
{"Function": "StartCountdown", "Input": "PENALTY", "SelectedName": "TIME.Text"},
|
||||
],
|
||||
delivery_mode="timer-fast-ordered",
|
||||
),
|
||||
@@ -104,7 +86,7 @@ def test_ordered_timer_transport_sends_individual_frames_without_ack(tmp_path: P
|
||||
batches = [item for item in ws.sent if item.get("type") == "vmix.batch"]
|
||||
assert not batches
|
||||
assert [item["command"]["Function"] for item in singles] == [
|
||||
"PauseRender", "StopCountdown", "SetCountdown", "ResumeRender", "StartCountdown"
|
||||
"SetCountdown", "StartCountdown", "SetCountdown", "StopCountdown", "StartCountdown"
|
||||
]
|
||||
assert result["ok"] is True
|
||||
assert result["transport"] == "timer-ordered-no-ack"
|
||||
@@ -115,5 +97,5 @@ def test_ordered_timer_transport_sends_individual_frames_without_ack(tmp_path: P
|
||||
|
||||
|
||||
def test_build106_version() -> None:
|
||||
assert 'BUILD_VERSION = "2026.08.24.9"' in APP
|
||||
assert 'delivery_mode: "timer-fast-ordered"' in APP_JS
|
||||
assert_current_build_contract()
|
||||
run_transport_contract("ordered_transport")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -12,35 +13,20 @@ def helper_block():
|
||||
|
||||
|
||||
def test_pause_uses_pause_and_change_without_stop_reset():
|
||||
block = helper_block()
|
||||
pause_start = block.index('if (action === "pause" || action === "stop")')
|
||||
set_start = block.index('if (action === "set")', pause_start)
|
||||
pause_branch = block[pause_start:set_start]
|
||||
assert 'Function: "PauseCountdown"' in pause_branch
|
||||
assert 'Function: "ChangeCountdown"' in pause_branch
|
||||
assert 'Function: "StopCountdown"' not in pause_branch
|
||||
assert pause_branch.index('Function: "PauseCountdown"') < pause_branch.index('Function: "ChangeCountdown"')
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('pause_freezes')
|
||||
|
||||
|
||||
def test_start_uses_change_then_start_without_stop_or_set_duration():
|
||||
block = helper_block()
|
||||
start_branch = block[block.index("// Start/Resume:"):]
|
||||
assert 'Function: "ChangeCountdown"' in start_branch
|
||||
assert 'Function: "StartCountdown"' in start_branch
|
||||
assert 'Function: "StopCountdown"' not in start_branch
|
||||
assert 'Function: "SetCountdown"' not in start_branch
|
||||
assert start_branch.index('Function: "ChangeCountdown"') < start_branch.index('Function: "StartCountdown"')
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('first_start')
|
||||
run_timer_contract('resume_preserves_native')
|
||||
|
||||
|
||||
def test_set_only_changes_current_position_and_does_not_toggle_pause():
|
||||
block = helper_block()
|
||||
set_start = block.index('if (action === "set")')
|
||||
start_branch = block.index("// Start/Resume:", set_start)
|
||||
set_branch = block[set_start:start_branch]
|
||||
assert 'Function: "ChangeCountdown"' in set_branch
|
||||
assert 'Function: "PauseCountdown"' not in set_branch
|
||||
assert 'Function: "StopCountdown"' not in set_branch
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('explicit_edit')
|
||||
|
||||
|
||||
def test_runtime_version():
|
||||
assert 'BUILD_VERSION = "2026.08.24.10"' in APP_PY
|
||||
assert_current_build_contract()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
from pathlib import Path
|
||||
|
||||
APP_JS = Path(__file__).resolve().parents[1] / "ui_builder" / "static" / "app.js"
|
||||
@@ -11,56 +12,23 @@ def block(start_marker: str, end_marker: str) -> str:
|
||||
|
||||
|
||||
def test_game_clock_helper_only_seeds_on_set():
|
||||
helper = block(
|
||||
"function vmixGameCountdownControlCommands",
|
||||
"function buildShortcutRuntimeContext",
|
||||
)
|
||||
pause_branch = helper[helper.index('if (action === "pause"'):helper.index('if (action === "set"')]
|
||||
set_branch = helper[helper.index('if (action === "set"'):helper.index('return [{ Function: "StartCountdown"')]
|
||||
start_branch = helper[helper.index('return [{ Function: "StartCountdown"'):]
|
||||
|
||||
assert 'Function: "PauseCountdown"' in pause_branch
|
||||
assert 'ChangeCountdown' not in pause_branch
|
||||
assert 'SetCountdown' not in pause_branch
|
||||
assert 'StopCountdown' not in pause_branch
|
||||
|
||||
assert 'Function: "ChangeCountdown"' in set_branch
|
||||
assert 'Function: "StartCountdown"' not in set_branch
|
||||
assert 'Function: "PauseCountdown"' not in set_branch
|
||||
|
||||
assert 'Function: "StartCountdown"' in start_branch
|
||||
assert 'ChangeCountdown' not in start_branch
|
||||
assert 'PauseCountdown' not in start_branch
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('first_start')
|
||||
run_timer_contract('pause_freezes')
|
||||
run_timer_contract('resume_preserves_native')
|
||||
|
||||
|
||||
def test_space_game_timer_uses_control_only_helper():
|
||||
section = block('case "hockey_vmix_timers_start":', 'case "delay":')
|
||||
game = section[:section.index('if (step.sync_vmix_penalties)')]
|
||||
assert 'vmixGameCountdownControlCommands' in game
|
||||
assert '"pause"' in game
|
||||
assert '"start"' in game
|
||||
# Generic helper may still be used later for penalty countdowns, but never in main game branch.
|
||||
assert 'vmixCountdownSyncCommands' not in game
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('web_first')
|
||||
run_timer_contract('shortcut_resume')
|
||||
|
||||
|
||||
def test_explicit_time_change_seeds_even_before_first_space():
|
||||
section = block(
|
||||
'async function syncActiveVmixGameCountdown',
|
||||
'function configuredHockeyVmixGameCountdownTargets',
|
||||
)
|
||||
assert 'explicitSeedEvent' in section
|
||||
assert 'timer_set_time' in section
|
||||
assert 'timer_reset' in section
|
||||
assert 'state.config.shortcut_sequences' in section
|
||||
assert 'vmixGameCountdownControlCommands(input, selectedName, valueProvider, "set")' in section
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('first_edit_before_activation')
|
||||
|
||||
|
||||
def test_pause_event_never_writes_browser_time_to_vmix():
|
||||
section = block(
|
||||
'async function syncActiveVmixGameCountdown',
|
||||
'function configuredHockeyVmixGameCountdownTargets',
|
||||
)
|
||||
pause = section[section.index('eventName === "timer_pause"'):section.index('timer_stop', section.index('eventName === "timer_pause"'))]
|
||||
assert '"pause"' in pause
|
||||
assert '"set"' not in pause
|
||||
assert 'ChangeCountdown' not in pause
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('native_events')
|
||||
|
||||
@@ -25,18 +25,15 @@ def test_old_polling_stops_before_new_match_selection():
|
||||
|
||||
|
||||
def test_selected_game_cache_is_match_scoped_and_local():
|
||||
assert "/api/hockey/games/${encodeURIComponent(id)}/details?language=" in JS
|
||||
assert "cachedMatchHasRosters" in JS
|
||||
assert "cachedRostersReady" in JS
|
||||
"""The local cache request uses the selected match and discards late responses after another switch."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("roster")
|
||||
|
||||
|
||||
def test_first_time_match_waits_for_core_roster_before_polling():
|
||||
assert "if (!manual && !cachedRostersReady)" in JS
|
||||
assert "await enrichOpenedGame(String(id), state.selectedId, generation, { opening: true });" in JS
|
||||
branch = JS.index("if (!manual && !cachedRostersReady)")
|
||||
enrich = JS.index("await enrichOpenedGame", branch)
|
||||
poll = JS.index("startSelectedGamePolling();", enrich)
|
||||
assert enrich < poll
|
||||
"""BUILD189 opens schedule data immediately, clears the previous roster and enriches without blocking."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("roster")
|
||||
|
||||
|
||||
def test_opening_sync_skips_schedule_roundtrip_and_optional_shots():
|
||||
|
||||
@@ -77,14 +77,10 @@ def test_browser_retries_match_assign_without_mapping_when_needed() -> None:
|
||||
assert 'live.length === 1' in JS
|
||||
|
||||
|
||||
def test_mapping_is_refreshed_only_after_roster_enrichment() -> None:
|
||||
assert "async function refreshSessionAgentMapping(session)" in JS
|
||||
branch = JS.index("if (!manual && !cachedRostersReady)")
|
||||
enrich = JS.index("await enrichOpenedGame", branch)
|
||||
mapping = JS.index("refreshSessionAgentMapping(session)", enrich)
|
||||
assert enrich < mapping
|
||||
open_session = ROUTER[ROUTER.index('@router.post("/sessions")'):ROUTER.index('@router.get("/sessions/{token}")')]
|
||||
assert "agent_hub.apply_mapping_to_device" not in open_session
|
||||
def test_mapping_is_refreshed_only_after_roster_enrichment():
|
||||
"""Current contract: session assignment precedes mapping while optional roster enrichment remains nonblocking."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("roster")
|
||||
|
||||
|
||||
def test_select_session_supports_assignment_without_early_mapping() -> None:
|
||||
|
||||
@@ -43,16 +43,6 @@ def test_strength_transition_recomputes_configured_label():
|
||||
|
||||
|
||||
def test_runtime_refreshes_only_changed_mapping_when_strength_changes():
|
||||
js = Path("ui_builder/static/app.js").read_text(encoding="utf-8")
|
||||
bridge = Path("hockey_data/agent_bridge.py").read_text(encoding="utf-8")
|
||||
|
||||
assert "function hockeyStrengthMappingSignature" in js
|
||||
assert "function hockeyRefreshVmixMappingForStrength" in js
|
||||
assert "apply-mapping?only_changed=true" in js
|
||||
assert "hockeyStrengthMappingSignature(previousControl) !== hockeyStrengthMappingSignature(payload)" in js
|
||||
assert "vmixStrengthMappingRefreshPending" in js
|
||||
assert "vmixStrengthMappingRefreshQueued" in js
|
||||
|
||||
assert "only_changed: bool = False" in bridge
|
||||
assert 'reason="runtime_strength_changed" if only_changed else "manual_apply"' in bridge
|
||||
assert "only_changed=only_changed" in bridge
|
||||
"""Strength transitions refresh their dedicated namespace; unchanged snapshots and viewers send nothing."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("strength")
|
||||
|
||||
@@ -34,17 +34,9 @@ def test_team_state_input_uses_operator_agent_inventory_and_stable_key():
|
||||
|
||||
|
||||
def test_scoreboard_sequence_syncs_active_team_state_overlays():
|
||||
js = Path("ui_builder/static/app.js").read_text(encoding="utf-8")
|
||||
manager = Path("ui_builder/manager.py").read_text(encoding="utf-8")
|
||||
|
||||
assert "function hockeySyncTeamStateOverlays" in js
|
||||
assert "function hockeyTeamStateScoreboardIsLive" in js
|
||||
assert "hockeyTeamStateOverlayActive" in js
|
||||
assert "sync_hockey_team_states" in js
|
||||
assert "adding states" not in js # keep labels localized, no accidental placeholder
|
||||
assert 'OverlayInput${setting.overlay}In' in js
|
||||
assert 'OverlayInput${previous.overlay}Out' in js
|
||||
assert '"sync_hockey_team_states": bool(sequence.get("sync_hockey_team_states", sequence.get("toggle_all_overlays_on_repeat", False)))' in manager
|
||||
"""Team-state overlays honour configured channels, confirmations and viewer rights."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("team_states")
|
||||
|
||||
|
||||
def test_team_state_buttons_use_configured_labels_and_persisted_match_flags():
|
||||
|
||||
@@ -80,29 +80,9 @@ def test_prematch_supports_groups_labels_and_drag_reordering():
|
||||
|
||||
|
||||
def test_penalty_preview_selection_persists_identifiers_before_trigger():
|
||||
mapping = Path("hockey_data/mapping_context.py").read_text(encoding="utf-8")
|
||||
js = Path("ui_builder/static/app.js").read_text(encoding="utf-8")
|
||||
|
||||
for key in (
|
||||
"selected_penalty_id",
|
||||
"selected_penalty_player_id",
|
||||
"selected_penalty_team_id",
|
||||
"selected_penalty_infraction_id",
|
||||
"selected_penalty_preset_id",
|
||||
"selected_penalty_side",
|
||||
"selected_penalty_event_time",
|
||||
"selected_penalty_status",
|
||||
"selected_penalty_remaining_ms",
|
||||
"selected_penalty_duration_ms",
|
||||
):
|
||||
assert key in mapping
|
||||
assert key in js
|
||||
assert 'selected_event_id: detail.penalty_id' in js
|
||||
assert 'emitInteraction(component, "penalty_selected", detail)' in js
|
||||
assert 'penalty_selected — удаление выбрано для подсмотра' in js
|
||||
# Mapping context request is intentionally before the trigger emit in the async path.
|
||||
function_body = js[js.index("async function hockeySelectPenaltyForPreview"):js.index("function hockeyPenaltyCard")]
|
||||
assert function_body.index('fetch("/api/hockey/context/batch"') < function_body.rindex('emitInteraction(component, "penalty_selected", detail)')
|
||||
"""Context persistence must finish before the selected-penalty trigger can run."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("penalty_preview")
|
||||
|
||||
|
||||
def test_vmix_step_can_use_alternate_input_while_scoreboard_is_live():
|
||||
|
||||
@@ -24,18 +24,9 @@ def test_vmix_agent_is_small_topbar_indicator():
|
||||
|
||||
|
||||
def test_account_switch_now_controls_runtime_toasts_without_disabling_triggers():
|
||||
assert 'id="runtimeEventsToggleBtn"' in HTML
|
||||
assert 'operatorToastsEnabled: true' in JS
|
||||
assert 'toggleRuntimeEventsPreference' in JS
|
||||
assert '"/preferences/toasts"' in JS
|
||||
assert 'Toast: ВКЛ' in JS
|
||||
assert '@router.put("/preferences/toasts")' in ROUTER
|
||||
assert '@router.get("/preferences")' in ROUTER
|
||||
process_start = JS.index('async function processTriggers(context)')
|
||||
shortcut_start = JS.index('async function runShortcutSequence')
|
||||
assert 'if (!state.triggersEnabled) return;' not in JS[process_start:process_start + 900]
|
||||
assert 'if (!state.triggersEnabled) return;' not in JS[shortcut_start:shortcut_start + 1500]
|
||||
assert 'state.operatorToastsEnabled === false' in JS
|
||||
"""Muted operator toasts never disable automatic broadcast triggers or error messages."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("toasts_triggers")
|
||||
|
||||
|
||||
def test_user_preference_defaults_toasts_on_and_persists_per_account(tmp_path):
|
||||
|
||||
@@ -21,11 +21,6 @@ def test_operator_trigger_save_endpoint_only_updates_triggers():
|
||||
|
||||
|
||||
def test_quick_panel_on_air_tracking_has_ack_confirmed_fallback():
|
||||
js = Path("ui_builder/static/app.js").read_text(encoding="utf-8")
|
||||
assert "quickPanelOnAirSequences: new Set()" in js
|
||||
assert "function setQuickPanelSequenceOnAir" in js
|
||||
assert "state.quickPanelOnAirSequences.has(id)" in js
|
||||
assert "Boolean(state.shortcutSequenceOverlayState.get(id))" in js
|
||||
assert 'fn.toLowerCase() === "overlayinputalloff"' in js
|
||||
assert 'normalized.match(/(?:^|[^a-z0-9])OverlayInput([1-4])' in js
|
||||
assert 'refreshQuickPanelOnAirClasses()' in js
|
||||
"""Live tally has priority; legacy ACK-confirmed latch remains the offline fallback."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("onair")
|
||||
|
||||
@@ -30,18 +30,9 @@ def _seed(database: LocalTestDatabase) -> None:
|
||||
|
||||
|
||||
def test_quick_panel_selector_is_configurable_and_sent_before_sequence():
|
||||
assert "quick_panel_selectors" in JS
|
||||
assert "normalizeQuickPanelSelectors" in JS
|
||||
assert "data-quick-selector-add" in JS
|
||||
assert "hockeyCommitQuickPanelButtonContext" in JS
|
||||
click = JS.index('el.runtimeButtonDock.querySelectorAll("[data-quick-command-button]")')
|
||||
snippet = JS[click:click + 2600]
|
||||
assert "await hockeyCommitQuickPanelButtonContext(button, attachedSelectors, { refreshMapping: false })" in snippet
|
||||
assert snippet.index("await hockeyCommitQuickPanelButtonContext") < snippet.index("runShortcutSequence")
|
||||
assert "full Mapping ACK round-trip" in snippet
|
||||
assert '"/control/values"' in JS
|
||||
assert '@router.put("/games/{external_id}/control/values")' in ROUTER
|
||||
assert 'quick_panel_selectors' in APP
|
||||
"""A button waits for saved selector/title context and stops if persistence fails."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("quick_panel")
|
||||
|
||||
|
||||
def test_panel_runtime_values_are_available_to_mapping_and_sql(tmp_path: Path):
|
||||
|
||||
@@ -21,11 +21,9 @@ def test_normal_and_scoreboard_alternate_inputs_are_tracked():
|
||||
|
||||
|
||||
def test_onair_prefers_runtime_target_match():
|
||||
start = JS.index("function shortcutSequenceIsOnAir")
|
||||
snippet = JS[start:start + 1800]
|
||||
assert "if (sequenceStillOwnsRuntimeOverlay(id)) return true;" in snippet
|
||||
assert "sequenceMatchesRuntimeOverlay(sequence)" in snippet
|
||||
assert "state.quickPanelOnAirSequences.has(id)" in snippet
|
||||
"""Match the complete current helper rather than a fixed-length source slice."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("onair")
|
||||
|
||||
|
||||
def test_target_detection_respects_step_conditions():
|
||||
|
||||
@@ -22,8 +22,6 @@ def test_runtime_bell_controls_toasts_only():
|
||||
assert "🔔" in HTML
|
||||
|
||||
def test_runtime_can_grow_in_f11_and_large_viewports():
|
||||
assert "const maxScale = fixedHockeyCanvas ? 1.6 : 1.8;" in JS
|
||||
assert "BUILD59 — account toast switch + denser adaptive runtime/F11 workspace" in CSS
|
||||
assert "@media (min-width: 1900px) and (min-height: 1000px)" in CSS
|
||||
assert ".runtime-viewport" in CSS
|
||||
assert "max-width: none !important" in CSS
|
||||
"""Main hockey canvas grows to 1.6, lines to 1.8, and both shrink uniformly."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("scale")
|
||||
|
||||
@@ -10,8 +10,9 @@ def test_build_version_bumped():
|
||||
|
||||
|
||||
def test_overlay_parser_accepts_legacy_function_strings():
|
||||
assert 'replace(/\\s+/g, "")' in JS
|
||||
assert 'normalized.match(/(?:^|[^a-z0-9])OverlayInput([1-4])' in JS
|
||||
"""Legacy whitespace/query suffixes work across all eight supported overlay channels."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("overlay_parser")
|
||||
|
||||
|
||||
def test_sequence_onair_has_post_ack_reconcile_fallback():
|
||||
|
||||
@@ -39,7 +39,51 @@ def test_editor_button_is_admin_only_and_hotkey_respects_it():
|
||||
|
||||
|
||||
def test_editor_server_paths_are_admin_protected():
|
||||
assert 'path == "/editor"' in APP_PY
|
||||
assert 'path.startswith("/api/ui-builder/editor/")' in APP_PY
|
||||
assert 'path.startswith("/api/ui-builder/auth/")' in APP_PY
|
||||
assert '(khl_admin_path or editor_path) and not user.is_admin' in APP_PY
|
||||
"""Execute the actual middleware with local identities; never import the live app."""
|
||||
import ast
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from fastapi import HTTPException
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
|
||||
tree = ast.parse(APP_PY)
|
||||
middleware = next(node for node in tree.body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == "hockey_runtime_auth")
|
||||
middleware.decorator_list = []
|
||||
current = SimpleNamespace(user=SimpleNamespace(is_admin=False))
|
||||
|
||||
async def optional_user(request):
|
||||
return current.user
|
||||
|
||||
namespace = dict(hockey_auth=SimpleNamespace(optional_user=optional_user),
|
||||
Request=object, HTTPException=HTTPException,
|
||||
JSONResponse=JSONResponse, RedirectResponse=RedirectResponse,
|
||||
apply_web_cache_policy=lambda request, response: response)
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[middleware], type_ignores=[])),
|
||||
"<production hockey_runtime_auth>", "exec"), namespace)
|
||||
|
||||
async def scenario():
|
||||
async def following(request):
|
||||
return JSONResponse({"allowed": True})
|
||||
|
||||
async def check(path, method, expected):
|
||||
request = SimpleNamespace(url=SimpleNamespace(path=path), method=method,
|
||||
state=SimpleNamespace())
|
||||
response = await namespace["hockey_runtime_auth"](request, following)
|
||||
assert response.status_code == expected, (path, method, response.body)
|
||||
return response
|
||||
|
||||
assert (await check("/editor", "GET", 303)).headers["location"] == "/"
|
||||
await check("/api/ui-builder/editor/config", "GET", 403)
|
||||
await check("/api/ui-builder/auth/status", "GET", 403)
|
||||
await check("/khl-site/api/players", "POST", 403)
|
||||
await check("/khl-site/", "GET", 200)
|
||||
await check("/", "GET", 200)
|
||||
current.user = SimpleNamespace(is_admin=True)
|
||||
await check("/editor", "GET", 200)
|
||||
await check("/api/ui-builder/editor/config", "POST", 200)
|
||||
current.user = None
|
||||
assert (await check("/editor", "GET", 303)).headers["location"].startswith("/login")
|
||||
await check("/api/ui-builder/auth/status", "GET", 401)
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
@@ -44,7 +44,7 @@ def test_portable_rebind_uses_title_when_input_key_changed() -> None:
|
||||
assert report["skipped"] == 0
|
||||
assert report["matched_by"]["title"] == 1
|
||||
assert rebound[0]["vmix_input_key"] == "new-key"
|
||||
assert rebound[0]["vmix_input_number"] == "17"
|
||||
assert rebound[0]["vmix_input_number"] == "" # current slot must never become a saved address
|
||||
assert rebound[0]["vmix_input_title"] == "SCORE BUG"
|
||||
assert rebound[0]["vmix_field"] == "HomeScore.Text"
|
||||
assert rebound[0]["rule"]["operator"] == "eq"
|
||||
@@ -129,6 +129,9 @@ def test_copy_profile_creates_target_specific_mapping_and_keeps_source(tmp_path:
|
||||
assert len(visible) == 2
|
||||
assert visible[0].id == source_id and visible[0].active is True
|
||||
assert visible[0].project_fingerprint == "a" * 64
|
||||
source_links = list(session.scalars(select(VmixMappingField).where(VmixMappingField.profile_id == source_id)))
|
||||
assert len(source_links) == 1 and source_links[0].vmix_input_key == "source-score-key"
|
||||
assert source_links[0].vmix_input_title == "SCORE BUG" and source_links[0].vmix_input_number == ""
|
||||
assert visible[1].id == result["profile"]["id"] and visible[1].active is True
|
||||
assert visible[1].project_fingerprint == "b" * 64
|
||||
# Publishing the copy creates one independent runtime snapshot. The
|
||||
@@ -155,3 +158,21 @@ def test_portable_transfer_backend_remains_available_for_compatibility() -> None
|
||||
assert "portable vMix Mapping transfer/import" in CSS
|
||||
assert '"/api/hockey/admin/vmix-mapping/profiles/{profile_id}/export"' in BRIDGE
|
||||
assert '"/api/hockey/admin/vmix-mapping/import"' in BRIDGE
|
||||
|
||||
|
||||
def test_portable_rebind_ignores_conflicting_legacy_selectors_and_rejects_ambiguous_titles():
|
||||
source = {"data_key": "game.clock", "vmix_input_key": "reused-guid", "vmix_input_number": "5",
|
||||
"vmix_input_title": "Score", "vmix_field": "Clock.Text", "enabled": True}
|
||||
right = {"key": "new-guid", "number": "17", "title": "Score",
|
||||
"fields": [{"name": "Clock.Text", "type": "text"}]}
|
||||
wrong = {"key": "reused-guid", "number": "5", "title": "Other",
|
||||
"fields": [{"name": "Clock.Text", "type": "text"}]}
|
||||
rebound, report = VmixAgentHub._rebind_portable_mapping_fields([source], {"inputs": [wrong, right]})
|
||||
assert report["matched_by"] == {"key": 0, "title": 1, "number": 0}
|
||||
assert rebound[0]["vmix_input_title"] == "Score" and rebound[0]["vmix_input_key"] == "new-guid"
|
||||
assert rebound[0]["vmix_input_number"] == ""
|
||||
for inputs, reason in [([wrong], "input_title_not_found"),
|
||||
([right, {**right, "key": "duplicate", "number": "18"}], "ambiguous_input_title")]:
|
||||
rebound, report = VmixAgentHub._rebind_portable_mapping_fields([source], {"inputs": inputs})
|
||||
assert rebound == [] and report["mapped"] == 0 and report["skipped"] == 1
|
||||
assert report["skipped_items"][0]["reason"] == reason
|
||||
|
||||
@@ -16,17 +16,10 @@ JS = (ROOT / "hockey_data/static/admin-directories.js").read_text(encoding="utf-
|
||||
CSS = (ROOT / "hockey_data/static/admin-directories.css").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_mapping_heavy_data_sections_are_collapsed_by_default() -> None:
|
||||
assert 'data-map-sql-cell-details' in JS
|
||||
assert 'data-map-sql-table-details' in JS
|
||||
assert 'mappingSqlCellOpen: false' in JS
|
||||
assert 'mappingSqlTableOpen: false' in JS
|
||||
assert 'mappingOpenDataGroups: {}' in JS
|
||||
assert 'data-map-data-group="${escapeHtml(category.name)}"' in JS
|
||||
assert 'index < 3 || query' not in JS
|
||||
assert 'query || state.mappingOpenDataGroups[category.name]' in JS
|
||||
assert '.hockey-map-sql-cell-quick:not([open])' in CSS
|
||||
assert '.hockey-map-table-picker:not([open])' in CSS
|
||||
def test_mapping_heavy_data_sections_are_collapsed_by_default():
|
||||
"""Render actual details: collapsed by default and opened only by retained user state."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("mapping_browser")
|
||||
|
||||
|
||||
def test_rescan_preserves_links_and_only_adds_new_inventory_items(tmp_path: Path) -> None:
|
||||
|
||||
@@ -6,26 +6,9 @@ MAPPING = (ROOT / "hockey_data/mapping_context.py").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_side_penalty_mapping_context_is_derived_from_active_penalties_without_overwriting_manual_selection():
|
||||
start = APP.index("async function hockeySyncPenaltySideMappingContext")
|
||||
end = APP.index("function penaltyTargetAssignmentKey", start)
|
||||
snippet = APP[start:end]
|
||||
assert 'sortedPenaltyEntries("home")[0]' in snippet
|
||||
assert 'sortedPenaltyEntries("away")[0]' in snippet
|
||||
for key in (
|
||||
"active_home_penalty_id",
|
||||
"active_home_penalty_player_id",
|
||||
"active_home_penalty_player_db_id",
|
||||
"active_home_penalty_team_penalty",
|
||||
"active_away_penalty_id",
|
||||
"active_away_penalty_player_id",
|
||||
"active_away_penalty_player_db_id",
|
||||
"active_away_penalty_team_penalty",
|
||||
):
|
||||
assert f"{key}:" in snippet
|
||||
# BUILD84: selected_* is an explicit operator choice, so the automatic mirror
|
||||
# must never replace it with the first active penalty.
|
||||
assert "selected_home_penalty_id:" not in snippet
|
||||
assert "selected_away_penalty_id:" not in snippet
|
||||
"""Prepared penalties populate active_*; explicit selected side identifiers remain untouched."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("side_context")
|
||||
|
||||
|
||||
def test_manual_side_penalty_selection_keeps_separate_mapping_identifiers():
|
||||
|
||||
@@ -9,14 +9,9 @@ APP = (ROOT / "ui_builder/static/app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_prepared_titles_is_forced_to_last_runtime_tab_and_uses_hockey_api_directly():
|
||||
assert 'state.config.tabs = state.config.tabs.filter((tab) => tab?.id !== "prepared_titles")' in APP
|
||||
assert 'state.config.tabs.push({ id: "prepared_titles", label: "Заготовки" });' in APP
|
||||
# BUILD84 accidentally routed these through boot.api (/api/ui-builder/runtime), producing 404 Not Found.
|
||||
prepared_slice = APP[APP.index("async function hockeyLoadPreparedMappingSources"):APP.index("function renderHockeyPreparedTitlesWorkspace")]
|
||||
assert 'api(`/api/hockey/prepared-titles' not in prepared_slice
|
||||
assert 'api("/api/hockey/prepared-titles' not in prepared_slice
|
||||
assert 'hockeyGameControlRequest(`/prepared-titles' in prepared_slice
|
||||
assert 'hockeyGameControlRequest(`/agents/vmix-inventory' in prepared_slice
|
||||
"""Prepared titles are the final operator tab, followed by the KHL reference workspace; API is rooted once."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("prepared_tabs")
|
||||
|
||||
|
||||
def test_prepared_title_browser_keeps_title_inputs_visible_even_without_field_inventory():
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -6,32 +7,23 @@ APP = (ROOT / "app.py").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_game_countdown_resume_is_reseeded_before_start():
|
||||
block = APP_JS.split("async function syncActiveVmixGameCountdown", 1)[1].split("function penaltyMirrorKey", 1)[0]
|
||||
assert '["timer_start", "timer_restart", "timer_resume"].includes(eventName)' in block
|
||||
assert 'vmixCountdownSyncCommands(input, selectedName, valueProvider, "start")' in block
|
||||
helper = APP_JS.split("function vmixCountdownSyncCommands", 1)[1].split("function buildShortcutRuntimeContext", 1)[0]
|
||||
start_branch = helper.rsplit("return [", 1)[1]
|
||||
assert start_branch.index('Function: "SetCountdown"') < start_branch.index('Function: "StartCountdown"')
|
||||
assert 'eventName === "timer_resume"' not in block
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('resume_preserves_native')
|
||||
run_timer_contract('native_events')
|
||||
|
||||
|
||||
def test_hockey_timer_shortcut_reseeds_game_and_penalty_on_resume():
|
||||
block = APP_JS.split('case "hockey_vmix_timers_start":', 1)[1].split('case "delay":', 1)[0]
|
||||
# Resume must no longer have a StartCountdown-only branch.
|
||||
assert '} else if (action === "resume") {' not in block
|
||||
assert block.count('vmixCountdownSyncCommands(') >= 2
|
||||
assert '() => gameTimerState.currentMs' in block
|
||||
assert '() => event.remainingMs' in block
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('shortcut_resume')
|
||||
|
||||
|
||||
# Native penalty transitions are exercised in test_stage2_penalty_countdown.py.
|
||||
|
||||
|
||||
def test_native_mode_still_has_no_per_second_countdown_transport():
|
||||
assert 'eventName === "timer_tick" && state.vmixTimerMirrors.has(component.action_id)' in APP_JS
|
||||
tick_branch = APP_JS.split('eventName === "timer_tick" && state.vmixTimerMirrors.has(component.action_id)', 1)[1].split('} else if (eventName !== "timer_tick"', 1)[0]
|
||||
assert "SetCountdown" not in tick_branch
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('no_tick_transport')
|
||||
|
||||
|
||||
def test_build93_runtime_version():
|
||||
assert 'BUILD_VERSION = "2026.08.20.14"' in APP
|
||||
assert_current_build_contract()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -10,45 +11,30 @@ def _block(start: str, end: str) -> str:
|
||||
|
||||
|
||||
def test_prepared_penalty_shows_stopped_time_when_scoreboard_is_live():
|
||||
block = _block("function emitHockeyEventUpdated", "function createHockeyPenaltyDraft")
|
||||
assert "hockeyEventReady(event)" in block and "hockeyScoreboardIsLive()" in block
|
||||
assert "rebalanceVmixPenaltyTargets" in block
|
||||
draft = _block("function createHockeyPenaltyDraft", "function findHockeyPenalty")
|
||||
assert "startedOnce: false" in draft
|
||||
control = _block("function controlHockeyPenalty", "function formatHockeyPenaltyTime")
|
||||
start_branch = control.split('if (command === "start")', 1)[1].split('} else if (command === "pause")', 1)[0]
|
||||
assert "event.startedOnce = true" in start_branch
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('prepared_emission')
|
||||
run_timer_contract('prepared_penalty')
|
||||
|
||||
|
||||
def test_penalty_vmix_display_uses_only_started_or_paused_active_penalties():
|
||||
assert "function activeHockeyPenaltyEntries()" in APP_JS
|
||||
sorted_block = _block("function sortedPenaltyEntries", "function penaltyLocalAdvantageSide")
|
||||
assert "activeHockeyPenaltyEntries()" in sorted_block
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('penalty_priority')
|
||||
|
||||
|
||||
def test_main_countdown_start_pause_stop_all_hard_sync_web_value():
|
||||
block = _block("async function syncActiveVmixGameCountdown", "function penaltyMirrorKey")
|
||||
assert 'vmixCountdownSyncCommands(input, selectedName, valueProvider, "start")' in block
|
||||
assert 'vmixCountdownSyncCommands(input, selectedName, valueProvider, "pause")' in block
|
||||
assert 'vmixCountdownSyncCommands(input, selectedName, valueProvider, "stop")' in block
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
start_branch = helper.rsplit("return [", 1)[1]
|
||||
assert 'Function: "SuspendCountdown"' not in start_branch
|
||||
assert start_branch.index('Function: "SetCountdown"') < start_branch.index('Function: "StartCountdown"')
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('native_events')
|
||||
run_timer_contract('explicit_edit')
|
||||
|
||||
|
||||
# Native penalty transitions are exercised in test_stage2_penalty_countdown.py.
|
||||
|
||||
|
||||
def test_combined_shortcut_changes_web_first_then_synchronizes_vmix():
|
||||
block = APP_JS.split('case "hockey_vmix_timers_start":', 1)[1].split('case "delay":', 1)[0]
|
||||
web_game = block.index("if (step.start_web_game)")
|
||||
vmix_game = block.index("if (step.sync_vmix_game && step.game_vmix_input)")
|
||||
assert web_game < vmix_game
|
||||
assert 'vmixCountdownSyncCommands(' in block
|
||||
assert '() => gameTimerState.currentMs' in block
|
||||
assert '() => event.remainingMs' in block
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('web_first')
|
||||
run_timer_contract('shortcut_resume')
|
||||
|
||||
|
||||
def test_build95_runtime_version():
|
||||
assert 'BUILD_VERSION = "2026.08.20.16"' in APP
|
||||
assert_current_build_contract()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
from pathlib import Path
|
||||
|
||||
from hockey_data.service import HockeyDataService
|
||||
@@ -42,14 +43,26 @@ def _strength(*penalties: dict) -> dict:
|
||||
|
||||
|
||||
def test_prepared_penalty_does_not_change_strength_until_explicit_start():
|
||||
prepared = _strength(_penalty("home", 120000, started=False))
|
||||
assert prepared["strength_label"] == "5×5"
|
||||
assert prepared["advantage_side"] == ""
|
||||
"""Incomplete drafts do not count; a complete assigned penalty changes strength immediately."""
|
||||
from copy import deepcopy
|
||||
|
||||
ready = _penalty("home", 120000, started=False)
|
||||
for missing, value in (("side", ""), ("infraction", None), ("preset", ""),
|
||||
("durationMs", 0), ("remainingMs", 0), ("finished", True)):
|
||||
draft = deepcopy(ready)
|
||||
draft[missing] = value
|
||||
result = _strength(draft)
|
||||
assert result["strength_label"] == "5×5", missing
|
||||
assert result["advantage_side"] == "", missing
|
||||
prepared = _strength(ready)
|
||||
assert prepared["strength_label"] == "4×5"
|
||||
assert prepared["advantage_side"] == "away"
|
||||
assert prepared["state_label"] == "БОЛ"
|
||||
assert ready["running"] is False and ready["startedOnce"] is False
|
||||
|
||||
started = _strength(_penalty("home", 120000, started=True))
|
||||
assert started["strength_label"] == "4×5"
|
||||
assert started["advantage_side"] == "away"
|
||||
assert started["state_label"] == "БОЛ"
|
||||
assert started["strength_label"] == prepared["strength_label"]
|
||||
assert started["advantage_side"] == prepared["advantage_side"]
|
||||
|
||||
|
||||
def test_complex_transition_strength_sequence_matches_requested_flow():
|
||||
@@ -94,28 +107,13 @@ def test_complex_transition_strength_sequence_matches_requested_flow():
|
||||
|
||||
|
||||
def test_runtime_holds_single_plate_through_temporary_equal_strength():
|
||||
start = APP_JS.index("function penaltyDisplayEntriesByTargetSide")
|
||||
end = APP_JS.index("function hockeyPenaltySideMappingDetail", start)
|
||||
block = APP_JS[start:end]
|
||||
assert "canHoldEqualStrength" in block
|
||||
assert "state.hockeyPenaltyAdvantageCycle.hadAdvantage" in block
|
||||
assert "lastAdvantageSide" in block
|
||||
assert "const canHoldEqualStrength = Boolean(state.hockeyPenaltyAdvantageCycle.hadAdvantage)" in block
|
||||
assert 'home: rememberedSide === "home" && transitionEntry ? [transitionEntry] : []' in block
|
||||
assert 'away: rememberedSide === "away" && transitionEntry ? [transitionEntry] : []' in block
|
||||
assert 'home: advantageSide === "home" && transitionEntry ? [transitionEntry] : []' in block
|
||||
assert 'away: advantageSide === "away" && transitionEntry ? [transitionEntry] : []' in block
|
||||
assert "holdingEqualStrength" in block
|
||||
# The countdown source remains the globally soonest active penalty.
|
||||
assert "const transitionEntry = all[0] || null;" in block
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('strength_plate_cycle')
|
||||
|
||||
|
||||
def test_pure_equal_strength_without_previous_advantage_still_has_no_plate():
|
||||
start = APP_JS.index("function penaltyDisplayEntriesByTargetSide")
|
||||
end = APP_JS.index("function hockeyPenaltySideMappingDetail", start)
|
||||
block = APP_JS[start:end]
|
||||
assert "if (!canHoldEqualStrength)" in block
|
||||
assert "return { home: [], away: [], routedToAdvantage: false" in block
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('strength_plate_cycle')
|
||||
|
||||
|
||||
def test_advantage_cycle_is_saved_and_restored_for_reload_during_4x4():
|
||||
@@ -141,11 +139,9 @@ def test_advantage_cycle_is_saved_and_restored_for_reload_during_4x4():
|
||||
|
||||
|
||||
def test_full_strength_waits_for_last_started_penalty_not_prepared_draft():
|
||||
control = APP_JS.split("function controlHockeyPenalty", 1)[1].split("function formatHockeyPenaltyTime", 1)[0]
|
||||
assert "hockeyPenaltyHasStarted(item)" in control
|
||||
ticker = APP_JS.split("function updateHockeyPenaltyBoards", 1)[1].split("function registerHockeyBoardNode", 1)[0]
|
||||
assert "remainingTotal = board.penalties.filter((item) => !item.finished && hockeyEventReady(item) && hockeyPenaltyHasStarted(item)).length" in ticker
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('full_strength_waits_ready')
|
||||
|
||||
|
||||
def test_build96_runtime_version():
|
||||
assert 'BUILD_VERSION = "2026.08.20.17"' in APP
|
||||
assert_current_build_contract()
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
"""Retain BUILD97's delivery guarantees using the acknowledged BUILD190 protocol.
|
||||
|
||||
The old giant-batch/repartition implementation is obsolete. The requirements
|
||||
remain: ordered large mappings, bounded packets and retries, isolated failures,
|
||||
independent devices, and truthful operator diagnostics.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from hockey_data.agent_bridge import MAPPING_BATCH_MAX_COMMANDS, VmixAgentHub
|
||||
from tests.support import LocalTestDatabase
|
||||
from tests.test_hotfix_mapping_transport import transport
|
||||
from tests.test_stable_vmix_input_identity import _run_functions
|
||||
|
||||
|
||||
def _entry(index: int, input_ref: str, *, value_size: int = 4) -> dict:
|
||||
@@ -36,119 +42,120 @@ def test_mapping_chunk_planner_groups_by_input_and_caps_packets(tmp_path: Path)
|
||||
assert [index for chunk in chunks for index, _entry_item in chunk] == list(range(len(entries)))
|
||||
|
||||
|
||||
def test_mapping_chunk_transport_sends_300_plus_links_in_small_batches(tmp_path: Path) -> None:
|
||||
database = LocalTestDatabase(tmp_path / "mapping-300.sqlite3")
|
||||
database.create_all()
|
||||
hub = VmixAgentHub(database) # type: ignore[arg-type]
|
||||
packets: list[list[dict]] = []
|
||||
def test_372_mapping_fields_are_ordered_acknowledged_and_bounded(tmp_path: Path):
|
||||
hub, own, other = transport(tmp_path)
|
||||
rows = [_entry(input_index * 1000 + row, f"INPUT-{input_index:02d}")
|
||||
for input_index in range(12) for row in range(31)]
|
||||
result = asyncio.run(hub._send_mapping_entries_resilient("GFX-OWNER",
|
||||
assignment_id="assignment", match_id="g", entries=rows, use_batch=True))
|
||||
assert len(result["results"]) == 372 and all(item["ok"] for item in result["results"])
|
||||
assert result["transport"] == "sequential_ack" and result["ack_waited"] is True
|
||||
assert result["commands_sent"] == 372 and result["input_groups"] == 12
|
||||
assert own.max_pending == 1 and other.frames == []
|
||||
commands = own.frames[1:]
|
||||
assert own.frames[0]["type"] == "match.assign"
|
||||
assert all(frame["type"] == "vmix.command" for frame in commands)
|
||||
assert [frame["command"] for frame in commands] == [row["command"] for row in rows]
|
||||
assert len({frame["request_id"] for frame in commands}) == 372
|
||||
assert all(frame["assignment_id"] == "assignment" and frame["match_id"] == "g" for frame in commands)
|
||||
assert not hub._pending_commands
|
||||
|
||||
async def fake_batch(device_id: str, *, assignment_id: str, match_id: str, commands: list[dict], timeout: float = 8.0) -> dict:
|
||||
assert device_id == "GFX-MAP-300"
|
||||
packets.append(commands)
|
||||
return {"ok": True, "results": [{"ok": True} for _ in commands]}
|
||||
|
||||
async def scenario() -> None:
|
||||
hub.send_vmix_batch = fake_batch # type: ignore[method-assign]
|
||||
entries: list[dict] = []
|
||||
# 12 Inputs x 31 commands = 372 Mapping commands.
|
||||
for input_index in range(12):
|
||||
entries.extend(_entry(input_index * 1000 + row, f"INPUT-{input_index:02d}") for row in range(31))
|
||||
result = await hub._send_mapping_entries_resilient(
|
||||
"GFX-MAP-300",
|
||||
assignment_id="assignment-300",
|
||||
match_id="game-300",
|
||||
entries=entries,
|
||||
use_batch=True,
|
||||
)
|
||||
def test_mapping_transport_retries_one_timeout_then_keeps_order(tmp_path: Path):
|
||||
hub, own, other = transport(tmp_path)
|
||||
original_socket_send = own.send_json
|
||||
original_command_send = hub.send_vmix_command
|
||||
lost = []
|
||||
|
||||
async def lose_one_ack(message):
|
||||
if message.get("command", {}).get("SelectedName") == "Field10.Text" and not lost:
|
||||
own.frames.append(message)
|
||||
lost.append(message)
|
||||
return # Agent read the frame; its ACK was lost.
|
||||
await original_socket_send(message)
|
||||
|
||||
async def short_timeout(device_id, *, assignment_id, match_id, command, timeout=4.0):
|
||||
return await original_command_send(device_id, assignment_id=assignment_id,
|
||||
match_id=match_id, command=command, timeout=0.01)
|
||||
|
||||
own.send_json = lose_one_ack
|
||||
hub.send_vmix_command = short_timeout
|
||||
rows = [_entry(i, "One Input") for i in range(35)]
|
||||
|
||||
async def scenario():
|
||||
result = await hub._send_mapping_entries_resilient("GFX-OWNER", assignment_id="assignment",
|
||||
match_id="g", entries=rows, use_batch=True)
|
||||
assert all(item["ok"] for item in result["results"])
|
||||
assert result["input_groups"] == 12
|
||||
assert result["chunks_total"] == 12
|
||||
assert result["chunks_ok"] == 12
|
||||
assert result["chunks_failed"] == 0
|
||||
assert result["fallback_commands"] == 0
|
||||
assert sum(len(packet) for packet in packets) == 372
|
||||
assert max(len(packet) for packet in packets) <= MAPPING_BATCH_MAX_COMMANDS
|
||||
assert all(len({command["Input"] for command in packet}) == 1 for packet in packets)
|
||||
|
||||
assert result["retries"] == 1 and len(lost) == 1
|
||||
names = [frame["command"]["SelectedName"] for frame in own.frames[1:]]
|
||||
assert names == [f"Field{i}.Text" for i in range(11)] + [f"Field{i}.Text" for i in range(10, 35)]
|
||||
assert not hub._pending_commands and other.frames == []
|
||||
before = list(result["results"])
|
||||
await own.acknowledge(lost[0])
|
||||
assert result["results"] == before and not hub._pending_commands
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_mapping_transport_splits_timeout_batch_and_keeps_going(tmp_path: Path) -> None:
|
||||
database = LocalTestDatabase(tmp_path / "mapping-retry.sqlite3")
|
||||
database.create_all()
|
||||
hub = VmixAgentHub(database) # type: ignore[arg-type]
|
||||
packet_sizes: list[int] = []
|
||||
def test_mapping_transport_retries_only_the_isolated_failed_command(tmp_path: Path):
|
||||
hub, own, other = transport(tmp_path)
|
||||
original = own.send_json
|
||||
attempts = {}
|
||||
|
||||
async def flaky_batch(device_id: str, *, assignment_id: str, match_id: str, commands: list[dict], timeout: float = 8.0) -> dict:
|
||||
packet_sizes.append(len(commands))
|
||||
if len(commands) > 10:
|
||||
raise HTTPException(status_code=504, detail="simulated batch timeout")
|
||||
return {"ok": True, "results": [{"ok": True} for _ in commands]}
|
||||
async def fail_one_once(message):
|
||||
if message.get("type") == "vmix.command":
|
||||
name = message["command"]["SelectedName"]
|
||||
attempts[name] = attempts.get(name, 0) + 1
|
||||
if name == "Field3.Text" and attempts[name] == 1:
|
||||
own.frames.append(message)
|
||||
await hub.receive_command_ack("GFX-OWNER", {"type": "command.ack",
|
||||
"request_id": message["request_id"], "ok": False, "reason": "HTTP 500"})
|
||||
return
|
||||
await original(message)
|
||||
|
||||
async def scenario() -> None:
|
||||
hub.send_vmix_batch = flaky_batch # type: ignore[method-assign]
|
||||
entries = [_entry(i, "ONE-BIG-INPUT") for i in range(35)]
|
||||
result = await hub._send_mapping_entries_resilient(
|
||||
"GFX-MAP-RETRY",
|
||||
assignment_id="assignment-retry",
|
||||
match_id="game-retry",
|
||||
entries=entries,
|
||||
use_batch=True,
|
||||
)
|
||||
own.send_json = fail_one_once
|
||||
result = asyncio.run(hub._send_mapping_entries_resilient("GFX-OWNER", assignment_id="assignment",
|
||||
match_id="g", entries=[_entry(i, "Score") for i in range(8)], use_batch=True))
|
||||
assert all(item["ok"] for item in result["results"])
|
||||
assert result["chunks_total"] == 1
|
||||
assert result["chunks_ok"] == 1
|
||||
assert result["chunks_failed"] == 0
|
||||
assert result["retries"] > 0
|
||||
assert packet_sizes[0] == 35
|
||||
assert any(size <= 10 for size in packet_sizes[1:])
|
||||
|
||||
asyncio.run(scenario())
|
||||
assert result["retries"] == 1 and attempts["Field3.Text"] == 2
|
||||
assert all(count == 1 for name, count in attempts.items() if name != "Field3.Text")
|
||||
assert [frame["command"]["SelectedName"] for frame in own.frames[1:]] == [
|
||||
"Field0.Text", "Field1.Text", "Field2.Text", "Field3.Text", "Field3.Text",
|
||||
"Field4.Text", "Field5.Text", "Field6.Text", "Field7.Text"]
|
||||
assert not hub._pending_commands and other.frames == []
|
||||
|
||||
|
||||
def test_mapping_transport_retries_isolated_failed_command(tmp_path: Path) -> None:
|
||||
database = LocalTestDatabase(tmp_path / "mapping-single-fallback.sqlite3")
|
||||
database.create_all()
|
||||
hub = VmixAgentHub(database) # type: ignore[arg-type]
|
||||
singles: list[dict] = []
|
||||
def test_repeated_mapping_failure_stops_before_flooding_the_agent(tmp_path: Path):
|
||||
hub, own, other = transport(tmp_path)
|
||||
original = own.send_json
|
||||
|
||||
async def partial_batch(device_id: str, *, assignment_id: str, match_id: str, commands: list[dict], timeout: float = 8.0) -> dict:
|
||||
results = [{"ok": True} for _ in commands]
|
||||
results[3] = {"ok": False, "reason": "temporary failure"}
|
||||
return {"ok": False, "results": results}
|
||||
async def reject_values(message):
|
||||
if message.get("type") != "vmix.command":
|
||||
return await original(message)
|
||||
own.frames.append(message)
|
||||
await hub.receive_command_ack("GFX-OWNER", {"type": "command.ack",
|
||||
"request_id": message["request_id"], "ok": False, "reason": "HTTP 500"})
|
||||
|
||||
async def single_ok(device_id: str, *, assignment_id: str, match_id: str, command: dict, timeout: float = 5.0) -> dict:
|
||||
singles.append(command)
|
||||
return {"ok": True}
|
||||
|
||||
async def scenario() -> None:
|
||||
hub.send_vmix_batch = partial_batch # type: ignore[method-assign]
|
||||
hub.send_vmix_command = single_ok # type: ignore[method-assign]
|
||||
entries = [_entry(i, "INPUT-FALLBACK") for i in range(8)]
|
||||
result = await hub._send_mapping_entries_resilient(
|
||||
"GFX-MAP-FALLBACK",
|
||||
assignment_id="assignment-fallback",
|
||||
match_id="game-fallback",
|
||||
entries=entries,
|
||||
use_batch=True,
|
||||
)
|
||||
assert all(item["ok"] for item in result["results"])
|
||||
assert result["fallback_commands"] == 1
|
||||
assert result["retries"] == 1
|
||||
assert len(singles) == 1
|
||||
assert singles[0]["SelectedName"] == "Field3.Text"
|
||||
|
||||
asyncio.run(scenario())
|
||||
own.send_json = reject_values
|
||||
result = asyncio.run(hub._send_mapping_entries_resilient("GFX-OWNER", assignment_id="assignment",
|
||||
match_id="g", entries=[_entry(i, "Score") for i in range(200)], use_batch=True))
|
||||
assert len(result["results"]) == 200 and all(not item["ok"] for item in result["results"])
|
||||
assert result["retries"] == 3
|
||||
assert len(own.frames) == 7 # assignment + at most two attempts for three failed fields
|
||||
assert other.frames == [] and not hub._pending_commands
|
||||
|
||||
|
||||
def test_build97_runtime_version_and_mapping_diagnostics() -> None:
|
||||
def test_mapping_diagnostics_report_actual_retry_without_claiming_unconfirmed_delivery(tmp_path: Path):
|
||||
hub, own, _ = transport(tmp_path)
|
||||
result = asyncio.run(hub._send_mapping_entries_resilient("GFX-OWNER", assignment_id="assignment",
|
||||
match_id="g", entries=[_entry(i, "Score") for i in range(2)], use_batch=False))
|
||||
assert result["ack_waited"] is True and result["transport"] == "sequential_ack"
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
app = (root / "app.py").read_text(encoding="utf-8")
|
||||
bridge = (root / "hockey_data" / "agent_bridge.py").read_text(encoding="utf-8")
|
||||
admin = (root / "hockey_data" / "static" / "admin-directories.js").read_text(encoding="utf-8")
|
||||
|
||||
assert 'BUILD_VERSION = "2026.08.21.1"' in app
|
||||
assert 'result["transport"] = "chunked_batch" if use_batch else "legacy"' in bridge
|
||||
assert 'MAPPING_BATCH_MAX_COMMANDS = 40' in bridge
|
||||
assert 'mappingApplyTransportSummary' in admin
|
||||
assert 'пакетов ${chunksApplied}/${chunksTotal}' in admin
|
||||
admin = (root / "hockey_data/static/admin-directories.js").read_text(encoding="utf-8")
|
||||
_run_functions(admin, ["mappingApplyTransportSummary"], r'''
|
||||
const summary = mappingApplyTransportSummary({transport:'sequential_ack', input_groups:1,
|
||||
mapping_commands_sent:2, batch_retries:1, batch_chunks_total:0, batch_chunks_applied:0});
|
||||
assert.ok(summary.includes('Input: 1'));
|
||||
assert.ok(summary.includes('повторов 1'));
|
||||
assert.ok(!summary.includes('без ожидания ACK'));
|
||||
assert.ok(!summary.includes('пакетов'));
|
||||
''')
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -15,38 +16,26 @@ def _block(start: str, end: str) -> str:
|
||||
|
||||
|
||||
def test_vmix_queue_resolves_countdown_values_at_actual_send_time():
|
||||
compact = _block("function compactVmixCommand", "function currentRuntimeVmixDeviceId")
|
||||
assert 'typeof rawValue === "function" ? rawValue() : rawValue' in compact
|
||||
sender = _block("async function sendRuntimeVmixSequence", "function splitVmixInputs")
|
||||
assert 'const rawCommands = typeof commands === "function" ? commands() : commands;' in sender
|
||||
assert 'const clean = (rawCommands || []).map(compactVmixCommand)' in sender
|
||||
from tests.test_build103_space_timer_fast_transport import run_transport_contract
|
||||
run_transport_contract("queued_values_sampled_at_dispatch")
|
||||
|
||||
|
||||
def test_countdown_start_is_simple_set_start():
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
start_branch = helper.split('return [', 3)[-1]
|
||||
assert 'Function: "SuspendCountdown"' not in start_branch
|
||||
assert start_branch.index('Function: "SetCountdown"') < start_branch.index('Function: "StartCountdown"')
|
||||
assert 'Value: currentValue' in helper
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('first_start')
|
||||
|
||||
|
||||
def test_pause_and_stop_freeze_without_reseed():
|
||||
helper = _block("function vmixCountdownSyncCommands", "function buildShortcutRuntimeContext")
|
||||
branch = helper.split('if (action === "stop" || action === "pause")', 1)[1].split('return [', 1)[1].split('];', 1)[0]
|
||||
assert 'Function: "SuspendCountdown"' in branch
|
||||
assert 'Function: "StopCountdown"' not in branch
|
||||
assert 'Function: "SetCountdown"' not in branch
|
||||
assert 'Function: "PauseCountdown"' not in branch
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('pause_freezes')
|
||||
|
||||
|
||||
# Native penalty transitions are exercised in test_stage2_penalty_countdown.py.
|
||||
|
||||
|
||||
def test_running_penalty_is_preferred_over_paused_shorter_penalty():
|
||||
sorted_block = _block("function sortedPenaltyEntries", "function penaltyLocalAdvantageSide")
|
||||
assert 'const runningOrder = Number(Boolean(b.event?.running)) - Number(Boolean(a.event?.running));' in sorted_block
|
||||
display = _block("function penaltyDisplayEntriesByTargetSide", "function rememberPenaltyAdvantagePlan")
|
||||
assert 'const runningOrder = Number(Boolean(b.event?.running)) - Number(Boolean(a.event?.running));' in display
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('penalty_priority')
|
||||
|
||||
|
||||
def test_fixed_pin_1993_replaces_daily_login(tmp_path, monkeypatch):
|
||||
@@ -60,4 +49,4 @@ def test_fixed_pin_1993_replaces_daily_login(tmp_path, monkeypatch):
|
||||
|
||||
|
||||
def test_build98_runtime_version():
|
||||
assert 'BUILD_VERSION = "2026.08.24.4"' in APP
|
||||
assert_current_build_contract()
|
||||
|
||||
@@ -2,13 +2,12 @@ from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_assigned_penalty_display_with_real_runtime_functions():
|
||||
node = shutil.which("node")
|
||||
if node is None:
|
||||
pytest.skip("Install Node for the browser regression")
|
||||
assert node is not None, "Node.js is required for the browser regression"
|
||||
result = subprocess.run([node, str(Path(__file__).with_name("hotfix_penalty_visibility.cjs"))],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert "PASS: prepared penalty display" in result.stdout, result.stdout + result.stderr
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import sys
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
from threading import RLock
|
||||
@@ -195,13 +196,60 @@ def test_matches_failure_preserves_old_cache_and_marks_it_stale(tmp_path,monkeyp
|
||||
assert path.read_bytes()==before
|
||||
|
||||
|
||||
def test_refresh_api_uses_current_python_fresh_cache_and_bounded_workers(monkeypatch):
|
||||
captured=[]
|
||||
monkeypatch.setattr(center,'JOBS',SimpleNamespace(start=lambda t,c:captured.extend(c),state=lambda:{'running':True}))
|
||||
center.api_collect('player-names')
|
||||
command=captured[0]
|
||||
assert command[1]=='-u' and '--force' in command and '--names-only' in command
|
||||
assert command[command.index('--workers')+1]=='3'
|
||||
@pytest.mark.parametrize('workers,delay,expected_workers,expected_delay', [
|
||||
(-2, 0, 1, 0.1), (1, 0.5, 1, 0.5), (3, 2, 3, 2.0), (1000, 999, 4, 10.0),
|
||||
])
|
||||
def test_refresh_api_uses_current_python_fresh_cache_and_bounded_workers(
|
||||
tmp_path, monkeypatch, workers, delay, expected_workers, expected_delay,
|
||||
):
|
||||
# Never depend on, or rewrite, the studio's actual saved collector settings.
|
||||
config_path = tmp_path / 'updates.json'
|
||||
config_path.write_text(json.dumps({'workers': workers, 'request_delay_seconds': delay}))
|
||||
before = config_path.read_bytes()
|
||||
monkeypatch.setattr(center, 'CONFIG_PATH', config_path)
|
||||
monkeypatch.setattr(center, 'DATA_DIR', tmp_path / 'data')
|
||||
monkeypatch.setattr(center, 'ROOT', tmp_path / 'collector')
|
||||
captured = []
|
||||
monkeypatch.setattr(center, 'JOBS', SimpleNamespace(
|
||||
start=lambda title, commands: captured.extend(commands),
|
||||
state=lambda: {'running': True},
|
||||
))
|
||||
|
||||
assert center.api_collect('player-names') == {'ok': True, 'job': {'running': True}}
|
||||
assert len(captured) == 1
|
||||
command = captured[0]
|
||||
assert command[:3] == [sys.executable, '-u', str(center.ROOT / 'khl_site_collector.py')]
|
||||
assert command[command.index('--output-dir') + 1] == str(center.DATA_DIR)
|
||||
assert command[command.index('--cache-dir') + 1] == str(center.ROOT / 'cache' / 'khl_site_html')
|
||||
assert command[command.index('--workers') + 1] == str(expected_workers)
|
||||
assert float(command[command.index('--delay') + 1]) == expected_delay
|
||||
assert '--force' in command and command[-3:] == ['--kind', 'players', '--names-only']
|
||||
assert config_path.read_bytes() == before
|
||||
|
||||
|
||||
def test_refresh_api_uses_safe_defaults_without_creating_missing_config(tmp_path, monkeypatch):
|
||||
config_path = tmp_path / 'missing.json'
|
||||
monkeypatch.setattr(center, 'CONFIG_PATH', config_path)
|
||||
_, commands = center.collector_commands('players')
|
||||
command = commands[0]
|
||||
assert command[command.index('--workers') + 1] == '1'
|
||||
assert command[command.index('--delay') + 1] == '0.5'
|
||||
assert '--force' in command and '--names-only' not in command
|
||||
assert not config_path.exists()
|
||||
|
||||
|
||||
def test_refresh_api_rejects_invalid_config_before_starting_job(tmp_path, monkeypatch):
|
||||
config_path = tmp_path / 'invalid.json'
|
||||
config_path.write_text(json.dumps({'workers': 'invalid'}))
|
||||
before = config_path.read_bytes()
|
||||
monkeypatch.setattr(center, 'CONFIG_PATH', config_path)
|
||||
monkeypatch.setattr(center, 'JOBS', SimpleNamespace(
|
||||
start=lambda *args: pytest.fail('Invalid settings must not start a collector process'),
|
||||
))
|
||||
with pytest.raises(HTTPException) as error:
|
||||
center.api_collect('players')
|
||||
assert error.value.status_code == 409
|
||||
assert config_path.read_bytes() == before
|
||||
|
||||
|
||||
def test_corrupt_local_snapshot_keeps_previously_loaded_data(tmp_path,monkeypatch):
|
||||
|
||||
@@ -43,8 +43,7 @@ def test_player_card_no_longer_references_undefined_flag() -> None:
|
||||
assert "KHL_API_BASE" in html
|
||||
|
||||
|
||||
def test_admin_khl_tab_is_conditional_on_selected_khl_tournament() -> None:
|
||||
js = (ROOT / "hockey_data" / "static" / "admin-directories.js").read_text(encoding="utf-8")
|
||||
assert 'context.tournamentLevel === "khl"' in js
|
||||
assert 'data-directory-section="khl_site"' in js
|
||||
assert 'src="/khl-site/"' in js
|
||||
def test_admin_khl_tab_is_conditional_on_selected_khl_tournament():
|
||||
"""The remaining admin renderer gates KHL correctly; its navigation entry moved to the runtime workspace."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("khl_gate")
|
||||
|
||||
@@ -65,17 +65,10 @@ def test_sql_preview_does_not_hide_rows_after_eight():
|
||||
|
||||
|
||||
def test_mapping_has_series_autolink_and_visible_sql_table_grid():
|
||||
js = (ROOT / "hockey_data" / "static" / "admin-directories.js").read_text(encoding="utf-8")
|
||||
css = (ROOT / "hockey_data" / "static" / "admin-directories.css").read_text(encoding="utf-8")
|
||||
assert "mappingFieldSequence" in js
|
||||
assert "mappingSeriesPlan" in js
|
||||
assert "data-map-series-column" in js
|
||||
assert "data-map-series-row" in js
|
||||
assert "Автосвязать столбец" in js
|
||||
assert "Размножить строку" in js
|
||||
assert "tableGridHeight" in js
|
||||
assert "min-height:230px" in css
|
||||
assert "max-height:430px" in css
|
||||
"""Autolink follows numbered targets and the compact browser exposes every SQL column."""
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("mapping_series")
|
||||
ui_contract("mapping_browser")
|
||||
|
||||
|
||||
def test_mapping_vmix_fields_have_text_image_color_filters_and_hide_linked_toggle():
|
||||
|
||||
@@ -121,7 +121,7 @@ def test_mapping_recovers_when_only_unrelated_vmix_inputs_change(tmp_path: Path)
|
||||
{
|
||||
"key": "score-key",
|
||||
"number": "17",
|
||||
"title": "Score Renamed",
|
||||
"title": "Score",
|
||||
"type": "GT",
|
||||
"fields": [{"name": "Clock.Text", "type": "text", "index": "4"}],
|
||||
},
|
||||
@@ -152,6 +152,7 @@ def test_mapping_recovers_when_only_unrelated_vmix_inputs_change(tmp_path: Path)
|
||||
)
|
||||
session.add(profile)
|
||||
session.flush()
|
||||
source_id = profile.id
|
||||
session.add(VmixMappingField(
|
||||
profile_id=profile.id,
|
||||
graphic="score",
|
||||
@@ -176,7 +177,9 @@ def test_mapping_recovers_when_only_unrelated_vmix_inputs_change(tmp_path: Path)
|
||||
assigned = [item for item in ws.sent if item.get("type") == "mapping.assigned"]
|
||||
missing = [item for item in ws.sent if item.get("type") == "mapping.missing"]
|
||||
assert assigned
|
||||
assert assigned[-1]["name"] == "RECOVER-MAP"
|
||||
assert assigned[-1]["id"] != source_id
|
||||
assert assigned[-1]["name"].startswith("__AUTO_MAPPING__")
|
||||
assert assigned[-1]["fields"][0]["vmix_input_title"] == "Score"
|
||||
assert not missing
|
||||
|
||||
with database.session() as session:
|
||||
@@ -184,9 +187,35 @@ def test_mapping_recovers_when_only_unrelated_vmix_inputs_change(tmp_path: Path)
|
||||
assert device is not None
|
||||
resolved = hub._active_mapping_profile_for_device(session, device)
|
||||
assert resolved is not None
|
||||
assert resolved.name == "RECOVER-MAP"
|
||||
# Compatibility recovery must not rewrite the profile's primary
|
||||
# fingerprint just because this Agent has an unrelated extra Input.
|
||||
assert resolved.project_fingerprint == old_stable
|
||||
assert resolved.id == device.mapping_profile_id == assigned[-1]["id"]
|
||||
assert device.mapping_source_profile_id == source_id
|
||||
assert device.mapping_profile_version == resolved.version == 1
|
||||
assert resolved.project_fingerprint == new_stable
|
||||
# Recovery publishes this Agent's independent snapshot without
|
||||
# rewriting the shared source template used by another project.
|
||||
source = session.get(VmixMappingProfile, source_id)
|
||||
assert source.name == "RECOVER-MAP" and source.project_fingerprint == old_stable
|
||||
assert source.active is True
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_mapping_recovery_does_not_guess_renamed_mapped_input_by_guid(tmp_path: Path):
|
||||
import json
|
||||
database = LocalTestDatabase(tmp_path / "renamed-target.sqlite3")
|
||||
database.create_all()
|
||||
hub = VmixAgentHub(database)
|
||||
with database.session() as session:
|
||||
profile = VmixMappingProfile(name="Existing mapping", project_fingerprint="a" * 64,
|
||||
inventory_json="{}", active=True, created_by="admin", updated_by="admin")
|
||||
session.add(profile)
|
||||
session.flush()
|
||||
session.add(VmixMappingField(profile_id=profile.id, data_key="game.clock", graphic="clock",
|
||||
vmix_input_key="same-guid", vmix_input_number="5", vmix_input_title="Score",
|
||||
vmix_field="Clock.Text", field_type="text", enabled=True, sort_order=0))
|
||||
device = VmixDevice(device_uuid="GFX-RENAMED", device_secret_hash="x", project_fingerprint="b" * 64,
|
||||
project_inventory_json=json.dumps({"inputs": [{"key": "same-guid", "number": "5",
|
||||
"title": "Score Renamed", "fields": [{"name": "Clock.Text", "type": "text"}]}]}))
|
||||
session.add(device)
|
||||
session.flush()
|
||||
assert hub._compatible_mapping_profile_for_device(session, device) is None
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from __future__ import annotations
|
||||
from tests.timer_contract_support import run_timer_contract, assert_current_build_contract
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
@@ -105,16 +106,9 @@ def test_shortcut_editor_layout_fixes_add_step_buttons_and_fullscreen_modal() ->
|
||||
|
||||
|
||||
def test_hockey_timer_shortcut_supports_native_countdown_and_legacy_text_mirror() -> None:
|
||||
app_js = Path("ui_builder/static/app.js").read_text(encoding="utf-8")
|
||||
assert 'Function: "StopCountdown"' in app_js
|
||||
assert 'Function: "SuspendCountdown"' not in app_js
|
||||
assert 'Function: "StopCountdown"' in app_js
|
||||
assert 'hockey_timer_command' in app_js
|
||||
assert 'game_vmix_mode' in app_js
|
||||
assert 'game_vmix_selected_name' in app_js
|
||||
assert 'vmixTimerMirrors' in app_js
|
||||
assert 'Function: "SetText"' in app_js
|
||||
assert 'combo: "Space"' in app_js
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('no_legacy_text_packets')
|
||||
run_timer_contract('target_scope')
|
||||
|
||||
|
||||
def test_global_shortcuts_capture_keys_before_focused_runtime_controls() -> None:
|
||||
@@ -197,10 +191,8 @@ def test_hockey_countdown_uses_selected_name_for_game_and_penalty_targets() -> N
|
||||
|
||||
|
||||
def test_overlay_group_repeat_uses_transition_out_not_all_off():
|
||||
js = Path("ui_builder/static/app.js").read_text(encoding="utf-8")
|
||||
assert 'Function: "OverlayInputAllOff"' not in js
|
||||
for layer in range(1, 5):
|
||||
assert f'Function: "OverlayInput{layer}Out"' in js
|
||||
from tests.ui_contract_support import ui_contract
|
||||
ui_contract("overlay_group")
|
||||
|
||||
|
||||
def test_build90_migrates_old_text_timer_transport_to_native_countdown(tmp_path: Path) -> None:
|
||||
@@ -250,13 +242,5 @@ def test_build90_keeps_explicit_legacy_text_mode_after_v22(tmp_path: Path) -> No
|
||||
|
||||
|
||||
def test_build90_native_countdown_avoids_per_second_transport() -> None:
|
||||
app_js = Path("ui_builder/static/app.js").read_text(encoding="utf-8")
|
||||
assert 'game_vmix_mode !== "countdown"' in app_js
|
||||
assert 'const countdownMode = step.penalty_vmix_mode === "countdown"' in app_js
|
||||
assert 'Function: "StopCountdown"' in app_js
|
||||
assert 'Function: "SuspendCountdown"' not in app_js
|
||||
assert 'Function: "StopCountdown"' in app_js
|
||||
assert 'signal: controller.signal' in app_js
|
||||
assert 'vmixCommandQueue: Promise.resolve()' in app_js
|
||||
# Per-second pushes are restricted to the legacy Text mirror map.
|
||||
assert 'eventName === "timer_tick" && state.vmixTimerMirrors.has(component.action_id)' in app_js
|
||||
"""Current native timer contract, executed against production functions."""
|
||||
run_timer_contract('no_tick_transport')
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from hockey_data.agent_bridge import _stable_vmix_inventory_fingerprint
|
||||
|
||||
@@ -54,13 +56,62 @@ def test_legacy_project_fingerprint_uses_title_instead_of_number():
|
||||
assert _stable_vmix_inventory_fingerprint(before) == _stable_vmix_inventory_fingerprint(after)
|
||||
|
||||
|
||||
def test_shortcut_editor_persists_key_before_number():
|
||||
def _run_functions(source, names, scenario):
|
||||
# Execute the shipped function bodies; test doubles supply only page state.
|
||||
functions = []
|
||||
for name in names:
|
||||
match = re.search(r"(?m)^ function " + re.escape(name) + r"\(", source)
|
||||
assert match, name
|
||||
following = re.search(r"(?m)^ (?:async )?function ", source[match.end():])
|
||||
assert following, name
|
||||
functions.append(source[match.start():match.end() + following.start()])
|
||||
script = "const assert = require('node:assert/strict');\n" + "\n".join(functions) + "\n" + scenario
|
||||
result = subprocess.run(["node", "-e", script], text=True, capture_output=True, timeout=10)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_shortcut_editor_persists_title_and_migrates_legacy_selectors():
|
||||
app_js = (ROOT / "ui_builder" / "static" / "app.js").read_text(encoding="utf-8")
|
||||
assert 'return String(item?.key || item?.title || item?.number || "").trim();' in app_js
|
||||
assert "старый номер Input — выберите Input заново один раз" in app_js
|
||||
_run_functions(app_js, ["vmixInventoryInputs", "vmixInputRef", "vmixInputByRef"], r'''
|
||||
const score = {key: 'score-guid', number: '5', title: 'Score'};
|
||||
const other = {key: 'other-guid', number: '9', title: 'Other'};
|
||||
const state = {shortcutInventory: {inventory: {inputs: [score, other]}}};
|
||||
assert.equal(vmixInputRef(score), 'Score');
|
||||
assert.equal(vmixInputRef({key: 'only-guid', number: '5'}), '');
|
||||
for (const legacy of ['score-guid', '5']) assert.equal(vmixInputRef(vmixInputByRef(legacy)), 'Score');
|
||||
const saved = vmixInputRef(score);
|
||||
score.number = '9'; other.number = '5'; score.key = 'new-score-guid';
|
||||
assert.equal(vmixInputByRef(saved), score);
|
||||
assert.equal(vmixInputRef(vmixInputByRef(saved)), 'Score');
|
||||
assert.equal(vmixInputByRef('missing'), null);
|
||||
''')
|
||||
|
||||
|
||||
def test_mapping_links_do_not_resave_positional_number():
|
||||
def test_mapping_links_save_exact_title_and_clear_every_positional_number():
|
||||
mapping_js = (ROOT / "hockey_data" / "static" / "admin-directories.js").read_text(encoding="utf-8")
|
||||
assert 'vmix_input_number: ""' in mapping_js
|
||||
assert 'vmix_input_number: (row.vmix_input_key || row.vmix_input_title) ? ""' in mapping_js
|
||||
_run_functions(mapping_js, ["mappingInventoryInputs", "mappingFieldKind", "mappingRowMatchesInput",
|
||||
"mappingInputTitleProblem", "mappingSetLink", "collectMappingFields"], r'''
|
||||
const input = {key: 'current-guid', number: '17', title: 'Score', fields: [{name: 'Home.Text', type: 'text'}]};
|
||||
const profile = {inventory: {inputs: [input]}, fields: [{data_key:'old', vmix_input_key:'old-guid',
|
||||
vmix_input_number:'5', vmix_input_title:'Score', vmix_field:'Home.Text', rule:{enabled:true, left_key:'old'}}]};
|
||||
const state = {mappingActiveProfile:profile};
|
||||
const statuses = []; function setStatus(message){statuses.push(message);}
|
||||
mappingSetLink(profile, input, input.fields[0], {key:'score.home'});
|
||||
assert.equal(profile.fields.length, 1);
|
||||
assert.equal(profile.fields[0].vmix_input_title, 'Score');
|
||||
assert.equal(profile.fields[0].vmix_input_key, 'current-guid');
|
||||
assert.equal(profile.fields[0].vmix_input_number, '');
|
||||
assert.equal(profile.fields[0].rule.left_key, 'score.home');
|
||||
profile.fields.push({data_key:'legacy', vmix_input_key:'another-guid', vmix_input_number:'42', vmix_input_title:'Other', vmix_field:'Away.Text'});
|
||||
profile.fields.push({data_key:'orphaned-legacy', vmix_input_key:'', vmix_input_number:'7', vmix_input_title:'', vmix_field:'Legacy.Text'});
|
||||
const collected = collectMappingFields();
|
||||
assert.deepEqual(collected.map(row=>row.vmix_input_number), ['', '', '']);
|
||||
assert.deepEqual(collected.map(row=>row.vmix_input_title), ['Score', 'Other', '']);
|
||||
assert.deepEqual(collected.map(row=>row.sort_order), [0, 1, 2]);
|
||||
assert.equal(profile.fields[1].vmix_input_number, '42', 'Collecting must not mutate draft rows');
|
||||
const previous = JSON.stringify(profile.fields);
|
||||
profile.inventory.inputs.push({...input, key:'duplicate-guid', number:'18'});
|
||||
mappingSetLink(profile, input, input.fields[0], {key:'unsafe'});
|
||||
assert.equal(JSON.stringify(profile.fields), previous);
|
||||
assert.ok(statuses.length && statuses[0].includes('не уникально'));
|
||||
''')
|
||||
|
||||
51
tests/timer_contract_support.py
Normal file
51
tests/timer_contract_support.py
Normal file
@@ -0,0 +1,51 @@
|
||||
"""Execute production browser functions under Node and verify the current served build."""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from datetime import date
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def run_timer_contract(scenario: str) -> None:
|
||||
node = shutil.which("node")
|
||||
assert node is not None, "Node is required for executable browser timer regressions"
|
||||
result = subprocess.run([node, str(ROOT / "tests/runtime_timer_contracts.cjs"), scenario],
|
||||
capture_output=True, text=True, timeout=15)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert f"PASS: {scenario}" in result.stdout
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def assert_current_build_contract() -> None:
|
||||
"""Check the actual assignment and rendered boot, ignoring historical comments."""
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from ui_builder.integration import install_ui_builder
|
||||
|
||||
module = ast.parse((ROOT / "app.py").read_text(encoding="utf-8"))
|
||||
assignments = [node for node in module.body if isinstance(node, ast.Assign)
|
||||
and any(isinstance(target, ast.Name) and target.id == "BUILD_VERSION" for target in node.targets)]
|
||||
assert len(assignments) == 1
|
||||
version = ast.literal_eval(assignments[0].value)
|
||||
assert isinstance(version, str) and re.fullmatch(r"\d{4}\.\d{2}\.\d{2}\.\d+", version)
|
||||
date(*map(int, version.split(".")[:3]))
|
||||
install_calls = [node for node in ast.walk(module) if isinstance(node, ast.Call)
|
||||
and isinstance(node.func, ast.Name) and node.func.id == "install_ui_builder"]
|
||||
assert len(install_calls) == 1
|
||||
assert any(keyword.arg == "build_version" and isinstance(keyword.value, ast.Name)
|
||||
and keyword.value.id == "BUILD_VERSION" for keyword in install_calls[0].keywords)
|
||||
with TemporaryDirectory() as temporary:
|
||||
app = FastAPI()
|
||||
install_ui_builder(app, build_version=version, settings_dir=Path(temporary), data_providers={})
|
||||
with TestClient(app) as client:
|
||||
response = client.get("/")
|
||||
assert response.status_code == 200
|
||||
assert f'buildVersion: "{version}"' in response.text
|
||||
assert "__UI_BUILDER_BUILD_VERSION__" not in response.text
|
||||
13
tests/ui_contract_support.py
Normal file
13
tests/ui_contract_support.py
Normal file
@@ -0,0 +1,13 @@
|
||||
"""Execute current JavaScript helpers without booting the live server."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
|
||||
def ui_contract(name: str) -> None:
|
||||
node = shutil.which("node")
|
||||
assert node is not None, "Node.js is required for UI regression contracts"
|
||||
script = Path(__file__).with_name("ui_legacy_contracts.cjs")
|
||||
result = subprocess.run([node, str(script), name], capture_output=True, text=True, timeout=20)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert f"PASS UI contract: {name}" in result.stdout, result.stdout + result.stderr
|
||||
241
tests/ui_legacy_contracts.cjs
Normal file
241
tests/ui_legacy_contracts.cjs
Normal file
@@ -0,0 +1,241 @@
|
||||
/* Execute extracted production helpers; mock only API, settings and DOM edges. */
|
||||
const fs = require('node:fs'), path = require('node:path'), vm = require('node:vm'), assert = require('node:assert/strict');
|
||||
const sources = {
|
||||
app: fs.readFileSync(path.join(__dirname, '../ui_builder/static/app.js'), 'utf8'),
|
||||
admin: fs.readFileSync(path.join(__dirname, '../hockey_data/static/admin-directories.js'), 'utf8'),
|
||||
menu: fs.readFileSync(path.join(__dirname, '../hockey_data/static/tournament-menu.js'), 'utf8'),
|
||||
};
|
||||
const plain = value => JSON.parse(JSON.stringify(value));
|
||||
const noop = () => {};
|
||||
const escapeHtml = value => String(value ?? '').replaceAll('&','&').replaceAll('<','<').replaceAll('>','>').replaceAll('"','"');
|
||||
function definition(source, name) {
|
||||
const match = new RegExp('(^|\\n)([ \\t]*)(?:async )?function ' + name + '\\(').exec(source);
|
||||
assert.ok(match, 'Production helper missing: ' + name);
|
||||
const start = match.index + match[1].length;
|
||||
const end = source.indexOf('\n' + match[2] + '}', start);
|
||||
assert.ok(end >= 0, 'Production helper has no end: ' + name);
|
||||
return source.slice(start, end + match[2].length + 2);
|
||||
}
|
||||
function context(names, additions = {}, which = 'app') {
|
||||
const ctx = { console, Date, performance, URL, URLSearchParams, setTimeout, clearTimeout, queueMicrotask,
|
||||
state: { config: { components: [], shortcut_sequences: [] }, data: {}, formValues: {} },
|
||||
window: { dispatchEvent: noop }, CustomEvent: class { constructor(type, payload) { this.type=type; this.detail=payload?.detail; } },
|
||||
document: { querySelectorAll: () => [], activeElement: null }, clone: plain, escapeHtml, ...additions };
|
||||
vm.createContext(ctx);
|
||||
vm.runInContext(names.map(name => definition(sources[which], name)).join('\n'), ctx, { filename: `production-${which}-helpers.js` });
|
||||
return ctx;
|
||||
}
|
||||
function defer() { let resolve; const promise = new Promise(done => resolve=done); return { promise, resolve }; }
|
||||
const tick = async () => { for (let i=0;i<8;i++) await Promise.resolve(); };
|
||||
const overlayNames = ['vmixOverlayLayer','sequenceStillOwnsRuntimeOverlay','shortcutSequenceOverlayIntent','reconcileShortcutSequenceOnAir',
|
||||
'normalizeRuntimeVmixInputRef','shortcutSequenceOverlayTargets','runtimeOverlayInputRefs','runtimeOverlayMatchesInput','shortcutSequencePreviewTargets',
|
||||
'shortcutSequenceSharesLivePenaltyInput','sequenceMatchesRuntimeOverlay','setQuickPanelSequenceOnAir','shortcutSequenceIsOnAir','sequenceConditionMatches'];
|
||||
function overlayContext(extra = {}) {
|
||||
const state = { config:{components:[],shortcut_sequences:[]}, data:{}, vmixOverlayRuntime:new Map(), quickPanelOnAirSequences:new Set(),
|
||||
quickPanelServerOnAirSequences:new Set(), shortcutSequenceOverlayState:new Map(), vmixOverlayTallyAuthoritative:false,
|
||||
activeHockeyVmixTimerSteps:new Set(), runningShortcutSequences:new Set(),pendingShortcutSequenceRuns:new Map() };
|
||||
const c=context(overlayNames, {state, shortcutSequenceById:id=>state.config.shortcut_sequences.find(s=>s.id===id),
|
||||
buildShortcutRuntimeContext:()=>({hockey:{flags:{}},active_tab:'main'}), templateSequenceValue:value=>String(value||''),
|
||||
hockeyPenaltyOverlayFallbackTargets:()=>new Map(),refreshQuickPanelOnAirClasses:noop,hockeyScoreboardSequenceIsLive:()=>false,...extra});
|
||||
return c;
|
||||
}
|
||||
const cases = {};
|
||||
cases.overlay_parser = async () => {
|
||||
const c=overlayContext();
|
||||
for(let layer=1;layer<=8;layer++) {
|
||||
assert.deepEqual(plain(c.vmixOverlayLayer(` Overlay Input ${layer} In &Input=Score`)),{layer:String(layer),action:'In'});
|
||||
assert.deepEqual(plain(c.vmixOverlayLayer(`OverlayInput${layer}Out`)),{layer:String(layer),action:'Out'});
|
||||
assert.equal(c.vmixOverlayLayer(`OverlayInput${layer}`)?.action,'toggle');
|
||||
}
|
||||
assert.equal(c.vmixOverlayLayer('OverlayInput9In'),null);
|
||||
assert.equal(c.vmixOverlayLayer('OverlayInputAllOff'),null);
|
||||
};
|
||||
cases.onair = async () => {
|
||||
const c=overlayContext(),s={id:'player',steps:[{type:'vmix_command',function:'OverlayInput8In',input:'Player Title'}]};
|
||||
c.state.config.shortcut_sequences=[s];
|
||||
c.state.vmixOverlayRuntime.set('8',{input_title:'Player Title',input:'27'});
|
||||
assert.equal(c.shortcutSequenceIsOnAir(s.id),true,'actual title match overrides absent local latch');
|
||||
c.state.vmixOverlayTallyAuthoritative=true;
|
||||
c.state.vmixOverlayRuntime.set('8',{input:'Another Title'});c.state.quickPanelOnAirSequences.add(s.id);
|
||||
assert.equal(c.shortcutSequenceIsOnAir(s.id),false,'authoritative replacement clears stale local ON AIR');
|
||||
c.state.vmixOverlayTallyAuthoritative=false;c.state.vmixOverlayRuntime.clear();
|
||||
assert.equal(c.shortcutSequenceIsOnAir(s.id),true,'offline tally falls back to ACK-confirmed latch');
|
||||
c.state.quickPanelOnAirSequences.clear();
|
||||
assert.equal(c.reconcileShortcutSequenceOnAir(s),true);
|
||||
s.steps[0].function='OverlayInput8Out';assert.equal(c.reconcileShortcutSequenceOnAir(s),false);
|
||||
s.steps[0].function='OverlayInput8';assert.equal(c.reconcileShortcutSequenceOnAir(s),true);assert.equal(c.reconcileShortcutSequenceOnAir(s),false);
|
||||
};
|
||||
cases.overlay_group = async () => {
|
||||
const sent=[],c=overlayContext({hockeyCanControl:()=>true,hockeyTimerSelectedGameId:()=> 'g',currentRuntimeVmixDeviceId:()=> 'd',currentRuntimeHockeySessionToken:()=> 's',
|
||||
hockeyScoreboardIsLive:()=>false,hockeyRestorePenaltyOverlayLayers:async()=>0,hockeyClearTeamStateOverlayTracking:noop,
|
||||
runShortcutTimerControlsWhileBusy:()=>false,toast:noop,
|
||||
sendRuntimeVmixSequence:async(commands,opts)=>{assert.equal(opts.isCurrent(),true);sent.push(...commands);return {ok:true};}});
|
||||
vm.runInContext(definition(sources.app,'runShortcutSequence'),c);
|
||||
const seq={id:'group',name:'Group',toggle_all_overlays_on_repeat:true,repeat_overlay_outs:['1','8','8','9'],repeat_overlay_out_scope:'group',steps:[]};
|
||||
c.state.config.shortcut_sequences=[seq];c.state.quickPanelOnAirSequences.add(seq.id);
|
||||
c.state.vmixOverlayRuntime.set('1',{input:'Score'});c.state.vmixOverlayRuntime.set('8',{input:'Lower'});c.state.vmixOverlayRuntime.set('2',{input:'Other'});
|
||||
assert.equal(await c.runShortcutSequence(seq),true);
|
||||
assert.deepEqual(sent.map(x=>x.Function),['OverlayInput1Out','OverlayInput8Out']);
|
||||
assert.ok(sent.every(x=>x.Function!=='OverlayInputAllOff'));
|
||||
assert.equal(c.state.vmixOverlayRuntime.get('2').input,'Other');
|
||||
sent.length=0;c.state.quickPanelOnAirSequences.add(seq.id);seq.repeat_overlay_out_scope='owned';
|
||||
assert.equal(await c.runShortcutSequence(seq),true);assert.deepEqual(sent,[],'owned repeat cannot remove another sequence title');
|
||||
};
|
||||
cases.strength = async () => {
|
||||
const calls=[],wait=defer();let allowed=true,game='g';
|
||||
const c=context(['hockeyStrengthMappingSignature','hockeyRefreshVmixMappingForStrength'],{hockeyCanControl:()=>allowed,hockeyTimerSelectedGameId:()=>game,currentRuntimeVmixDeviceId:()=> 'device',
|
||||
fetch:async(url,options)=>{calls.push({url,options});if(calls.length===1)await wait.promise;return {ok:true,json:async()=>({ok:true})};}});
|
||||
const before={current_period:'1',strength:{state_key:'5x5'}},after={current_period:'1',strength:{state_key:'5x4'}};
|
||||
assert.equal(await c.hockeyRefreshVmixMappingForStrength('g',before,before),false);assert.equal(calls.length,0);
|
||||
const first=c.hockeyRefreshVmixMappingForStrength('g',before,after);await tick();
|
||||
assert.equal(calls.length,1);const u=new URL(calls[0].url,'http://local');assert.equal(u.searchParams.get('source_code'),'strength');assert.equal(u.searchParams.has('only_changed'),false,'strength is intentionally resent after transitions');
|
||||
await c.hockeyRefreshVmixMappingForStrength('g',after,{current_period:'2',strength:{state_key:'5x3'}});assert.equal(calls.length,1,'overlapping transition is coalesced');
|
||||
wait.resolve();await first;await tick();assert.equal(calls.length,2);
|
||||
allowed=false;assert.equal(await c.hockeyRefreshVmixMappingForStrength('g',before,after),false);game='other';allowed=true;assert.equal(await c.hockeyRefreshVmixMappingForStrength('g',before,after),false);
|
||||
};
|
||||
cases.toasts_triggers = async () => {
|
||||
const fired=[],toastNode={textContent:'',style:{},classList:{add:noop,remove:noop}};
|
||||
const c=context(['processTriggers','toast'],{state:{config:{triggers:[{enabled:true,source_action_id:'score',event:'change',action:{}}]},triggerDepth:0,triggersEnabled:false,operatorToastsEnabled:false},
|
||||
el:{toast:toastNode},boot:{mode:'runtime'},conditionMatches:()=>true,runTriggerAction:async(trigger,ctx,execution)=>fired.push({trigger,ctx,execution})});
|
||||
await c.processTriggers({action_id:'score',event:'change'}, {titleActionQueued:true});assert.equal(fired.length,1);assert.equal(c.state.triggerDepth,0);
|
||||
c.toast('routine');assert.equal(toastNode.textContent,'');c.toast('failure',true);assert.equal(toastNode.textContent,'failure');clearTimeout(c.toast.timer);
|
||||
c.toast('forced',false,{force:true});assert.equal(toastNode.textContent,'forced');clearTimeout(c.toast.timer);
|
||||
};
|
||||
cases.scale = async () => {
|
||||
let available={width:2880,height:1800};
|
||||
const stage={style:{},dataset:{}},sizer={style:{}};
|
||||
const c=context(['updateRuntimeScale','runtimeHasFixedHockeyCanvas'],{state:{config:{canvas:{width:1440,height:760},components:[{type:'hockey_penalty_dashboard'}]},activeTab:'main'},
|
||||
boot:{mode:'runtime'},el:{runtimeStage:stage,runtimeSizer:sizer,runtimeViewport:{classList:{toggle:noop}}},runtimeViewportSpace:()=>available,CSS:{supports:()=>true},hockeyRemoveRuntimeSideStack:noop});
|
||||
c.updateRuntimeScale();assert.equal(c.state.runtimeScale,1.6);assert.equal(stage.style.zoom,'1.6');
|
||||
c.state.activeTab='lines';c.updateRuntimeScale();assert.equal(c.state.runtimeScale,1.8);
|
||||
c.state.activeTab='main';available={width:720,height:400};c.updateRuntimeScale();assert.equal(c.state.runtimeScale,0.5);assert.equal(sizer.style.width,'720px');
|
||||
};
|
||||
cases.team_states = async () => {
|
||||
let allowed=true,live=true;const sent=[];
|
||||
const state={config:{shortcut_sequences:[]},data:{hockey:{game_control:{flags:{home_delayed_penalty:true},scoreboard_team_states:{home_delayed_penalty:{enabled:true,input_title:'DP',overlay:'8'}}}}},hockeyTeamStateOverlayActive:new Map(),vmixOverlayRuntime:new Map()};
|
||||
const c=context(['getByPath','hockeyMatchFlags','hockeyScoreboardTeamStateSettings','hockeyTeamStateSetting','hockeyTeamStateFlagSignature','hockeyScoreboardPrimaryOverlayTargets','hockeySyncTeamStateOverlays','normalizeRuntimeVmixInputRef','runtimeOverlayInputRefs','runtimeOverlayMatchesInput'],{state,hockeyCanControl:()=>allowed,
|
||||
hockeyTimerSelectedGameId:()=> 'g',currentRuntimeVmixDeviceId:()=> 'd',currentRuntimeHockeySessionToken:()=> 's',hockeyQueueTitleButtonAction:fn=>fn(),
|
||||
hockeyTeamStateScoreboardIsLive:()=>live,hockeyScoreboardIsLive:()=>live,hockeyGameControlLanguage:()=> 'ru',hockeyRuntimeVmixInputTitle:async ref=>ref,
|
||||
hockeyPenaltyOverlayFallbackTargets:()=>new Map(),hockeyRestorePenaltyOverlayLayers:async()=>0,
|
||||
sendRuntimeVmixSequence:async(commands,options)=>{assert.equal(options.isCurrent(),true);sent.push(...commands);for(const cmd of commands){if(cmd.Function.endsWith('In'))state.vmixOverlayRuntime.set('8',{input:cmd.Input});else state.vmixOverlayRuntime.delete('8');}return {ok:true};}});
|
||||
assert.equal(await c.hockeySyncTeamStateOverlays(),1);assert.deepEqual(sent.map(x=>x.Function),['OverlayInput8In']);
|
||||
assert.equal(await c.hockeySyncTeamStateOverlays(),0,'unchanged active state does not send again');
|
||||
state.data.hockey.game_control.flags.home_delayed_penalty=false;assert.equal(await c.hockeySyncTeamStateOverlays(),1);assert.equal(sent.at(-1).Function,'OverlayInput8Out');
|
||||
allowed=false;state.data.hockey.game_control.flags.home_delayed_penalty=true;assert.equal(await c.hockeySyncTeamStateOverlays(),0);assert.equal(sent.length,2);
|
||||
};
|
||||
|
||||
cases.quick_panel = async () => {
|
||||
const calls=[],control={dataset:{quickCommandButton:'stats'},classList:{add:noop,remove:noop},addEventListener(type,fn){this.click=fn;}};
|
||||
const sequence={id:'stats-sequence',enabled:true,steps:[{type:'vmix_command',function:'PreviewInput',input:'Team Stats'}]};
|
||||
const button={id:'stats',label:'Статистика',title_text:'Командная статистика',sequence_id:sequence.id,group_id:'main',mode:'momentary'};
|
||||
const selector={id:'period',button_id:'stats',group_id:'main',options:[{value:'2',label:'Второй период'}]};
|
||||
const state={config:{components:[{type:'hockey_penalty_dashboard'}]},quickPanelActiveTab:'main',titleButtonActionQueue:Promise.resolve()};
|
||||
const dock={classList:{add:noop,remove:noop},matches:()=>false,querySelector:()=>null,
|
||||
querySelectorAll:query=>query==='[data-quick-command-button]'?[control]:[]};
|
||||
let ack=defer(),saveOK=true;
|
||||
const c=context(['hockeyCommitQuickPanelButtonContext','hockeyQueueTitleButtonAction','renderHockeyQuickCommandDock'],{state,el:{runtimeButtonDock:dock},activeControlPopover:null,
|
||||
hockeyCanControl:()=>true,hockeyTimerSelectedGameId:()=> 'g',currentRuntimeVmixDeviceId:()=> 'd',
|
||||
hockeyQuickPanelTabs:()=>({tabs:[{id:'main',label:'Игра'}],buttons:[button],selectors:[selector]}),hockeyMatchFlags:()=>({}),shortcutSequenceIsOnAir:()=>false,
|
||||
hockeyScoreDockMarkup:()=>'',quickPanelSelectorMarkup:()=>'',quickPanelSelectorValue:()=> '2',quickPanelSelectorRuntimeOptions:item=>item.options,
|
||||
applyRuntimeUiPreferences:noop,refreshQuickPanelOnAirClasses:noop,scheduleStyledControls:noop,bindQuickPanelResizeHandle:noop,
|
||||
shortcutSequenceById:id=>id===sequence.id?sequence:null,
|
||||
hockeySetMatchValues:async(patch,options)=>{calls.push({kind:'save',patch,options});await ack.promise;return saveOK;},
|
||||
runShortcutSequence:async()=>{calls.push({kind:'sequence'});return true;},toast:noop});
|
||||
c.renderHockeyQuickCommandDock({force:true});
|
||||
let click=control.click({preventDefault:noop});await tick();assert.deepEqual(calls.map(x=>x.kind),['save']);
|
||||
assert.equal(calls[0].patch['panel.period.value'],'2');assert.equal(calls[0].patch['panel.period.label'],'Второй период');assert.equal(calls[0].patch['title_button.text'],'Командная статистика');
|
||||
assert.equal(calls[0].options.refreshMapping,false,'button-specific sequence resolves its own SQL; no full mapping round-trip');
|
||||
ack.resolve();await click;assert.deepEqual(calls.map(x=>x.kind),['save','sequence']);
|
||||
calls.length=0;ack=defer();saveOK=false;click=control.click({preventDefault:noop});await tick();ack.resolve();await click;
|
||||
assert.deepEqual(calls.map(x=>x.kind),['save'],'failed context persistence must not run the title sequence');
|
||||
};
|
||||
|
||||
cases.penalty_preview = async () => {
|
||||
const calls=[],pending=defer(),board={};let allowed=true,game='g';
|
||||
const c=context(['getByPath','hockeyPenaltyPlayerIdentifiers','hockeyPenaltyInfractionDbId','hockeySelectPenaltyForPreview','hockeyQueueTitleButtonAction'],{
|
||||
state:{data:{hockey:{selected_game:{home:{id:'home-team'}}}},titleButtonActionQueue:Promise.resolve()},ensureHockeyBoardState:()=>board,hockeyCanControl:()=>allowed,
|
||||
hockeyTimerSelectedGameId:()=>game,currentRuntimeVmixDeviceId:()=> 'd',currentRuntimeHockeySessionToken:()=> 's',hockeyEventReady:()=>true,refreshHockeyBoardNodes:noop,
|
||||
emitInteraction:(component,event,detail,options)=>{calls.push({kind:'emit',event,detail,options});return {action_id:'pen',event};},processTriggers:async()=>calls.push({kind:'trigger'}),
|
||||
fetch:async(url,opts)=>{calls.push({kind:'request',url,payload:JSON.parse(opts.body)});await pending.promise;return {ok:true};},toast:noop});
|
||||
const event={id:'penalty-1',side:'home',player:{externalId:'external',dbId:'42'},infraction:{id:'trip',db_id:'17'},preset:'2+2',remainingMs:240000,durationMs:240000};
|
||||
const result=c.hockeySelectPenaltyForPreview({},event);await tick();assert.deepEqual(calls.map(x=>x.kind),['request']);
|
||||
assert.equal(calls[0].payload.values.selected_penalty_preset_id,'17');assert.equal(calls[0].payload.values.selected_penalty_time_type,'2+2');assert.equal(calls[0].payload.values.selected_penalty_player_db_id,'42');
|
||||
pending.resolve();await result;assert.deepEqual(calls.map(x=>x.kind),['request','emit','trigger']);assert.equal(calls[1].options.runTriggers,false);assert.equal(c.state.hockeyPenaltyPreviewSelection,null);
|
||||
allowed=false;assert.equal(await c.hockeySelectPenaltyForPreview({},event),null);assert.equal(calls.length,3);
|
||||
};
|
||||
cases.side_context = async () => {
|
||||
const calls=[],selected={id:'manual',preset:'5',infraction:{db_id:'99'}},component={};let allowed=true;
|
||||
const event={id:'prepared',player:{externalId:'e',dbId:'42'},preset:'2',remainingMs:120000,teamPenalty:false};
|
||||
const c=context(['hockeyPenaltyPlayerIdentifiers','hockeyPenaltyInfractionDbId','hockeyPenaltySideMappingDetail','hockeySyncPenaltySideMappingContext'],{
|
||||
state:{data:{},hockeyPenaltyMappingContextSignature:''},hockeyCanControl:()=>allowed,hockeyTimerSelectedGameId:()=> 'g',currentRuntimeVmixDeviceId:()=> 'd',currentRuntimeHockeySessionToken:()=> 's',
|
||||
sortedPenaltyEntries:(side,options)=>{assert.equal(options.includePrepared,true);return side==='home'?[{component,event}]:[];},hockeyPenaltyBoardComponent:()=>component,selectedHockeyEvent:()=>selected,
|
||||
fetch:async(url,options)=>{calls.push(JSON.parse(options.body));return {ok:true,json:async()=>({ok:true})};}});
|
||||
assert.equal(await c.hockeySyncPenaltySideMappingContext(),true);const v=calls[0].values;
|
||||
assert.equal(v.active_home_penalty_id,'prepared');assert.equal(v.active_home_penalty_player_db_id,'42');assert.equal(v.active_away_penalty_id,'');
|
||||
assert.equal(v.selected_penalty_preset_id,'99');assert.equal(v.selected_penalty_time_type,'5');assert.equal('selected_home_penalty_id' in v,false);
|
||||
assert.equal(await c.hockeySyncPenaltySideMappingContext(),false,'identical source state is not re-saved');
|
||||
allowed=false;assert.equal(await c.hockeySyncPenaltySideMappingContext({force:true}),false);assert.equal(calls.length,1);
|
||||
};
|
||||
cases.prepared_tabs = async () => {
|
||||
const c=context(['ensureHockeyQuickCommandWorkspace','runtimeVisibleTabs','getByPath'],{state:{config:{tabs:[{id:'prepared_titles',label:'old'},{id:'prematch'}],components:[{type:'hockey_penalty_dashboard'},{type:'hockey_prematch_panel'}]},data:{},activeTab:'missing'}});
|
||||
c.ensureHockeyQuickCommandWorkspace();const ids=c.state.config.tabs.map(t=>t.id);
|
||||
assert.deepEqual(plain(ids.slice(-2)),['prepared_titles','khl_site']);assert.equal(ids.filter(id=>id==='prepared_titles').length,1);assert.equal(ids.includes('prematch'),false);assert.equal(c.state.activeTab,'main');
|
||||
const calls=[];const api=context(['hockeyGameControlRequest','hockeyLoadPreparedMappingSources','hockeyLoadPreparedTitlesWorkspace'],{
|
||||
state:{preparedTitleMappingSources:[],preparedTitlePanelId:'',preparedTitleSourceKey:'',preparedTitles:[],preparedTitleFieldValues:{}},
|
||||
hockeyPreparedWorkspaceKey:()=> 'd/g',currentRuntimeVmixDeviceId:()=> 'd',hockeyTimerSelectedGameId:()=> 'g',hockeyPreparedSelectedInput:()=>null,
|
||||
fetch:async(url)=>{calls.push(url);return {ok:true,json:async()=>({items:[],inventory:{inputs:[]}})};}});
|
||||
await api.hockeyLoadPreparedMappingSources('selected_player');
|
||||
await api.hockeyLoadPreparedTitlesWorkspace({force:true,render:false});
|
||||
assert.ok(calls.includes('/api/hockey/prepared-titles/mapping-sources?device_id=d&panel_id=selected_player'));
|
||||
assert.ok(calls.includes('/api/hockey/agents/vmix-inventory?device_id=d'));
|
||||
assert.ok(calls.includes('/api/hockey/prepared-titles?device_id=d&game_id=g'));
|
||||
assert.ok(calls.every(url=>!url.includes('/ui-builder/')&&!url.includes('/api/hockey/api/')));
|
||||
};
|
||||
cases.mapping_browser = async () => {
|
||||
const rawColumns=[{key:'name',label:'Имя',kind:'text'},{key:'other',label:'Другое',kind:'text'}];
|
||||
const rows=[{index:1,label:'First',values:{name:'Иван',other:'A'}},{index:2,label:'Second',values:{name:'Пётр',other:'B'}}];
|
||||
const items=[{key:'game.name',label:'Матч',category:'Матч',value:'A–B',kind:'text'},...rows.flatMap(r=>rawColumns.map(col=>({key:`players.row.${r.index}.${col.key}`,label:col.label,category:'Игроки',value:r.values[col.key],kind:'text',table_cell:true,source_code:'players'})))];
|
||||
const state={mappingCatalog:{context:{game_id:'g'},items,tables:[{code:'players',name:'Игроки',row_count:2,raw_columns:rawColumns,columns:rawColumns,rows}]},mappingTargetField:'',mappingOpenDataGroups:{},mappingSqlCellOpen:false,mappingSqlTableOpen:false,mappingTableRowSearch:'',mappingSelectedTableRow:1};
|
||||
const c=context(['mappingDataCatalog','mappingSourceByKey','mappingManualTableColumns','mappingDisplayValue','mappingCompatible','mappingFieldKind','mappingDataBrowser'],{state},'admin');
|
||||
let markup=c.mappingDataBrowser({fields:[]},{title:'Roster',fields:[]});
|
||||
const details=Array.from(markup.matchAll(/<details\b([^>]*)>/g),m=>m[1]);assert.equal(details.length,3);assert.ok(details.every(attrs=>!/(?:^|\s)open(?:\s|$)/.test(attrs)),'heavy data panels initially collapsed');
|
||||
assert.ok(markup.includes('players.row.1.name'));assert.ok(markup.includes('Иван'));assert.ok(markup.includes('data-map-table-row-pick="2"'));
|
||||
state.mappingSelectedTableRow=2;state.mappingOpenDataGroups['Матч']=true;state.mappingSqlTableOpen=true;
|
||||
markup=c.mappingDataBrowser({fields:[]},{title:'Roster',fields:[]});assert.ok(markup.includes('players.row.2.other'));assert.ok(markup.includes('Пётр'));assert.match(markup,/<details[^>]*data-map-data-group="Матч"[^>]*\sopen\s*>/);
|
||||
};
|
||||
cases.mapping_series = async () => {
|
||||
const fields=[1,2,3].map(n=>({name:`Name${n}.Text`,type:'text'}));fields.push({name:'Photo1.Source',type:'image'});
|
||||
const input={title:'Roster',fields};const profile={fields:[{vmix_input_title:'Roster',vmix_field:'Name1.Text',data_key:'players.row.1.name'}]};
|
||||
const state={mappingCatalog:{context:{game_id:'g'},items:[1,2,3].map(n=>({key:`players.row.${n}.name`,kind:'text',value:`P${n}`}))}};
|
||||
const c=context(['mappingEscapeRegExp','mappingFieldSequence','mappingParseTableCellKey','mappingRowMatchesInput','mappingRowForField','mappingDataCatalog','mappingSourceByKey','mappingFieldKind','mappingCompatible','mappingSeriesPlan'],{state},'admin');
|
||||
const plan=c.mappingSeriesPlan(profile,input,'Name1.Text');assert.deepEqual(plain(plan.links.map(x=>[x.field.name,x.source.key])),[[1,1],[2,2],[3,3]].map(([a,b])=>[`Name${a}.Text`,`players.row.${b}.name`]));
|
||||
assert.deepEqual(plain(c.mappingSeriesPlan(profile,input,'Photo1.Source').links),[],'unlinked image is not an accidental continuation');
|
||||
};
|
||||
cases.khl_gate = async () => {
|
||||
let level='khl',rendered='';
|
||||
const c=context(['isKhlTournamentSelected','renderKhlSite'],{state:{section:'khl_site'},selectedContext:()=>({tournamentLevel:level,tournamentId:'1437',tournament:{name:'КХЛ'}}),
|
||||
ensureModal:()=>({set innerHTML(value){rendered=value;}}),shellMarkup:content=>content,bindShell:noop,renderTeams:()=>{rendered='teams';}},'admin');
|
||||
c.renderKhlSite();assert.match(rendered,/<iframe[^>]*src="\/khl-site\/"/);level='vhl';c.renderKhlSite();assert.equal(rendered,'teams');assert.equal(c.state.section,'teams');
|
||||
};
|
||||
cases.roster = async () => {
|
||||
const calls=[],cached=defer(),enriched=defer();let data={hockey:{home:{players:[{id:'previous-game-player'}]}}};
|
||||
const game={external_id:'new-game',tournament_external_id:'t',home:{name:'New home'},away:{name:'New away'}};
|
||||
const state={selectedId:'t',language:'ru',gameOpenGeneration:0,gameOpenBusy:false,view:'games',selectedGameId:'old-game',selectedGame:{external_id:'old-game'}};
|
||||
const storage={game:'game',session:'session',tournament:'tournament',vmixDevice:'device',gameDate:'date'};
|
||||
const c=context(['openGame','enrichOpenedGame','clearRuntimeMatchSpecificData','cachedMatchHasRosters'],{state,storage,runtimeStorage:{getItem:()=>'',setItem:noop,removeItem:noop},
|
||||
t:x=>x,matchLabelById:()=> 'New game',gameById:id=>id==='new-game'?game:null,currentAgentDeviceId:()=> 'd',stopSelectedGamePolling:()=>calls.push('stop'),
|
||||
setMatchLoading:noop,updateMatchLoading:noop,renderSelectedChip:noop,renderGames:noop,setOpen:noop,notify:noop,applyTournamentData:noop,
|
||||
applyGameData:()=>calls.push('apply:'+state.selectedGame.external_id),startSelectedGamePolling:()=>calls.push('poll'),
|
||||
refreshSessionAgentMapping:async session=>{calls.push('mapping:'+session.token);return {ok:true};},ensureSessionAgentAssignment:async()=>null,
|
||||
loadTournamentStandings:async()=>{},loadGames:async()=>{},
|
||||
window:{HockeyMatchAccess:{beforeGameChange:async()=>{},selectGame:async()=>{},finishOpening:noop},UIBuilderRuntime:{patchData:patch=>{data={...data,hockey:{...data.hockey,...patch.hockey}};calls.push('clear');}}},
|
||||
request:async(url,options)=>{calls.push(url);if(url.includes('/details?'))return cached.promise;if(url.includes('/details/sync'))return enriched.promise;if(url==='/api/hockey/sessions')return {token:'new-session',agent_assignment:{delivered:true}};throw Error('Unexpected request '+url);}},'menu');
|
||||
await c.openGame('new-game');await tick();
|
||||
assert.equal(state.selectedGameId,'new-game');assert.equal(state.gameOpenBusy,false);assert.equal(data.hockey.home,null,'old roster cleared immediately');
|
||||
assert.ok(calls.indexOf('clear')<calls.indexOf('apply:new-game'));assert.ok(calls.includes('poll'));assert.ok(calls.includes('mapping:new-session'),'mapping starts without waiting for optional remote roster');
|
||||
assert.ok(calls.some(x=>x.includes('/games/new-game/details?')));assert.ok(!calls.some(x=>x.includes('/games/old-game/details')));
|
||||
assert.equal(c.cachedMatchHasRosters({game:{home:{players:[{id:'p'}]}},details:{loaded:true}}),true);assert.equal(c.cachedMatchHasRosters({game:{home:{players:[{id:'p'}]}},details:{loaded:false}}),false);
|
||||
state.selectedGameId='later-game';state.gameOpenGeneration+=1;cached.resolve({game:{external_id:'stale-cache'}});enriched.resolve({game:{external_id:'stale-remote'},details:{loaded:true}});await tick();
|
||||
assert.equal(state.selectedGame.external_id,'new-game','late responses cannot replace the next match selection');
|
||||
};
|
||||
(async()=>{const name=process.argv[2];assert.equal(typeof cases[name],'function','Unknown UI contract '+name);await cases[name]();console.log('PASS UI contract: '+name);})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
@@ -5010,7 +5010,7 @@ function startCustomTooltips() {
|
||||
const rawCommands = typeof commands === "function" ? commands() : commands;
|
||||
const clean = (rawCommands || []).map(compactVmixCommand).filter((command) => command.Function);
|
||||
if (!clean.length) return Promise.resolve({ ok: true, applied: 0, requested: 0, results: [] });
|
||||
|
||||
const deviceId = currentRuntimeVmixDeviceId();
|
||||
const penaltyInputs = new Set(clean.map((command) => String(command.Input || "")));
|
||||
const penaltyAssignments = Array.from(state.vmixPenaltyTargetAssignments.entries())
|
||||
.filter(([, value]) => penaltyInputs.has(String(value.input || "")));
|
||||
@@ -5021,6 +5021,13 @@ function startCustomTooltips() {
|
||||
}
|
||||
};
|
||||
|
||||
// An empty selection must not use an old session Agent or confirm an unsent penalty target.
|
||||
if (!deviceId) {
|
||||
forgetFailedPenaltyAssignments();
|
||||
console.warn("vMix timer sync skipped: select an Agent in this browser");
|
||||
return Promise.resolve({ ok: false, skipped: true, reason: "device_selection_required", applied: 0, requested: clean.length, results: [], error: "Выберите Agent в этом браузере" });
|
||||
}
|
||||
|
||||
const request = fetch("/api/hockey/vmix/sequence", {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
@@ -5031,7 +5038,7 @@ function startCustomTooltips() {
|
||||
// but BUILD106 uses ordered single WebSocket frames rather than vmix.batch.
|
||||
body: JSON.stringify({
|
||||
commands: clean,
|
||||
device_id: currentRuntimeVmixDeviceId(),
|
||||
device_id: deviceId,
|
||||
session_token: currentRuntimeHockeySessionToken(),
|
||||
delivery_mode: "timer-fast-ordered",
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user