-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_normalize.py
More file actions
1565 lines (1318 loc) · 49.4 KB
/
Copy pathtest_normalize.py
File metadata and controls
1565 lines (1318 loc) · 49.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import csv
import json
import subprocess
import sys
import threading
from pathlib import Path, PureWindowsPath
import pytest
from normalize_test_helpers import FakeHandler, FakeProfile, write_analysis_csv
from matchpatch import normalize, workflow
from matchpatch.devices.base import (
DeviceTargetId,
MeasurementTarget,
SubdivisionSelection,
TargetSelection,
)
from matchpatch.workflow import NormalizationRequest, export_adjusted_file, normalize_presets
def test_count_csv_rows_handles_header(tmp_path) -> None:
csv_path = tmp_path / "results.csv"
csv_path.write_text("Preset,DevicePatch\n1,patch-1\n2,patch-2\n", encoding="utf-8")
assert normalize.count_csv_rows(csv_path) == 2
def test_snapshot_plan_serializes_for_native_worker() -> None:
assert normalize._format_snapshot_plan((("02B", (1, 3)), ("02C", (2,)))) == ("02B=1,3;02C=2")
def test_normalize_presets_filters_to_diff_input(tmp_path) -> None:
handler = FakeHandler()
input_path = tmp_path / "input.hls"
previous_path = tmp_path / "previous.hls"
output_path = tmp_path / "output.hls"
reference = tmp_path / "reference.wav"
work_dir = tmp_path / "work"
input_path.touch()
previous_path.touch()
reference.touch()
work_dir.mkdir()
measured = []
def fake_analysis(request, preset_ids, csv_path, callback):
measured.append(preset_ids)
write_analysis_csv(request, preset_ids, csv_path)
normalize_presets(
NormalizationRequest(
device="fake",
input_path=input_path,
output_path=output_path,
diff_input_path=previous_path,
backend="loopback",
windows_python="python.exe",
reference_di=reference,
automation=False,
),
run_analysis=fake_analysis,
get_profile=lambda device: FakeProfile(handler),
make_temp_dir=lambda: work_dir,
)
assert measured == [[2]]
def test_normalize_presets_filters_diff_input_snapshot_wise(tmp_path) -> None:
class SnapshotDiffHandler(FakeHandler):
def diff_snapshot_ids(self, input_path, previous_input_path, snapshot_count):
return {1: (2,), 2: (1, 3)}
handler = SnapshotDiffHandler()
input_path = tmp_path / "input.hls"
previous_path = tmp_path / "previous.hls"
output_path = tmp_path / "output.hls"
reference = tmp_path / "reference.wav"
work_dir = tmp_path / "work"
input_path.touch()
previous_path.touch()
reference.touch()
work_dir.mkdir()
requests = []
def fake_analysis(request, preset_ids, csv_path, callback):
requests.append((request, preset_ids))
write_analysis_csv(request, preset_ids, csv_path)
normalize_presets(
NormalizationRequest(
device="fake",
input_path=input_path,
output_path=output_path,
diff_input_path=previous_path,
backend="loopback",
windows_python="python.exe",
reference_di=reference,
automation=False,
snapshot_plan=(("patch-1", (1, 2)), ("patch-2", (3,))),
policy=workflow.NormalizationPolicy(snapshot_count=3),
),
run_analysis=fake_analysis,
get_profile=lambda device: FakeProfile(handler),
make_temp_dir=lambda: work_dir,
)
assert requests[0][1] == [1, 2]
assert requests[0][0].snapshot_plan == (("patch-1", (2,)), ("patch-2", (3,)))
def test_normalize_presets_diff_filter_uses_target_api_with_string_ids(tmp_path) -> None:
class StringTargetDiffHandler(FakeHandler):
def parse_target_set(self, value: str) -> list[DeviceTargetId]:
return [token.strip() for token in value.split(",") if token.strip()]
def list_targets(self, input_path: Path) -> list[MeasurementTarget]:
return [
MeasurementTarget(
id="scene:clean",
display_label="Clean Scene",
index=0,
name="Clean",
compat_numeric_id=1,
),
MeasurementTarget(
id="scene:lead",
display_label="Lead Scene",
index=1,
name="Lead",
compat_numeric_id=2,
),
]
def select_targets(
self,
input_path: Path,
targets: list[MeasurementTarget],
requested_ids: list[DeviceTargetId] | None,
) -> list[TargetSelection]:
requested = set(requested_ids or [target.id for target in targets])
return [
TargetSelection(
id=target.id,
display_label=target.display_label,
index=target.index,
name=target.name,
compat_numeric_id=target.compat_numeric_id,
)
for target in targets
if target.id in requested
]
def diff_subdivisions(
self,
input_path: Path,
previous_input_path: Path,
subdivision_count: int,
) -> dict[DeviceTargetId, tuple[SubdivisionSelection, ...]]:
return {
"scene:lead": (
SubdivisionSelection(
target_id="scene:lead",
id="snapshot:solo",
display_label="Solo",
index=1,
),
)
}
handler = StringTargetDiffHandler()
input_path = tmp_path / "input.scene"
previous_path = tmp_path / "previous.scene"
output_path = tmp_path / "output.scene"
reference = tmp_path / "reference.wav"
work_dir = tmp_path / "work"
input_path.touch()
previous_path.touch()
reference.touch()
work_dir.mkdir()
requests = []
def fake_analysis(request, preset_ids, csv_path, callback):
requests.append((request, preset_ids))
write_analysis_csv(request, preset_ids, csv_path)
normalize_presets(
NormalizationRequest(
device="fake",
input_path=input_path,
output_path=output_path,
diff_input_path=previous_path,
backend="loopback",
windows_python="python.exe",
reference_di=reference,
automation=False,
preset_set="scene:clean,scene:lead",
snapshot_plan=(("Lead Scene", (1, 2)),),
policy=workflow.NormalizationPolicy(snapshot_count=2),
),
run_analysis=fake_analysis,
get_profile=lambda device: FakeProfile(handler),
make_temp_dir=lambda: work_dir,
)
assert requests[0][1] == [2]
assert requests[0][0].snapshot_plan == (("Lead Scene", (2,)),)
def test_normalize_presets_default_temp_dir_uses_normalization_prefix(
tmp_path, monkeypatch
) -> None:
handler = FakeHandler()
input_path = tmp_path / "input.hls"
output_path = tmp_path / "output.hls"
reference = tmp_path / "reference.wav"
work_dir = tmp_path / "matchpatch_normalization_test"
input_path.touch()
reference.touch()
mkdtemp_kwargs = {}
def fake_mkdtemp(**kwargs):
mkdtemp_kwargs.update(kwargs)
work_dir.mkdir()
return str(work_dir)
def fake_analysis(request, preset_ids, csv_path, callback):
write_analysis_csv(request, preset_ids, csv_path)
monkeypatch.setattr(workflow.tempfile, "mkdtemp", fake_mkdtemp)
normalize_presets(
NormalizationRequest(
device="fake",
input_path=input_path,
output_path=output_path,
backend="loopback",
windows_python="python.exe",
reference_di=reference,
automation=False,
),
run_analysis=fake_analysis,
get_profile=lambda device: FakeProfile(handler),
)
assert mkdtemp_kwargs["prefix"] == "matchpatch_normalization_"
assert "dir" not in mkdtemp_kwargs
def test_request_from_args_includes_diff_input() -> None:
args = normalize.apply_config(
normalize.parse_args(
[
"--device",
"helix",
"-i",
"current.hls",
"--diff-input",
"previous.hls",
]
)
)
assert normalize.request_from_args(args).diff_input_path == Path("previous.hls")
def test_subprocess_helpers_delegate_and_translate_paths(tmp_path, monkeypatch) -> None:
calls = []
completed = subprocess.CompletedProcess([], 0, stdout="C:\\MatchPatch\\file.hls\n")
monkeypatch.setattr(
subprocess,
"run",
lambda *args, **kwargs: calls.append((args, kwargs)) or completed,
)
normalize.run_command(["tool", Path("input.hls")], timeout=3)
assert calls[0] == ((["tool", "input.hls"],), {"check": True, "text": True, "timeout": 3})
if normalize._is_windows():
assert normalize.wsl_path_to_windows(tmp_path / "file.hls") == str(tmp_path / "file.hls")
assert len(calls) == 1
else:
assert normalize.wsl_path_to_windows(tmp_path / "file.hls") == "C:\\MatchPatch\\file.hls"
assert calls[1][0][0][0:2] == ["wslpath", "-w"]
def test_wait_for_user_confirmation_prompts(monkeypatch, capsys) -> None:
prompts = []
monkeypatch.setattr("builtins.input", lambda prompt: prompts.append(prompt))
normalize.wait_for_user_confirmation("Import the patch")
assert "Import the patch" in capsys.readouterr().out
assert prompts == ["Press Enter to continue..."]
def test_apply_config_layers_cli_environment_and_toml(tmp_path, monkeypatch) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text(
"""
[normalize]
backend = "hardware"
reference_di = "configured.wav"
custom_adjustments_file = "configured-custom.csv"
target_lufs = -18.0
timeout_seconds = 90
ignore_bad_lufs = true
[devices.helix.audio]
device = "Configured Audio"
sample_rate = 44100
input_mapping = [3, 4]
output_mapping = [5, 6]
blocksize = 128
[devices.helix.steering]
output = "Configured MIDI"
channel = 2
preset_wait_seconds = 0.8
snapshot_wait_seconds = 0.1
measurement_wait_seconds = 0.7
[policy]
measured_snapshots = 3
solo_marker = "lead"
ignore_snapshot_regex = "^Init$"
ignore_preset_regex = "^Empty"
solo_gain_bump_db = 4.0
crest_factor_reference_db = 11.0
crest_factor_correction_ratio = 0.5
max_crest_factor_correction_db = 2.0
gain_deadband_db = 0.1
[analysis]
window_seconds = 2.0
interval_seconds = 0.2
minimum_valid_lufs = -90.0
pre_roll_seconds = 1.5
post_roll_seconds = 2.0
round_trip_latency_seconds = 0.03
""",
encoding="utf-8",
)
monkeypatch.setenv("MATCHPATCH_BACKEND", "loopback")
monkeypatch.setenv("MATCHPATCH_REFERENCE_DI", "environment.wav")
args = normalize.apply_config(
normalize.parse_args(
[
"--config",
str(config_path),
"--device",
"helix",
"-i",
"input.hls",
"--target-lufs",
"-17",
"--audio-device",
"CLI Audio",
]
)
)
assert args.backend == "loopback"
assert args.reference_di == "environment.wav"
assert args.custom_adjustments_file == "configured-custom.csv"
assert args.target_lufs == -17
assert args.audio_device == "CLI Audio"
assert args.input_mapping == "3,4"
assert args.output_mapping == "5,6"
assert args.blocksize == 128
assert args.steering_output == "Configured MIDI"
assert args.device_settings["audio_device"] == "CLI Audio"
assert args.device_settings["input_mapping"] == (3, 4)
assert args.device_settings["midi_output"] == "Configured MIDI"
assert args.policy.snapshot_count == 3
assert args.policy.solo_regex == "lead"
assert args.policy.ignore_snapshot_regex == "^Init$"
assert args.policy.ignore_preset_regex == "^Empty"
assert args.analysis_options.window_seconds == 2.0
assert args.pre_roll == 1.5
assert args.post_roll == 2.0
assert args.round_trip_latency == 0.03
def test_apply_config_rejects_invalid_snapshot_count(tmp_path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text("[policy]\nmeasured_snapshots = 0\n", encoding="utf-8")
with pytest.raises(ValueError, match="at least 1"):
normalize.apply_config(
normalize.parse_args(
["--config", str(config_path), "--device", "helix", "-i", "input.hls"]
)
)
def test_apply_config_cli_snapshot_count_overrides_toml(tmp_path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text("[policy]\nmeasured_snapshots = 3\n", encoding="utf-8")
args = normalize.apply_config(
normalize.parse_args(
[
"--config",
str(config_path),
"--device",
"helix",
"-i",
"input.hls",
"--snapshot-count",
"6",
]
)
)
assert args.policy.snapshot_count == 6
def test_apply_config_uses_device_timing_defaults_when_config_is_silent() -> None:
args = normalize.apply_config(normalize.parse_args(["--device", "helix", "-i", "input.hls"]))
assert args.audio_device == "Helix"
assert args.sample_rate == 48000
assert args.input_mapping == "1,2"
assert args.output_mapping == "3,4"
assert args.preset_wait == 0.5
assert args.snapshot_wait == 0.2
assert args.measurement_wait == 0.1
assert args.device_settings["sample_rate"] == 48000
assert args.device_settings["midi_channel"] == 1
def test_apply_config_validates_backend_against_selected_profile(monkeypatch) -> None:
class OfflineProfile(FakeProfile):
display_name = "Offline Processor"
def measurement_backends(self) -> tuple[str, ...]:
return ("offline",)
monkeypatch.setattr(
normalize, "get_device_profile", lambda device: OfflineProfile(FakeHandler())
)
args = normalize.apply_config(
normalize.parse_args(["--device", "fake", "-i", "input.hls", "--backend", "offline"])
)
assert args.backend == "offline"
with pytest.raises(ValueError, match="Backend 'hardware' is not supported"):
normalize.apply_config(
normalize.parse_args(["--device", "fake", "-i", "input.hls", "--backend", "hardware"])
)
def test_configured_windows_python_frozen_windows_ignores_stale_worker_config(
tmp_path, monkeypatch
) -> None:
bundled_executable = tmp_path / "MatchPatch.exe"
config = {"normalize": {"windows_python": "C:/source/.venv-windows/Scripts/python.exe"}}
args = argparse.Namespace(windows_python=None)
monkeypatch.setattr(sys, "frozen", True, raising=False)
monkeypatch.setattr(normalize.os, "name", "nt")
monkeypatch.setattr(normalize, "DEFAULT_WINDOWS_PYTHON", bundled_executable)
assert normalize._configured_windows_python(args, config) == str(bundled_executable)
def test_configured_windows_python_frozen_windows_keeps_explicit_worker_overrides(
tmp_path, monkeypatch
) -> None:
bundled_executable = tmp_path / "MatchPatch.exe"
config = {"normalize": {"windows_python": "C:/source/.venv-windows/Scripts/python.exe"}}
monkeypatch.setattr(sys, "frozen", True, raising=False)
monkeypatch.setattr(normalize.os, "name", "nt")
monkeypatch.setattr(normalize, "DEFAULT_WINDOWS_PYTHON", bundled_executable)
cli_args = argparse.Namespace(windows_python="C:/custom/python.exe")
env_args = argparse.Namespace(windows_python=None)
monkeypatch.setenv("MATCHPATCH_WINDOWS_PYTHON", "C:/env/python.exe")
assert normalize._configured_windows_python(cli_args, config) == "C:/custom/python.exe"
assert normalize._configured_windows_python(env_args, config) == "C:/env/python.exe"
def test_apply_config_rejects_snapshot_count_above_device_limit() -> None:
with pytest.raises(ValueError, match="must not exceed 8"):
normalize.apply_config(
normalize.parse_args(["--device", "helix", "-i", "input.hls", "--snapshot-count", "9"])
)
def test_apply_config_rejects_invalid_solo_regex(tmp_path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text("[policy]\nsolo_regex = '('\n", encoding="utf-8")
with pytest.raises(ValueError, match="Invalid solo snapshot regex"):
normalize.apply_config(
normalize.parse_args(
["--config", str(config_path), "--device", "helix", "-i", "input.hls"]
)
)
def test_apply_config_preserves_double_quoted_word_boundary_regex(tmp_path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text('[policy]\nsolo_regex = "(?i)\\bsolo\\b"\n', encoding="utf-8")
args = normalize.apply_config(
normalize.parse_args(["--config", str(config_path), "--device", "helix", "-i", "input.hls"])
)
assert args.policy.solo_regex == r"(?i)\bsolo\b"
def test_apply_config_rejects_invalid_ignore_snapshot_regex(tmp_path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text("[policy]\nignore_snapshot_regex = '('\n", encoding="utf-8")
with pytest.raises(ValueError, match="Invalid ignore snapshot regex"):
normalize.apply_config(
normalize.parse_args(
["--config", str(config_path), "--device", "helix", "-i", "input.hls"]
)
)
def test_apply_config_cli_hide_preset_regex_overrides_toml(tmp_path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text(
"[devices.helix.policy]\nhide_preset_regex = '^Empty$'\n",
encoding="utf-8",
)
args = normalize.apply_config(
normalize.parse_args(
[
"--config",
str(config_path),
"--device",
"helix",
"-i",
"input.hls",
"--hide-preset-regex",
"^Init",
]
)
)
assert args.policy.ignore_preset_regex == "^Init"
def test_apply_config_reads_device_hide_preset_regex(tmp_path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text(
"[devices.podgo.policy]\nhide_preset_regex = '^Factory$'\n",
encoding="utf-8",
)
args = normalize.apply_config(
normalize.parse_args(["--config", str(config_path), "--device", "podgo", "-i", "input.pgs"])
)
assert args.policy.ignore_preset_regex == "^Factory$"
@pytest.mark.parametrize(
("device", "input_path", "expected"),
[
("helix", "input.hls", ""),
("podgo", "input.pgs", r"(?i)^New Preset$"),
],
)
def test_apply_config_uses_device_hide_preset_regex_default(
tmp_path, device, input_path, expected
) -> None:
config_path = tmp_path / "empty.toml"
config_path.write_text("", encoding="utf-8")
args = normalize.apply_config(
normalize.parse_args(["--config", str(config_path), "--device", device, "-i", input_path])
)
assert args.policy.ignore_preset_regex == expected
def test_apply_config_accepts_legacy_ignore_preset_regex_config(tmp_path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text("[policy]\nignore_preset_regex = '^Empty$'\n", encoding="utf-8")
args = normalize.apply_config(
normalize.parse_args(["--config", str(config_path), "--device", "podgo", "-i", "input.pgs"])
)
assert args.policy.ignore_preset_regex == "^Empty$"
def test_apply_config_rejects_invalid_hide_preset_regex(tmp_path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text("[devices.helix.policy]\nhide_preset_regex = '('\n", encoding="utf-8")
with pytest.raises(ValueError, match="Invalid ignore preset regex"):
normalize.apply_config(
normalize.parse_args(
["--config", str(config_path), "--device", "helix", "-i", "input.hls"]
)
)
def test_wsl_path_to_windows_returns_native_windows_path(monkeypatch) -> None:
monkeypatch.setattr(normalize, "_is_windows", lambda: True)
monkeypatch.setattr(
normalize.subprocess,
"run",
lambda *args, **kwargs: pytest.fail("native Windows should not call wslpath"),
)
assert PureWindowsPath(normalize.wsl_path_to_windows(Path("C:/MatchPatch/results.csv"))) == (
PureWindowsPath("C:/MatchPatch/results.csv")
)
def test_wsl_path_to_windows_keeps_drive_path_on_wsl(monkeypatch) -> None:
monkeypatch.setattr(normalize, "_is_windows", lambda: False)
monkeypatch.setattr(
normalize.subprocess,
"run",
lambda *args, **kwargs: pytest.fail("Windows-style paths should not call wslpath"),
)
assert PureWindowsPath(normalize.wsl_path_to_windows(Path("C:/MatchPatch/results.csv"))) == (
PureWindowsPath("C:/MatchPatch/results.csv")
)
def test_run_windows_analysis_builds_worker_command(tmp_path, monkeypatch) -> None:
windows_python = tmp_path / "python.exe"
windows_python.touch()
csv_path = tmp_path / "results.csv"
reference = tmp_path / "reference.wav"
args = argparse.Namespace(
windows_python=str(windows_python),
device="helix",
backend="loopback",
reference_di=str(reference),
audio_device="Helix",
steering_output=None,
steering_channel=2,
sample_rate=None,
input_mapping="1,2",
output_mapping=None,
simulate_fail_presets="6,7",
pre_roll=1.5,
post_roll=2.0,
round_trip_latency=0.03,
timeout=12.0,
)
calls = []
monkeypatch.setattr(normalize, "wsl_path_to_windows", lambda path: f"WIN:{path.name}")
monkeypatch.setattr(
normalize, "run_command", lambda command, timeout=None: calls.append((command, timeout))
)
normalize.run_windows_analysis(args, [1, 6], csv_path)
command, timeout = calls[0]
assert command[:5] == [
windows_python.resolve(),
"-m",
"matchpatch.measure",
"measure",
"--device",
]
assert "1,6" in command
audio_index = command.index("--audio-device")
assert command[audio_index : audio_index + 2] == ["--audio-device", "Helix"]
failure_index = command.index("--simulate-fail-presets")
assert command[failure_index : failure_index + 2] == ["--simulate-fail-presets", "6,7"]
assert command[command.index("--pre-roll") : command.index("--pre-roll") + 2] == [
"--pre-roll",
1.5,
]
assert command[
command.index("--round-trip-latency") : command.index("--round-trip-latency") + 2
] == ["--round-trip-latency", 0.03]
assert timeout == 12.0
def test_run_windows_analysis_uses_installed_app_worker_command(tmp_path, monkeypatch) -> None:
matchpatch_exe = tmp_path / "MatchPatch.exe"
matchpatch_exe.touch()
csv_path = tmp_path / "results.csv"
reference = tmp_path / "reference.wav"
args = argparse.Namespace(
windows_python=str(matchpatch_exe),
device="helix",
backend="loopback",
reference_di=str(reference),
audio_device=None,
steering_output=None,
steering_channel=None,
sample_rate=None,
input_mapping=None,
output_mapping=None,
simulate_fail_presets=None,
pre_roll=None,
post_roll=None,
round_trip_latency=None,
timeout=None,
)
calls = []
monkeypatch.setattr(normalize, "wsl_path_to_windows", lambda path: f"WIN:{path.name}")
monkeypatch.setattr(
normalize, "run_command", lambda command, timeout=None: calls.append((command, timeout))
)
normalize.run_windows_analysis(args, [1], csv_path)
command, _timeout = calls[0]
assert command[:5] == [
matchpatch_exe.resolve(),
"--cli",
"measure",
"measure",
"--device",
]
def test_run_windows_optimization_builds_pinned_parameter_command(tmp_path, monkeypatch) -> None:
windows_python = tmp_path / "python.exe"
windows_python.touch()
reference = tmp_path / "reference.wav"
args = argparse.Namespace(
windows_python=str(windows_python),
device="helix",
backend="loopback",
reference_di=str(reference),
audio_device=None,
steering_output=None,
steering_channel=None,
sample_rate=None,
input_mapping=None,
output_mapping=None,
simulate_fail_presets=None,
blocksize=None,
preset_wait=0.5,
snapshot_wait=0.2,
measurement_wait=0.1,
pre_roll=0.2,
post_roll=0.1,
round_trip_latency=0.02,
analysis_options=normalize.AnalysisOptions(),
timeout=12.0,
)
calls = []
class Completed:
stdout = "done\n"
monkeypatch.setattr(normalize, "wsl_path_to_windows", lambda path: f"WIN:{path.name}")
monkeypatch.setattr(
normalize.subprocess,
"run",
lambda command, **kwargs: calls.append((command, kwargs)) or Completed(),
)
result = normalize.run_windows_optimization(
args,
7,
stability_runs=4,
termination_tolerance=12.5,
stability_tolerance=0.25,
pinned_parameters=("pre_roll", "measurement_wait"),
)
command, kwargs = calls[0]
assert result == "done"
assert command[:5] == [
str(windows_python.resolve()),
"-m",
"matchpatch.measure",
"optimize",
"--device",
]
assert command[command.index("--preset-id") : command.index("--preset-id") + 2] == [
"--preset-id",
"7",
]
assert command.count("--pinned-parameter") == 2
assert command[
command.index("--pinned-parameter") : command.index("--pinned-parameter") + 4
] == ["--pinned-parameter", "pre_roll", "--pinned-parameter", "measurement_wait"]
assert kwargs["timeout"] == 12.0
def test_check_windows_hardware_uses_installed_app_worker_command(tmp_path, monkeypatch) -> None:
matchpatch_exe = tmp_path / "MatchPatch.exe"
matchpatch_exe.touch()
args = argparse.Namespace(
windows_python=str(matchpatch_exe),
device="helix",
audio_device=None,
steering_output=None,
steering_channel=None,
sample_rate=None,
input_mapping=None,
output_mapping=None,
blocksize=None,
preset_wait=None,
snapshot_wait=None,
measurement_wait=None,
timeout=5,
)
calls = []
monkeypatch.setattr(
normalize.subprocess,
"run",
lambda command, **kwargs: (
calls.append((command, kwargs))
or subprocess.CompletedProcess(command, 0, stdout="", stderr="")
),
)
normalize.check_windows_hardware(args)
command, kwargs = calls[0]
assert command[:5] == [
str(matchpatch_exe.resolve()),
"--cli",
"measure",
"check-hardware",
"--device",
]
assert kwargs["timeout"] == 5
assert command[-1] == "--diagnostics-json"
def test_frozen_windows_default_worker_is_current_executable(monkeypatch, tmp_path) -> None:
matchpatch_exe = tmp_path / "MatchPatch.exe"
monkeypatch.setattr(sys, "frozen", True, raising=False)
monkeypatch.setattr(sys, "executable", str(matchpatch_exe))
monkeypatch.setattr(normalize.os, "name", "nt")
assert str(normalize._default_windows_python()).replace("\\", "/") == str(
matchpatch_exe
).replace("\\", "/")
def test_run_windows_analysis_reports_missing_environment(tmp_path) -> None:
args = argparse.Namespace(windows_python=str(tmp_path / "missing.exe"))
with pytest.raises(RuntimeError, match="sync-windows"):
normalize.run_windows_analysis(args, [1], tmp_path / "results.csv")
def test_run_windows_analysis_reports_native_windows_sync_command(tmp_path, monkeypatch) -> None:
monkeypatch.setattr(normalize, "_is_windows", lambda: True)
args = argparse.Namespace(windows_python=str(tmp_path / "missing.exe"))
with pytest.raises(RuntimeError, match=r"scripts\\sync-windows\.cmd"):
normalize.run_windows_analysis(args, [1], tmp_path / "results.csv")
def test_check_windows_hardware_builds_worker_command(tmp_path, monkeypatch) -> None:
windows_python = tmp_path / "python.exe"
windows_python.touch()
args = argparse.Namespace(
windows_python=str(windows_python),
device="helix",
audio_device="Helix",
steering_output="Helix MIDI",
steering_channel=2,
sample_rate=48000,
input_mapping="1,2",
output_mapping="3,4",
blocksize=128,
preset_wait=None,
snapshot_wait=None,
measurement_wait=None,
timeout=5,
)
calls = []
monkeypatch.setattr(
normalize.subprocess,
"run",
lambda command, **kwargs: (
calls.append((command, kwargs))
or subprocess.CompletedProcess(command, 0, stdout="", stderr="")
),
)
normalize.check_windows_hardware(args)
command, kwargs = calls[0]
assert command[:5] == [
str(windows_python.resolve()),
"-m",
"matchpatch.measure",
"check-hardware",
"--device",
]
assert command[command.index("--audio-device") : command.index("--audio-device") + 2] == [
"--audio-device",
"Helix",
]
assert command[command.index("--steering-output") : command.index("--steering-output") + 2] == [
"--steering-output",
"Helix MIDI",
]
assert command[command.index("--output-mapping") : command.index("--output-mapping") + 2] == [
"--output-mapping",
"3,4",
]
assert kwargs["timeout"] == 5
assert kwargs["stdout"] == subprocess.PIPE
assert kwargs["stderr"] == subprocess.PIPE
assert command[-1] == "--diagnostics-json"
def test_collect_windows_hardware_preflight_parses_failed_json(tmp_path, monkeypatch) -> None:
windows_python = tmp_path / "python.exe"
windows_python.touch()
args = argparse.Namespace(
windows_python=str(windows_python),
device="helix",
audio_device="Helix",
steering_output="Missing",
steering_channel=None,
sample_rate=48000,
input_mapping="1,2",
output_mapping="3,4",
blocksize=0,
preset_wait=None,
snapshot_wait=None,
measurement_wait=None,
timeout=5,
)
calls = []
payload = {
"device": "helix",
"backend": "hardware",
"ok": False,
"checks": [
{
"name": "audio_device",
"status": "ok",
"message": "Audio device is available",
"details": {"device": 2},
},
{
"name": "midi_output",
"status": "failed",
"message": "MIDI output query 'Missing' matched 0 ports",
"details": {"query": "Missing"},
},
],
}
monkeypatch.setattr(
normalize.subprocess,
"run",
lambda command, **kwargs: (
calls.append((command, kwargs))
or subprocess.CompletedProcess(command, 1, stdout=json.dumps(payload), stderr="")
),
)
result = normalize.collect_windows_hardware_preflight(args)
command, kwargs = calls[0]
assert command[-1] == "--diagnostics-json"
assert kwargs["check"] is False
assert result.ok is False
assert result.failure_message == "MIDI output query 'Missing' matched 0 ports"
assert result.checks[0].details["device"] == 2
def test_collect_windows_hardware_diagnostics_parses_json_array(tmp_path, monkeypatch) -> None:
windows_python = tmp_path / "python.exe"
windows_python.touch()
args = argparse.Namespace(
windows_python=str(windows_python),
device="helix",
audio_device=None,
steering_output=None,
steering_channel=None,
sample_rate=None,
input_mapping=None,
output_mapping=None,
blocksize=None,
preset_wait=None,
snapshot_wait=None,
measurement_wait=None,
timeout=5,
)
payload = [
{
"name": "device_profile",
"status": "pass",
"summary": "Loaded Helix",
"detail": "device=helix",