-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathtest_frontend_tkinter_parameter_editor_table.py
More file actions
executable file
·2273 lines (1833 loc) · 103 KB
/
test_frontend_tkinter_parameter_editor_table.py
File metadata and controls
executable file
·2273 lines (1833 loc) · 103 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
#!/usr/bin/env python3
"""
Tests for the ParameterEditorTable class.
This file is part of ArduPilot Methodic Configurator. https://github.com/ArduPilot/MethodicConfigurator
SPDX-FileCopyrightText: 2024-2026 Amilcar Lucas
SPDX-License-Identifier: GPL-3.0-or-later
"""
import tkinter as tk
from collections.abc import Generator
from tkinter import ttk
from types import SimpleNamespace
from typing import Any, Optional, cast
from unittest.mock import MagicMock, patch
import pytest
from conftest import PARAMETER_EDITOR_TABLE_HEADERS_ADVANCED, PARAMETER_EDITOR_TABLE_HEADERS_SIMPLE
from ardupilot_methodic_configurator import _
from ardupilot_methodic_configurator.backend_filesystem import LocalFilesystem
from ardupilot_methodic_configurator.data_model_ardupilot_parameter import ArduPilotParameter
from ardupilot_methodic_configurator.data_model_par_dict import Par, ParDict
from ardupilot_methodic_configurator.data_model_parameter_editor import (
InvalidParameterNameError,
ParameterEditor,
ParameterValueUpdateResult,
ParameterValueUpdateStatus,
)
from ardupilot_methodic_configurator.frontend_tkinter_pair_tuple_combobox import (
PairTupleCombobox,
setup_combobox_mousewheel_handling,
)
from ardupilot_methodic_configurator.frontend_tkinter_parameter_editor_table import (
NEW_VALUE_DIFFERENT_STR,
NEW_VALUE_WIDGET_WIDTH,
ParameterEditorTable,
ParameterEditorTableDialogs,
)
# pylint: disable=protected-access, redefined-outer-name, too-few-public-methods, too-many-lines
def create_mock_data_model_ardupilot_parameter( # pylint: disable=too-many-arguments, too-many-positional-arguments # noqa: PLR0913
name: str = "TEST_PARAM",
value: float = 1.0,
comment: str = "test comment",
metadata: Optional[dict[str, Any]] = None,
fc_value: Optional[float] = None,
is_forced: bool = False,
is_derived: bool = False,
is_calibration: bool = False,
is_readonly: bool = False,
is_bitmask: bool = False,
is_multiple_choice: bool = False,
) -> ArduPilotParameter:
"""Create a mock ArduPilotParameter for testing."""
# pylint: disable=duplicate-code
metadata = metadata or {}
if is_calibration:
metadata["Calibration"] = True
if is_readonly:
metadata["ReadOnly"] = True
if is_bitmask:
metadata["Bitmask"] = {0: "Bit 0", 1: "Bit 1", 2: "Bit 2"}
if is_multiple_choice:
metadata["values"] = {"0": "Option 0", "1": "Option 1"}
# pylint: enable=duplicate-code
metadata.setdefault("unit", "")
metadata.setdefault("doc_tooltip", "Test tooltip")
metadata.setdefault("unit_tooltip", "Unit tooltip")
par_obj = Par(value, comment)
default_par = Par(0.0, "default") if metadata else None
forced_par = Par(value, "forced comment") if is_forced else None
derived_par = Par(value, "derived comment") if is_derived else None
return ArduPilotParameter(
name=name,
par_obj=par_obj,
metadata=metadata,
default_par=default_par,
fc_value=fc_value,
forced_par=forced_par,
derived_par=derived_par,
)
@pytest.fixture
def mock_master() -> Generator[tk.Tk, None, None]:
"""Create a mock tkinter root window."""
root = tk.Tk()
yield root
root.destroy()
@pytest.fixture
def mock_local_filesystem() -> MagicMock:
"""Create a mock LocalFilesystem instance."""
filesystem = MagicMock(spec=LocalFilesystem)
filesystem.configuration_steps = {}
filesystem.file_parameters = {}
filesystem.forced_parameters = {}
filesystem.derived_parameters = {}
filesystem.get_eval_variables.return_value = {}
# Add required dictionaries with default empty values
filesystem.doc_dict = {}
filesystem.param_default_dict = {} # Add this line
return filesystem
@pytest.fixture
def mock_parameter_editor_window() -> MagicMock:
"""Create a mock parent window editor."""
parent_window = MagicMock()
parent_window.gui_complexity = "simple"
parent_window.repopulate_parameter_table = MagicMock()
parent_window.on_skip_click = MagicMock()
parent_window.root = MagicMock(spec=tk.Tk)
return parent_window
@pytest.fixture
def table_dialogs() -> ParameterEditorTableDialogs:
"""Provide dialog callbacks that record invocations for assertions."""
return ParameterEditorTableDialogs(
show_error=MagicMock(),
show_info=MagicMock(),
ask_yes_no=MagicMock(return_value=True),
)
@pytest.fixture
def parameter_editor_table(
mock_master: tk.Tk,
mock_local_filesystem: MagicMock,
mock_parameter_editor_window: MagicMock,
table_dialogs: ParameterEditorTableDialogs,
) -> ParameterEditorTable:
"""Create a ParameterEditorTable instance for testing, using ParameterEditor abstraction."""
with patch("tkinter.ttk.Style") as mock_style:
style_instance = mock_style.return_value
style_instance.lookup.return_value = "white"
# Create a mock ParameterEditor
mock_param_editor = MagicMock(spec=ParameterEditor)
mock_param_editor._local_filesystem = mock_local_filesystem
mock_param_editor.current_file = "test_file"
mock_param_editor.is_fc_connected = True
# Set up get_parameters_as_par_dict to return the right parameters
def get_current_file_parameters() -> ParDict:
return mock_local_filesystem.file_parameters.get(mock_param_editor.current_file, ParDict())
mock_param_editor.get_parameters_as_par_dict.return_value = get_current_file_parameters()
# Mock the _repopulate_configuration_step_parameters method to return the expected tuple
mock_param_editor._repopulate_configuration_step_parameters.return_value = ([], [])
# Mock the parameters attribute that gets populated during _repopulate_configuration_step_parameters
mock_param_editor.current_step_parameters = {}
# Mock the delete method to actually delete from the _local_filesystem parameters
def mock_delete_parameter(param_name: str) -> None:
current_file = mock_param_editor.current_file
if (
current_file in mock_local_filesystem.file_parameters
and param_name in mock_local_filesystem.file_parameters[current_file]
):
del mock_local_filesystem.file_parameters[current_file][param_name]
mock_param_editor.delete_parameter_from_current_file = MagicMock(side_effect=mock_delete_parameter)
# Mock _has_unsaved_changes to return False by default
mock_param_editor._has_unsaved_changes.return_value = False
mock_param_editor.should_display_bitmask_parameter_editor_usage.return_value = False
# Create the table instance
table = ParameterEditorTable(mock_master, mock_param_editor, mock_parameter_editor_window, dialogs=table_dialogs)
mock_parameter_editor_window.root = mock_master
# Mock necessary tkinter widgets and methods
table.add_parameter_row = MagicMock()
table.view_port = mock_master
table.canvas = MagicMock()
table.canvas.yview = MagicMock()
table.canvas.yview_moveto = MagicMock()
# Mock grid_slaves to handle widget cleanup
table.grid_slaves = MagicMock(return_value=[])
# Initialize variables dict
table.variables = {}
# Initialize upload_checkbutton_var dict
table.upload_checkbutton_var = {}
return table
def test_init_creates_instance_with_correct_attributes(
parameter_editor_table, mock_master, mock_local_filesystem, mock_parameter_editor_window
) -> None:
"""
ParameterEditorTable initializes with correct attributes and dependencies.
GIVEN: Required dependencies (master window, _local_filesystem, parameter editor)
WHEN: ParameterEditorTable is instantiated
THEN: All attributes are properly set and configured
AND: The table is ready for parameter display and editing
"""
# Arrange: Dependencies provided by fixtures
# Act: Instance created by fixture
# Assert: All attributes properly initialized
assert parameter_editor_table.main_frame == mock_master
assert parameter_editor_table.parameter_editor._local_filesystem == mock_local_filesystem
assert parameter_editor_table.parameter_editor_window == mock_parameter_editor_window
# current_file is now managed by parameter_editor
assert parameter_editor_table.parameter_editor.current_file == "test_file"
assert isinstance(parameter_editor_table.upload_checkbutton_var, dict)
assert parameter_editor_table.parameter_editor._has_unsaved_changes() is False
def test_init_configures_style(parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable properly configures ttk.Style for consistent appearance.
GIVEN: A ParameterEditorTable instance needs proper styling
WHEN: The table is initialized with ttk.Style configuration
THEN: Style is configured with appropriate button properties
AND: Visual consistency is maintained across the application
"""
# Arrange: Set up style mocking
with patch("tkinter.ttk.Style", autospec=True) as mock_style_class:
# Configure the mock style to return a valid color for both instances
mock_style_instance = mock_style_class.return_value
mock_style_instance.lookup.return_value = "#ffffff" # Use a valid hex color
mock_style_instance.configure.return_value = None
# Create a mock ParameterEditor for the new instance
mock_param_editor = MagicMock(spec=ParameterEditor)
mock_param_editor._local_filesystem = parameter_editor_table.parameter_editor._local_filesystem
mock_param_editor.current_file = "test_file"
mock_param_editor.get_parameters_as_par_dict.return_value = (
parameter_editor_table.parameter_editor._local_filesystem.file_parameters.get("test_file", {})
)
# Act: Create a new instance to trigger style configuration
ParameterEditorTable(parameter_editor_table.main_frame, mock_param_editor, parameter_editor_table.parameter_editor)
# Assert: Style was configured with expected parameters
mock_style_instance.configure.assert_called_with("narrow.TButton", padding=0, width=4, border=(0, 0, 0, 0))
def test_init_with_style_lookup_failure(mock_master, mock_local_filesystem, mock_parameter_editor_window) -> None:
"""
ParameterEditorTable handles style lookup failures gracefully during initialization.
GIVEN: ttk.Style lookup fails to return a valid color
WHEN: ParameterEditorTable is initialized
THEN: Initialization completes successfully despite style lookup failure
AND: Default styling is applied without crashing
"""
# Arrange: Set up style lookup to fail
with patch("tkinter.ttk.Style", autospec=True) as mock_style:
style_instance = mock_style.return_value
style_instance.lookup.return_value = None # Simulate style lookup failure
mock_param_editor = MagicMock(spec=ParameterEditor)
mock_param_editor._local_filesystem = mock_local_filesystem
mock_param_editor.current_file = "test_file"
mock_param_editor.get_parameters_as_par_dict.return_value = {}
# Act: Create table instance with style lookup failure
table = ParameterEditorTable(mock_master, mock_param_editor, mock_parameter_editor_window)
# Assert: Table created successfully despite style issues
assert table is not None
# Check that Style was initialized
mock_style.assert_called()
# Check that lookup was called
style_instance.lookup.assert_called()
# Check that configure was called with expected parameters
style_instance.configure.assert_called_with("narrow.TButton", padding=0, width=4, border=(0, 0, 0, 0))
def test_repopulate_empty_parameters(parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable handles repopulation with no parameters gracefully.
GIVEN: A configuration file contains no parameters
WHEN: The parameter table is repopulated
THEN: No parameter rows are added to the table
AND: The operation completes without errors
"""
# Arrange: Set up empty parameters
test_file = "test_file"
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = ParDict({test_file: ParDict({})})
# Act: Repopulate the table
parameter_editor_table.repopulate_table(show_only_differences=False, gui_complexity="simple")
# Assert: No parameter rows were added
parameter_editor_table.add_parameter_row.assert_not_called()
def test_repopulate_clears_existing_content(parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable clears existing content before repopulating.
GIVEN: A parameter table contains existing parameter rows
WHEN: The table is repopulated with new data
THEN: All existing widgets are properly destroyed
AND: The table is ready for new parameter display
"""
# Arrange: Create existing content to be cleared
test_file = "test_file"
dummy_widget = ttk.Label(parameter_editor_table)
parameter_editor_table.grid_slaves = MagicMock(return_value=[dummy_widget])
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = ParDict(
{test_file: ParDict({"PARAM1": Par(1.0, "test comment")})}
)
parameter_editor_table.parameter_editor._local_filesystem.doc_dict = {"PARAM1": {"units": "none"}}
parameter_editor_table.parameter_editor._local_filesystem.param_default_dict = ParDict({"PARAM1": Par(0.0, "default")})
# Act: Repopulate the table
parameter_editor_table.repopulate_table(show_only_differences=False, gui_complexity="simple")
# Assert: Existing content was cleared
assert not dummy_widget.winfo_exists()
def test_repopulate_handles_none_current_file(parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable handles repopulation when no current file is set.
GIVEN: No current configuration file is selected
WHEN: The parameter table attempts to repopulate
THEN: The operation completes gracefully without errors
AND: No parameter rows are added to the table
"""
# Arrange: Set up empty file state
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = ParDict({"": ParDict({})})
parameter_editor_table.parameter_editor.current_file = ""
parameter_editor_table.parameter_editor._local_filesystem.doc_dict = {}
parameter_editor_table.parameter_editor._local_filesystem.param_default_dict = ParDict({})
# Act: Attempt to repopulate_table with no current file
parameter_editor_table.repopulate_table(show_only_differences=False, gui_complexity="simple")
# Assert: No parameter rows were added
parameter_editor_table.add_parameter_row.assert_not_called()
def test_repopulate_single_parameter(parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable correctly displays a single parameter.
GIVEN: A configuration file contains exactly one parameter
WHEN: The parameter table is repopulated
THEN: One parameter row is added to the table
AND: The parameter is displayed with correct formatting
"""
# Arrange: Set up single parameter
test_file = "test_file"
parameter_editor_table.parameter_editor.current_file = test_file
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = ParDict(
{test_file: ParDict({"PARAM1": Par(1.0, "test comment")})}
)
parameter_editor_table.parameter_editor._local_filesystem.doc_dict = {"PARAM1": {"units": "none"}}
parameter_editor_table.parameter_editor._local_filesystem.param_default_dict = ParDict({"PARAM1": Par(0.0, "default")})
# Act: Repopulate with single parameter
with patch.object(parameter_editor_table, "grid_slaves", return_value=[]):
parameter_editor_table.repopulate_table(show_only_differences=False, gui_complexity="simple")
# Assert: Parameter row was added (implicitly tested through repopulate_table call)
def test_repopulate_multiple_parameters(parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable correctly displays multiple parameters.
GIVEN: A configuration file contains multiple parameters
WHEN: The parameter table is repopulated
THEN: All parameter rows are added to the table
AND: Parameters are displayed in correct order with proper formatting
"""
# Arrange: Set up multiple parameters
test_file = "test_file"
parameter_editor_table.parameter_editor.current_file = test_file
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = ParDict(
{
test_file: ParDict(
{
"PARAM1": Par(1.0, "test comment 1"),
"PARAM2": Par(2.0, "test comment 2"),
"PARAM3": Par(3.0, "test comment 3"),
}
)
}
)
parameter_editor_table.parameter_editor._local_filesystem.doc_dict = {
"PARAM1": {"units": "none"},
"PARAM2": {"units": "none"},
"PARAM3": {"units": "none"},
}
parameter_editor_table.parameter_editor._local_filesystem.param_default_dict = ParDict(
{
"PARAM1": Par(0.0, "default"),
"PARAM2": Par(0.0, "default"),
"PARAM3": Par(0.0, "default"),
}
)
# Act: Repopulate with multiple parameters
with patch.object(parameter_editor_table, "grid_slaves", return_value=[]):
parameter_editor_table.repopulate_table(show_only_differences=False, gui_complexity="simple")
# Assert: All parameters were processed (implicitly tested through repopulate_table call)
def test_repopulate_preserves_checkbutton_states(parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable preserves upload checkbutton states during repopulation.
GIVEN: Parameters have upload checkbuttons in specific states
WHEN: The parameter table is repopulated
THEN: The checkbutton states are preserved
AND: User selections for parameter upload are maintained
"""
# Arrange: Set up checkbutton states
test_file = "test_file"
param1_var = tk.BooleanVar(value=True)
param2_var = tk.BooleanVar(value=False)
parameter_editor_table.upload_checkbutton_var = {"PARAM1": param1_var, "PARAM2": param2_var}
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = ParDict(
{test_file: ParDict({"PARAM1": Par(1.0, "test comment"), "PARAM2": Par(2.0, "test comment")})}
)
parameter_editor_table.parameter_editor._local_filesystem.doc_dict = {
"PARAM1": {"units": "none"},
"PARAM2": {"units": "none"},
}
parameter_editor_table.parameter_editor._local_filesystem.param_default_dict = ParDict(
{"PARAM1": Par(0.0, "default"), "PARAM2": Par(0.0, "default")}
)
# Act: Repopulate the table
parameter_editor_table.repopulate_table(show_only_differences=False, gui_complexity="simple")
# Assert: Checkbutton states were preserved (implicitly tested through repopulate_table call)
def test_repopulate_show_only_differences(parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable shows only parameters that differ from defaults when requested.
GIVEN: A configuration file with parameters that have different values from defaults
WHEN: The table is repopulated with show_only_differences=True
THEN: Only parameters with non-default values are displayed
AND: Default parameters are filtered out for focused editing
"""
# Arrange: Set up parameters with some matching defaults
test_file = "test_file"
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = ParDict(
{
test_file: ParDict(
{
"PARAM1": Par(1.0, "test comment"), # Same as FC
"PARAM2": Par(2.5, "test comment"), # Different from FC
"PARAM3": Par(3.0, "test comment"), # Not in FC
}
)
}
)
parameter_editor_table.parameter_editor._local_filesystem.doc_dict = {
"PARAM1": {"units": "none"},
"PARAM2": {"units": "none"},
"PARAM3": {"units": "none"},
}
parameter_editor_table.parameter_editor._local_filesystem.param_default_dict = ParDict(
{
"PARAM1": Par(0.0, "default"),
"PARAM2": Par(0.0, "default"),
"PARAM3": Par(0.0, "default"),
}
)
# Act: Repopulate showing only differences
parameter_editor_table.repopulate_table(show_only_differences=True, gui_complexity="simple")
# Assert: Only differing parameters were processed (implicitly tested through repopulate_table call)
@pytest.mark.parametrize("pending_scroll", [True, False])
def test_repopulate_uses_scroll_helper(parameter_editor_table: ParameterEditorTable, pending_scroll: bool) -> None:
"""
ParameterEditorTable uses scroll helper to manage table positioning during repopulation.
GIVEN: A parameter table with pending scroll state
WHEN: The table is repopulated
THEN: The scroll helper is called with the correct position
AND: The pending scroll flag is reset after operation
"""
# Arrange: Set pending scroll state
parameter_editor_table._pending_scroll_to_bottom = pending_scroll
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = ParDict({"test_file": ParDict({})})
parameter_editor_table.parameter_editor._repopulate_configuration_step_parameters = MagicMock(return_value=([], []))
parameter_editor_table._update_table = MagicMock()
parameter_editor_table.view_port.winfo_children = MagicMock(return_value=[])
parameter_editor_table._create_headers_and_tooltips = MagicMock(return_value=((), ()))
parameter_editor_table._should_show_upload_column = MagicMock(return_value=False)
# Act: Repopulate and check scroll behavior
with patch.object(parameter_editor_table, "_apply_scroll_position") as mock_scroll:
parameter_editor_table.repopulate_table(show_only_differences=False, gui_complexity="simple")
# Assert: Scroll position was applied correctly
mock_scroll.assert_called_once_with(pending_scroll)
assert parameter_editor_table._pending_scroll_to_bottom is False
@pytest.mark.parametrize(
("scroll_to_bottom", "expected_position"),
[(True, 1.0), (False, 0.0)],
)
def test_apply_scroll_position_moves_canvas(
parameter_editor_table: ParameterEditorTable, scroll_to_bottom: bool, expected_position: float
) -> None:
"""
ParameterEditorTable scroll helper moves canvas to correct position.
GIVEN: A parameter table canvas that needs scrolling
WHEN: The scroll position is applied with specific scroll_to_bottom value
THEN: The canvas is moved to the expected position (1.0 for bottom, 0.0 for top)
AND: The UI update is triggered to reflect the change
"""
# Arrange: Set up canvas mock
canvas_yview = parameter_editor_table.canvas.yview_moveto
assert isinstance(canvas_yview, MagicMock)
canvas_yview.reset_mock()
# Act: Apply scroll position
with patch.object(parameter_editor_table, "update_idletasks") as mock_update_idletasks:
parameter_editor_table._apply_scroll_position(scroll_to_bottom)
# Assert: Canvas moved to expected position and UI updated
mock_update_idletasks.assert_called_once_with()
canvas_yview.assert_called_once_with(expected_position)
class TestUIComplexityBehavior:
"""Test how ParameterEditorTable adapts to different UI complexity settings."""
def test_should_show_upload_column_simple_mode(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable hides upload column in simple UI mode.
GIVEN: The application is configured for simple UI complexity
WHEN: The table determines whether to show the upload column
THEN: The upload column is hidden to reduce interface complexity
AND: Users see a cleaner, less cluttered interface
"""
# Arrange: Set simple mode
parameter_editor_table.parameter_editor_window.gui_complexity = "simple"
# Act: Check if upload column should be shown
should_show = parameter_editor_table._should_show_upload_column()
# Assert: Upload column is hidden in simple mode
assert should_show is False
def test_should_show_upload_column_advanced_mode(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable shows upload column in advanced UI mode.
GIVEN: The application is configured for advanced UI complexity
WHEN: The table determines whether to show the upload column
THEN: The upload column is displayed for full functionality access
AND: Advanced users have complete control over parameter uploads
"""
# Arrange: Set advanced mode
parameter_editor_table.parameter_editor_window.gui_complexity = "normal"
# Act: Check if upload column should be shown
should_show = parameter_editor_table._should_show_upload_column()
# Assert: Upload column is shown in advanced mode
assert should_show is True
def test_should_show_upload_column_explicit_override(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable respects explicit gui_complexity parameter override.
GIVEN: The application default is simple mode
WHEN: An explicit advanced complexity parameter is passed
THEN: The explicit parameter takes precedence over the default
AND: The upload column is shown despite the default setting
"""
# Arrange: Set simple mode as default
parameter_editor_table.parameter_editor_window.gui_complexity = "simple"
# Act: Explicitly pass "normal" to override the default
should_show = parameter_editor_table._should_show_upload_column("normal")
# Assert: Explicit parameter overrides default
assert should_show is True
def test_get_change_reason_column_index_with_upload(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable calculates correct column index for change reason with upload column.
GIVEN: The upload column is enabled in the parameter table
WHEN: The change reason column index is calculated
THEN: The index accounts for all base columns plus the upload column
AND: Change reason entries are positioned correctly in the grid
"""
# Act: Get column index with upload column enabled
column_index = parameter_editor_table._get_change_reason_column_index(show_upload_column=True)
# Assert: Base columns (6) + Upload column (1) = 7
assert column_index == 7
def test_get_change_reason_column_index_without_upload(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable calculates correct column index for change reason without upload column.
GIVEN: The upload column is disabled in the parameter table
WHEN: The change reason column index is calculated
THEN: The index accounts for only the base columns
AND: Change reason entries are positioned correctly in the simplified grid
"""
# Act: Get column index with upload column disabled
column_index = parameter_editor_table._get_change_reason_column_index(show_upload_column=False)
# Assert: Base columns (6) only
assert column_index == 6
class TestParameterChangeStateBehavior:
"""Test how ParameterEditorTable manages parameter change state and unsaved changes."""
def test_has_unsaved_changes_false(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable correctly reports no unsaved changes when parameters are clean.
GIVEN: All parameters in the configuration are saved and unchanged
WHEN: The system checks for unsaved changes
THEN: No unsaved changes are detected
AND: Users can proceed without worrying about lost changes
"""
# Arrange: Configure no dirty parameters
parameter_editor_table.parameter_editor._has_unsaved_changes.return_value = False
# Act: Check for unsaved changes
result = parameter_editor_table.parameter_editor._has_unsaved_changes()
# Assert: No unsaved changes detected
assert result is False
def test_has_unsaved_changes_true(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable correctly reports unsaved changes when parameters are modified.
GIVEN: Some parameters in the configuration have been modified but not saved
WHEN: The system checks for unsaved changes
THEN: Unsaved changes are detected
AND: Users are warned about potential data loss
"""
# Arrange: Configure dirty parameters
parameter_editor_table.parameter_editor._has_unsaved_changes.return_value = True
# Act: Check for unsaved changes
result = parameter_editor_table.parameter_editor._has_unsaved_changes()
# Assert: Unsaved changes detected
assert result is True
class TestIntegrationBehavior:
"""Test integration between ParameterEditorTable components and methods."""
def test_gui_complexity_affects_column_calculation(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
ParameterEditorTable column calculations adapt to UI complexity settings.
GIVEN: The application switches between simple and advanced UI modes
WHEN: Column indices are calculated for different complexity levels
THEN: Simple mode excludes upload column from calculations
AND: Advanced mode includes upload column in position calculations
"""
# Arrange: Set simple mode as default
parameter_editor_table.parameter_editor_window.gui_complexity = "simple"
# Act: Calculate columns for simple mode
show_upload = parameter_editor_table._should_show_upload_column()
column_index = parameter_editor_table._get_change_reason_column_index(show_upload)
# Assert: Simple mode calculations
assert show_upload is False
assert column_index == 6 # No upload column
# Act: Calculate columns for advanced mode override
show_upload_advanced = parameter_editor_table._should_show_upload_column("normal")
column_index_advanced = parameter_editor_table._get_change_reason_column_index(show_upload_advanced)
# Assert: Advanced mode calculations
assert show_upload_advanced is True
assert column_index_advanced == 7 # With upload column
class TestParameterValueUpdateHandling:
"""Test the presenter-driven parameter value update handling."""
def test_handle_parameter_value_update_success(self, parameter_editor_table: ParameterEditorTable) -> None:
"""Presenter reports success and UI returns True without showing errors."""
param = create_mock_data_model_ardupilot_parameter(name="TEST_PARAM", value=1.0)
error_dialog = cast("MagicMock", parameter_editor_table._dialogs.show_error)
error_dialog.reset_mock()
update_mock = cast("MagicMock", parameter_editor_table.parameter_editor.update_parameter_value)
update_mock.return_value = ParameterValueUpdateResult(ParameterValueUpdateStatus.UPDATED)
result = parameter_editor_table._handle_parameter_value_update(param, "2.5")
assert result is True
update_mock.assert_called_once_with(
"TEST_PARAM",
"2.5",
include_range_check=True,
)
error_dialog.assert_not_called()
def test_handle_parameter_value_update_unchanged(self, parameter_editor_table: ParameterEditorTable) -> None:
"""Presenter reports unchanged result which UI treats as no-op."""
param = create_mock_data_model_ardupilot_parameter(name="TEST_PARAM", value=1.0)
update_mock = cast("MagicMock", parameter_editor_table.parameter_editor.update_parameter_value)
update_mock.return_value = ParameterValueUpdateResult(ParameterValueUpdateStatus.UNCHANGED)
error_dialog = cast("MagicMock", parameter_editor_table._dialogs.show_error)
result = parameter_editor_table._handle_parameter_value_update(param, "1.0")
assert result is False
error_dialog.assert_not_called()
def test_handle_parameter_value_update_out_of_range_accepted(self, parameter_editor_table: ParameterEditorTable) -> None:
"""UI confirms out-of-range prompt and retries update ignoring range checks."""
param = create_mock_data_model_ardupilot_parameter(name="TEST_PARAM", value=5.0)
ask_dialog = cast("MagicMock", parameter_editor_table._dialogs.ask_yes_no)
ask_dialog.return_value = True
update_mock = cast("MagicMock", parameter_editor_table.parameter_editor.update_parameter_value)
update_mock.side_effect = [
ParameterValueUpdateResult(
ParameterValueUpdateStatus.CONFIRM_OUT_OF_RANGE,
title="Out-of-range value",
message="Too high",
),
ParameterValueUpdateResult(ParameterValueUpdateStatus.UPDATED),
]
result = parameter_editor_table._handle_parameter_value_update(param, "15.0")
assert result is True
assert update_mock.call_count == 2
first_call, second_call = update_mock.call_args_list
assert first_call.kwargs["include_range_check"] is True
assert second_call.kwargs["include_range_check"] is False
ask_dialog.assert_called_once()
def test_handle_parameter_value_update_out_of_range_rejected(self, parameter_editor_table: ParameterEditorTable) -> None:
"""UI aborts update when user rejects out-of-range confirmation."""
param = create_mock_data_model_ardupilot_parameter(name="TEST_PARAM", value=5.0)
ask_dialog = cast("MagicMock", parameter_editor_table._dialogs.ask_yes_no)
ask_dialog.return_value = False
update_mock = cast("MagicMock", parameter_editor_table.parameter_editor.update_parameter_value)
update_mock.return_value = ParameterValueUpdateResult(
ParameterValueUpdateStatus.CONFIRM_OUT_OF_RANGE,
title="Out-of-range value",
message="Too high",
)
result = parameter_editor_table._handle_parameter_value_update(param, "15.0")
assert result is False
update_mock.assert_called_once()
ask_dialog.assert_called_once()
def test_handle_parameter_value_update_error_without_prompt(self, parameter_editor_table: ParameterEditorTable) -> None:
"""Presenter-provided errors are surfaced through the injected dialog callbacks."""
param = create_mock_data_model_ardupilot_parameter(name="TEST_PARAM", value=5.0)
update_mock = cast("MagicMock", parameter_editor_table.parameter_editor.update_parameter_value)
update_mock.return_value = ParameterValueUpdateResult(
ParameterValueUpdateStatus.ERROR,
title="Invalid value",
message="Not a number",
)
ask_dialog = cast("MagicMock", parameter_editor_table._dialogs.ask_yes_no)
error_dialog = cast("MagicMock", parameter_editor_table._dialogs.show_error)
result = parameter_editor_table._handle_parameter_value_update(param, "bad", include_range_check=False)
assert result is False
ask_dialog.assert_not_called()
error_dialog.assert_called_once_with("Invalid value", "Not a number")
def test_handle_parameter_value_update_generic_error(self, parameter_editor_table: ParameterEditorTable) -> None:
"""Presenter errors without title/message still show a fallback dialog."""
param = create_mock_data_model_ardupilot_parameter(name="TEST_PARAM", value=5.0)
update_mock = cast("MagicMock", parameter_editor_table.parameter_editor.update_parameter_value)
update_mock.return_value = ParameterValueUpdateResult(ParameterValueUpdateStatus.ERROR)
error_dialog = cast("MagicMock", parameter_editor_table._dialogs.show_error)
result = parameter_editor_table._handle_parameter_value_update(param, "bad")
assert result is False
error_dialog.assert_called_once()
def test_handle_parameter_value_update_forced_retry_failure(self, parameter_editor_table: ParameterEditorTable) -> None:
"""If retry also fails, the UI surfaces the second error message to the user."""
param = create_mock_data_model_ardupilot_parameter(name="TEST_PARAM", value=5.0)
ask_dialog = cast("MagicMock", parameter_editor_table._dialogs.ask_yes_no)
ask_dialog.return_value = True
update_mock = cast("MagicMock", parameter_editor_table.parameter_editor.update_parameter_value)
update_mock.side_effect = [
ParameterValueUpdateResult(
ParameterValueUpdateStatus.CONFIRM_OUT_OF_RANGE,
title="Out-of-range value",
message="Too high",
),
ParameterValueUpdateResult(
ParameterValueUpdateStatus.ERROR,
title="Retry failed",
message="Still invalid",
),
]
error_dialog = cast("MagicMock", parameter_editor_table._dialogs.show_error)
result = parameter_editor_table._handle_parameter_value_update(param, "15.0")
assert result is False
error_dialog.assert_called_once_with("Retry failed", "Still invalid")
class TestWidgetCreationBehavior:
"""Test the behavior of widget creation methods for visual indicators."""
def test_create_parameter_name_calibration(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
User interface highlights calibration parameters with yellow background.
GIVEN: A parameter editor table is initialized
WHEN: A parameter name label is created for a calibration parameter
THEN: The label has a yellow background to indicate calibration status
"""
# Arrange: Create calibration parameter
param = create_mock_data_model_ardupilot_parameter(name="CAL_PARAM", is_calibration=True)
# Act: Create parameter name label
label = parameter_editor_table._create_parameter_name(param)
# Assert: Label has yellow background for calibration
assert isinstance(label, ttk.Label)
assert str(label.cget("background")) == "yellow"
def test_create_parameter_name_readonly(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
User interface highlights readonly parameters with purple background.
GIVEN: A parameter editor table is initialized
WHEN: A parameter name label is created for a readonly parameter
THEN: The label has a purple background to indicate readonly status
"""
# Arrange: Create readonly parameter
param = create_mock_data_model_ardupilot_parameter(name="RO_PARAM", is_readonly=True)
# Act: Create parameter name label
label = parameter_editor_table._create_parameter_name(param)
# Assert: Label has purple background for readonly
assert isinstance(label, ttk.Label)
assert str(label.cget("background")) == "purple1"
class TestEventHandlerBehavior:
"""Test the behavior of event handler methods."""
def test_on_parameter_delete_confirmed(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
User can successfully delete parameters when confirming the action.
GIVEN: A parameter exists in the current file
WHEN: User confirms parameter deletion
THEN: The parameter is removed and the table is repopulated
"""
# Arrange: Set up parameter in _local_filesystem
parameter_editor_table.parameter_editor.current_file = "test_file"
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = {
"test_file": ParDict({"TEST_PARAM": Par(1.0, "comment")})
}
parameter_editor_table.parameter_editor_window.repopulate_parameter_table = MagicMock()
parameter_editor_table.canvas = MagicMock()
parameter_editor_table.canvas.yview.return_value = [0.5, 0.8]
# Act: Confirm parameter deletion
ask_dialog = cast("MagicMock", parameter_editor_table._dialogs.ask_yes_no)
ask_dialog.return_value = True
parameter_editor_table._on_parameter_delete("TEST_PARAM")
# Assert: Parameter is deleted and table repopulated
assert "TEST_PARAM" not in parameter_editor_table.parameter_editor._local_filesystem.file_parameters["test_file"]
parameter_editor_table.parameter_editor_window.repopulate_parameter_table.assert_called_once_with()
def test_on_parameter_delete_cancelled(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
User can cancel parameter deletion without removing the parameter.
GIVEN: A parameter exists in the current file
WHEN: User cancels parameter deletion
THEN: The parameter remains in the file
"""
# Arrange: Set up parameter in _local_filesystem
parameter_editor_table.parameter_editor.current_file = "test_file"
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = {
"test_file": {"TEST_PARAM": Par(1.0, "comment")}
}
# Act: Cancel parameter deletion
ask_dialog = cast("MagicMock", parameter_editor_table._dialogs.ask_yes_no)
ask_dialog.return_value = False
parameter_editor_table._on_parameter_delete("TEST_PARAM")
# Assert: Parameter remains in file
assert "TEST_PARAM" in parameter_editor_table.parameter_editor._local_filesystem.file_parameters["test_file"]
def test_confirm_parameter_addition_valid_fc_param(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
User can successfully add valid flight controller parameters.
GIVEN: A valid parameter name that exists in the flight controller
WHEN: User attempts to add the parameter
THEN: The parameter is added successfully and the operation returns true
"""
# Arrange: Set up empty file and mock successful addition
parameter_editor_table.parameter_editor.current_file = "test_file"
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = {"test_file": ParDict({})}
parameter_editor_table.parameter_editor_window.repopulate_parameter_table = MagicMock()
# Act: Confirm parameter addition with mocked success
with patch.object(
parameter_editor_table.parameter_editor,
"add_parameter_to_current_file",
return_value=True,
):
result = parameter_editor_table._confirm_parameter_addition("NEW_PARAM")
# Assert: Parameter addition succeeds
assert result is True
parameter_editor_table.parameter_editor.add_parameter_to_current_file.assert_called_once_with("NEW_PARAM")
def test_confirm_parameter_addition_empty_name(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
User sees error when attempting to add parameter with empty name.
GIVEN: User attempts to add a parameter with an empty name
WHEN: The system validates the parameter name
THEN: An error dialog is shown and the operation fails
"""
# Arrange: Mock the add_parameter_to_current_file method to raise error
parameter_editor_table.parameter_editor.add_parameter_to_current_file = MagicMock(
side_effect=InvalidParameterNameError("Parameter name can not be empty.")
)
# Act & Assert: Confirm parameter addition shows error for empty name
error_dialog = cast("MagicMock", parameter_editor_table._dialogs.show_error)
result = parameter_editor_table._confirm_parameter_addition("")
assert result is False
error_dialog.assert_called_once()
def test_confirm_parameter_addition_existing_param(self, parameter_editor_table: ParameterEditorTable) -> None:
"""
User sees error when attempting to add parameter that already exists.
GIVEN: A parameter with the same name already exists in the current file
WHEN: User attempts to add a parameter with that name
THEN: An error dialog is shown and the operation fails
"""
# Arrange: Set up existing parameter in file
parameter_editor_table.parameter_editor.current_file = "test_file"
parameter_editor_table.parameter_editor._local_filesystem.file_parameters = {
"test_file": ParDict({"EXISTING_PARAM": Par(1.0, "comment")})
}