diff --git a/ARCHITECTURE_2_flight_controller_communication.md b/ARCHITECTURE_2_flight_controller_communication.md index c038595fb..b0686ec30 100644 --- a/ARCHITECTURE_2_flight_controller_communication.md +++ b/ARCHITECTURE_2_flight_controller_communication.md @@ -118,7 +118,6 @@ This architecture provides: - **Purpose**: Manages flight controller connection lifecycle - **Key Classes**: - `FlightControllerConnection`: Connection establishment and management - - `FakeSerialForTests`: Mock serial class for unit testing - **Key Methods**: - `connect()`: Establishes connection with retry logic - `disconnect()`: Closes connection gracefully diff --git a/ardupilot_methodic_configurator/backend_flightcontroller_connection.py b/ardupilot_methodic_configurator/backend_flightcontroller_connection.py index 739fe7147..167d96768 100644 --- a/ardupilot_methodic_configurator/backend_flightcontroller_connection.py +++ b/ardupilot_methodic_configurator/backend_flightcontroller_connection.py @@ -23,7 +23,7 @@ from time import monotonic from time import sleep as time_sleep from time import time as time_time -from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, Optional, Union, cast, no_type_check +from typing import TYPE_CHECKING, Any, ClassVar, Optional, Union, cast, no_type_check import serial.tools.list_ports import serial.tools.list_ports_common @@ -108,33 +108,6 @@ def _serial_port_autodetect_rank(port: ListPortInfo) -> int: # pylint: disable=too-many-lines -class FakeSerialForTests: - """ - A mock serial class for unit testing purposes. - - This class simulates the behavior of a serial connection for testing purposes, - allowing for the testing of serial communication without needing a physical - serial device. It includes methods for reading, writing, and checking the - number of bytes in the input buffer, as well as closing the connection. - """ - - def __init__(self, device: str) -> None: - self.device = device - - def read(self, _len) -> str: # noqa: ANN001 - return "" - - def write(self, _buf) -> NoReturn: # noqa: ANN001 - msg = "write always fails" - raise Exception(msg) # pylint: disable=broad-exception-raised - - def inWaiting(self) -> int: # noqa: N802, pylint: disable=invalid-name - return 0 - - def close(self) -> None: - pass - - DEFAULT_BAUDRATE: int = 115200 FC_STATUS_TEXT_BUFFER_LIMIT = 100 DEVICE_FC_PARAM_FROM_FILE: str = "file" # Special device name to simulate FC parameters from params.param file diff --git a/ardupilot_methodic_configurator/data_model_data_telemetry.py b/ardupilot_methodic_configurator/data_model_data_telemetry.py index e354f1beb..3c4279e60 100644 --- a/ardupilot_methodic_configurator/data_model_data_telemetry.py +++ b/ardupilot_methodic_configurator/data_model_data_telemetry.py @@ -115,6 +115,7 @@ def update(self, sample: TelemetrySample) -> TelemetryState: # pylint: disable= and radio.source == cached_radio.source and radio.rxerrors >= cached_radio.rxerrors ) + old_radio = previous.radio if same_counter else None if not same_counter: # Rebaseline the radio independently; preserve byte/message measurement intervals. previous = replace(previous, radio=radio) @@ -131,7 +132,6 @@ def update(self, sample: TelemetrySample) -> TelemetryState: # pylint: disable= strict=True, ) ) - old_radio = previous.radio if same_counter else None # Polling the same fresh report must retain its last measured rate. if radio is None or old_radio is None or radio.time != old_radio.time: radio_error_rate = None diff --git a/pyproject.toml b/pyproject.toml index 282ce4df8..08c9882b9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -321,6 +321,7 @@ pytest_add_cli_args_test_selection = [ "tests/test_data_model_firmware_upload.py", "tests/test_frontend_tkinter_usage_popup_windows.py", "tests/test_frontend_tkinter_log_analysis.py", + "tests/test_frontend_tkinter_log_analysis_rendering.py", "tests/test_backend_flightcontroller_connection.py", "tests/test_backend_flightcontroller.py", "tests/test_backend_filesystem_program_settings.py", diff --git a/tests/acceptance_template_import_from_params.py b/tests/acceptance_template_import_from_params.py index 637d4a083..cd19fafa0 100755 --- a/tests/acceptance_template_import_from_params.py +++ b/tests/acceptance_template_import_from_params.py @@ -127,6 +127,8 @@ - Tests skip gracefully when empty templates are unavailable for certain vehicle types - ArduPlane uses its available empty_4.7.x template; Heli and Rover are skipped where an empty template is required because none is currently available +- Template setup downloads exact-release metadata when its cache is missing or stale; + project metadata seeding then runs offline from the validated cache """ @@ -136,13 +138,16 @@ import re import shutil from pathlib import Path +from tempfile import TemporaryDirectory import pytest import ardupilot_methodic_configurator.backend_filesystem as filesystem_module +from ardupilot_methodic_configurator.annotate_params import get_xml_url from ardupilot_methodic_configurator.backend_filesystem import LocalFilesystem from ardupilot_methodic_configurator.backend_filesystem_vehicle_components import VehicleComponents from ardupilot_methodic_configurator.backend_flightcontroller import DEVICE_FC_PARAM_FROM_FILE, FlightController +from ardupilot_methodic_configurator.backend_internet import download_file_from_url from ardupilot_methodic_configurator.data_model_par_dict import ParDict from ardupilot_methodic_configurator.data_model_vehicle_components import ComponentDataModel from ardupilot_methodic_configurator.data_model_vehicle_components_json_schema import ( @@ -258,6 +263,83 @@ def test_offline_metadata_seed_rejects_incompatible_firmware_metadata(tmp_path: _seed_offline_parameter_metadata(template_dir, target_dir, "ArduCopter", "4.6.3") +@pytest.mark.parametrize(("vehicle_type", "firmware_version"), [("ArduCopter", "4.6.3"), ("ArduPlane", "4.7.2")]) +@pytest.mark.parametrize("cached_release", [None, "4.6.0", "4.6.30", "4.6.3", "4.7.2"]) +def test_template_setup_prepares_exact_release_metadata( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + vehicle_type: str, + firmware_version: str, + cached_release: str | None, +) -> None: + """ + Template setup repairs missing or stale caches and works offline with matching metadata. + + GIVEN: A template with missing, stale or matching cached metadata + WHEN: Acceptance setup prepares the template and seeds a generated project + THEN: Both use the exact firmware release, downloading only when necessary + """ + metadata_vehicle = vehicle_type.removeprefix("Ardu") + (tmp_path / "vehicle_components.json").write_text( + json.dumps({"Components": {"Flight Controller": {"Firmware": {"Version": firmware_version}}}}), encoding="utf-8" + ) + metadata_path = tmp_path / "apm.pdef.xml" + if cached_release: + metadata_path.write_text(f"", encoding="utf-8") + expected_metadata = f"" + downloaded_urls = [] + + def download_metadata(url: str, path: str) -> bool: + assert cached_release != firmware_version, "Matching template metadata must work offline" + downloaded_urls.append(url) + Path(path).write_text(expected_metadata, encoding="utf-8") + return True + + monkeypatch.setattr(f"{__name__}.download_file_from_url", download_metadata) + + _prepare_template_parameter_metadata(tmp_path, vehicle_type) + target_dir = tmp_path / "new_vehicle" + target_dir.mkdir() + _seed_offline_parameter_metadata(tmp_path, target_dir, vehicle_type, firmware_version) + + assert (target_dir / "apm.pdef.xml").read_text(encoding="utf-8") == expected_metadata + expected_url = get_xml_url(vehicle_type, firmware_version) + "apm.pdef.xml" + assert downloaded_urls == ([] if cached_release == firmware_version else [expected_url]) + + +@pytest.mark.parametrize("downloaded_release", [None, "Copter-4.6.0", "Plane-4.6.3", "Copter-4.6.30", "unknown"]) +def test_template_setup_preserves_cache_when_exact_metadata_is_unavailable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, downloaded_release: str | None +) -> None: + """ + Failed refreshes cannot replace the template cache with incompatible metadata. + + GIVEN: A stale template cache and an unavailable or incompatible exact-release download + WHEN: Acceptance setup attempts to refresh metadata + THEN: Setup fails and preserves the old cache for diagnosis + """ + (tmp_path / "vehicle_components.json").write_text( + json.dumps({"Components": {"Flight Controller": {"Firmware": {"Version": "4.6.3"}}}}), encoding="utf-8" + ) + metadata_path = tmp_path / "apm.pdef.xml" + original_metadata = "" + metadata_path.write_text(original_metadata, encoding="utf-8") + + def download_metadata(_url: str, path: str) -> bool: + if downloaded_release is None: + return False + Path(path).write_text(f"", encoding="utf-8") + return True + + monkeypatch.setattr(f"{__name__}.download_file_from_url", download_metadata) + + with pytest.raises(ValueError, match=r"Could not prepare|incompatible"): + _prepare_template_parameter_metadata(tmp_path, "ArduCopter") + + assert metadata_path.read_text(encoding="utf-8") == original_metadata + assert sorted(path.name for path in tmp_path.iterdir()) == ["apm.pdef.xml", "vehicle_components.json"] + + def _seed_offline_parameter_metadata( metadata_source_dir: Path, new_vehicle_dir: str | Path, vehicle_type: str, firmware_version: str ) -> None: @@ -281,6 +363,33 @@ def _seed_offline_parameter_metadata( shutil.copy2(metadata_source, metadata_target) +def _prepare_template_parameter_metadata(template_dir: Path, vehicle_type: str) -> None: + """Ensure template setup caches the exact release before running offline project imports.""" + with (template_dir / "vehicle_components.json").open(encoding="utf-8") as component_file: + firmware_version = json.load(component_file)["Components"]["Flight Controller"]["Firmware"]["Version"] + metadata_vehicle = {"ArduCopter": "Copter", "ArduPlane": "Plane"}[vehicle_type] + release_tag = f"Generated from git tag {metadata_vehicle}-{firmware_version}" + + def matches_release(metadata_path: Path) -> bool: + if not metadata_path.is_file(): + return False + return re.search(re.escape(release_tag) + r"(?=\s|\(|$)", metadata_path.read_text(encoding="utf-8")) is not None + + metadata_target = template_dir / "apm.pdef.xml" + if matches_release(metadata_target): + return + + # Keep the old cache intact unless a download for the exact release succeeds. + metadata_url = get_xml_url(vehicle_type, firmware_version) + "apm.pdef.xml" + with TemporaryDirectory(dir=template_dir) as download_dir: + downloaded_metadata = Path(download_dir) / "apm.pdef.xml" + if not download_file_from_url(metadata_url, str(downloaded_metadata)): + raise ValueError(f"Could not prepare offline parameter metadata from {metadata_url}") + if not matches_release(downloaded_metadata): + raise ValueError(f"Downloaded parameter metadata is incompatible with {vehicle_type} {firmware_version}") + downloaded_metadata.replace(metadata_target) + + def create_test_filesystem(vehicle_dir: Path, vehicle_type: str): """ Create LocalFilesystem and schema for testing. @@ -445,6 +554,7 @@ def get_empty_template_dir(vehicle_type: str) -> Path: if not templates_base.exists(): raise FileNotFoundError(f"Template directory not found: {templates_base}") + _prepare_template_parameter_metadata(templates_base, vehicle_type) return templates_base diff --git a/tests/log_analysis/test_data_model_gnss_analysis.py b/tests/log_analysis/test_data_model_gnss_analysis.py index e779a910d..d5cc82745 100755 --- a/tests/log_analysis/test_data_model_gnss_analysis.py +++ b/tests/log_analysis/test_data_model_gnss_analysis.py @@ -127,6 +127,25 @@ def test_status_indication_maps_receiver_status_to_precise_finding( assert finding.timestamp_us == finding.end_timestamp_us == 1_000_000 +def test_status_indications_exclude_invalid_values_from_readable_coverage() -> None: + """Valid status samples produce findings while healthy and invalid samples affect coverage correctly.""" + series = SensorSeries( + 2, + {"TimeUS": np.arange(1.0, 6.0), "GSS": np.array([1.0, 0.0, 2.5, 256.0, 3.0])}, + ) + + outcomes = GPSLogAnalysis._status_indications(series, "ILB5", "GSS") # pylint: disable=protected-access + findings = [item for item in outcomes if item.timestamp_us is not None] + coverage = next(item for item in outcomes if item.group == "Coverage") + + assert [(item.timestamp_us, _evidence(item)) for item in findings] == [ + (2_000_000, {"status": 0.0}), + (5_000_000, {"status": 3.0}), + ] + assert [item.severity for item in findings] == ["informational", "warning"] + assert _evidence(coverage) == {"readable": 3.0} + + @pytest.mark.parametrize( ("message", "field", "threat", "previous", "current_time", "current_status", "recovered"), [ @@ -366,6 +385,29 @@ def test_no_timestamped_capability_is_not_reported_as_completed_analysis() -> No assert "No supported timestamped GNSS checks" in result.reason +def test_receiver_analysis_sorts_findings_and_reports_available_guidance() -> None: + """Receiver findings are ordered by time and the completed assessment carries usable guidance.""" + log = LogData() + _add(log, "AERG", TimeUS=[2, 1], Jam=[2, 3], Spf=[3, 2]) + + result = GPSLogAnalysis(log, _context()).analyse() + + assert result.available is True + assert result.name == "GPS Analysis" + assert result.reason == ( + "GNSS assessment complete. Receiver indications and consistency discrepancies require review; " + "sensor faults can cause similar symptoms, and undetected spoofing remains possible." + ) + assert result.related_step == "" + group_order = {"Receiver indications": 0, "GNSS consistency": 1, "Correlated evidence": 2, "Coverage": 3} + actual_groups = [group_order.get(item.group or "", 4) for item in result.outcomes] + assert actual_groups == sorted(actual_groups) + indications = [item for item in result.outcomes if item.group == "Receiver indications"] + assert [(item.timestamp_us, item.source) for item in indications] == sorted( + (item.timestamp_us, item.source) for item in indications + ) + + def test_ublox_rise_is_receiver_specific_and_constant_levels_are_not_an_attack() -> None: """GIVEN interleaved receivers WHEN one indicator rises THEN only that receiver gets an RF finding.""" log = LogData() diff --git a/tests/log_analysis/test_data_model_imu_analysis.py b/tests/log_analysis/test_data_model_imu_analysis.py index abdce68fc..def0da2b7 100755 --- a/tests/log_analysis/test_data_model_imu_analysis.py +++ b/tests/log_analysis/test_data_model_imu_analysis.py @@ -20,6 +20,7 @@ from ardupilot_methodic_configurator.log_analysis.data_model_availability_imu import ImuLogAnalysis, ImuLogAvailabilityModel from ardupilot_methodic_configurator.log_analysis.data_model_log_analysis_context import LogAnalysisContext from ardupilot_methodic_configurator.log_analysis.data_model_log_availability import LogAvailabilityState +from ardupilot_methodic_configurator.log_analysis.data_model_log_data import LogData # pylint: disable=redefined-outer-name @@ -194,25 +195,32 @@ def test_user_is_told_to_check_log_bitmask_when_imu_bit_is_disabled(self, imu_ap class TestImuLogAnalysisTemperatureCalibrationState: """Test temperature calibration enable/disable/in-progress state detection.""" - def test_user_is_recommended_to_calibrate_when_temp_cal_is_not_enabled(self) -> None: + def test_user_is_recommended_to_calibrate_when_temp_cal_is_not_enabled(self, imu_apm_doc, monkeypatch) -> None: """ User is nudged to run temperature calibration when it has never been enabled. GIVEN: INS_TCAL1_ENABLE is 0 (disabled) WHEN: Temperature calibration analysis runs - THEN: It suggests running calibration, without proposing a one-click fix + THEN: It suggests running calibration and provides the template enable value """ # Arrange: single-IMU board, calibration disabled - log_data = FakeLogData({}) + log_data = LogData() model = ImuLogAnalysis(log_data, _context({"INS_TCAL1_ENABLE": 0.0, "INS_ACC_ID": 1.0}, apm_doc=imu_apm_doc)) + monkeypatch.setattr(model, "step_for_parameter", lambda _param_name: "05-ins-calibration") + monkeypatch.setattr(model, "expected_parameter_value", lambda _step, _param_name: (1.0, "template")) # Act: run temperature calibration analysis outcomes = model.check_temperature_calibration() - # Assert: one suggestion, no unsafe suggested_value + # Assert: one suggestion with the template enable value assert len(outcomes) == 1 assert outcomes[0].param_name == "INS_TCAL1_ENABLE" + assert outcomes[0].value == 0.0 + assert outcomes[0].suggested_value == 1.0 + assert outcomes[0].related_step == "05-ins-calibration" + assert outcomes[0].message.startswith("IMU 1 temperature calibration is not enabled.") assert "not enabled" in outcomes[0].message + assert "Consider running it" in outcomes[0].message def test_user_sees_calibration_in_progress_status(self) -> None: """ @@ -230,6 +238,10 @@ def test_user_sees_calibration_in_progress_status(self) -> None: outcomes = model.check_temperature_calibration() # Assert: in-progress status reported + assert len(outcomes) == 1 + assert outcomes[0].param_name == "INS_TCAL1_ENABLE" + assert outcomes[0].value == 2.0 + assert outcomes[0].message.startswith("IMU 1 temperature calibration is in progress") assert "in progress" in outcomes[0].message def test_user_sees_only_present_imu_instances_analyzed(self) -> None: @@ -248,6 +260,73 @@ def test_user_sees_only_present_imu_instances_analyzed(self) -> None: assert len(outcomes) == 1 + def test_user_sees_second_imu_when_first_imu_has_no_calibration_parameter(self, imu_apm_doc) -> None: + """A missing TCAL enable parameter for IMU 1 does not skip a present IMU 2.""" + model = ImuLogAnalysis( + LogData(), + _context( + {"INS_ACC_ID": 1.0, "INS_ACC2_ID": 2.0, "INS_TCAL2_ENABLE": 2.0}, + apm_doc=imu_apm_doc, + ), + ) + + outcomes = model.check_temperature_calibration() + + assert len(outcomes) == 1 + assert outcomes[0].param_name == "INS_TCAL2_ENABLE" + assert outcomes[0].value == 2.0 + assert "in progress" in outcomes[0].message + + def test_user_sees_third_imu_when_earlier_imu_instances_are_absent(self, imu_apm_doc) -> None: + """Analysis continues through absent IMU instances to report a present IMU 3.""" + model = ImuLogAnalysis( + LogData(), + _context({"INS_ACC3_ID": 3.0, "INS_TCAL3_ENABLE": 0.0}, apm_doc=imu_apm_doc), + ) + + outcomes = model.check_temperature_calibration() + + assert len(outcomes) == 1 + assert outcomes[0].param_name == "INS_TCAL3_ENABLE" + assert "not enabled" in outcomes[0].message + + def test_user_sees_unexpected_temperature_calibration_enable_value(self, imu_apm_doc) -> None: + """Enable values outside disabled, learning, and documented states are reported.""" + model = ImuLogAnalysis( + LogData(), + _context({"INS_TCAL1_ENABLE": 7.0, "INS_ACC_ID": 1.0}, apm_doc=imu_apm_doc), + ) + + outcomes = model.check_temperature_calibration() + + assert len(outcomes) == 1 + assert outcomes[0].param_name == "INS_TCAL1_ENABLE" + assert outcomes[0].value == 7.0 + assert "unexpected INS_TCAL1_ENABLE value of 7.0" in outcomes[0].message + + def test_user_is_warned_when_temperature_calibration_bounds_are_missing(self, imu_apm_doc) -> None: + """An enabled calibration without either temperature bound is reported as inconsistent.""" + model = ImuLogAnalysis( + LogData(), + _context( + { + "INS_TCAL1_ENABLE": 1.0, + "INS_ACC_ID": 1.0, + "INS_ACC1_CALTEMP": 25.0, + "INS_GYR1_CALTEMP": 25.0, + "INS_TCAL1_TMIN": -10.0, + }, + apm_doc=imu_apm_doc, + ), + ) + + outcomes = model.check_temperature_calibration() + + assert len(outcomes) == 1 + assert outcomes[0].param_name == "INS_TCAL1_ENABLE" + assert outcomes[0].value is None + assert "TMIN/TMAX data is missing" in outcomes[0].message + class TestImuLogAnalysisTemperatureSpread: """Test the sourced spread thresholds (10C required, 25C recommended) for completed calibrations.""" @@ -351,8 +430,37 @@ def test_user_sees_both_a_warm_start_caveat_and_a_below_recommended_spread_findi assert "above freezing" in outcomes[0].message assert "below the recommended" in outcomes[1].message - -class TestImuLogAnalysisInvalidCalTemp: # pylint: disable=too-few-public-methods + def test_user_sees_exact_minimum_and_recommended_spread_boundaries(self, imu_apm_doc) -> None: + """The 10C minimum and 25C recommendation use the documented inclusive boundaries.""" + cases = [ + (-10.0, 0.0, "meets the minimum but below the recommended"), + (-10.0, 15.0, "good coverage"), + (-10.0, 20.0, "good coverage"), + ] + for tmin, tmax, expected_message in cases: + model = ImuLogAnalysis( + LogData(), + _context( + { + "INS_TCAL1_ENABLE": 1.0, + "INS_ACC_ID": 1.0, + "INS_ACC1_CALTEMP": 25.0, + "INS_GYR1_CALTEMP": 25.0, + "INS_TCAL1_TMIN": tmin, + "INS_TCAL1_TMAX": tmax, + }, + apm_doc=imu_apm_doc, + ), + ) + + outcomes = model.check_temperature_calibration() + + assert len(outcomes) == 1 + assert expected_message in outcomes[0].message + assert outcomes[0].value == pytest.approx(tmax - tmin) + + +class TestImuLogAnalysisInvalidCalTemp: """Test detection of an invalid CALTEMP baseline on a calibrated IMU.""" def test_user_is_warned_when_caltemp_baseline_was_never_set(self, imu_apm_doc) -> None: @@ -385,4 +493,31 @@ def test_user_is_warned_when_caltemp_baseline_was_never_set(self, imu_apm_doc) - # Assert: single "never performed" finding, spread not evaluated assert len(outcomes) == 1 + assert outcomes[0].param_name == "INS_TCAL1_ENABLE" + assert outcomes[0].value is None assert "never performed" in outcomes[0].message + + def test_user_is_warned_when_either_caltemp_baseline_is_missing(self, imu_apm_doc) -> None: + """A missing baseline for either sensor invalidates that IMU's temperature calibration.""" + for accel_caltemp, gyro_caltemp in ((-300.0, 25.0), (25.0, -300.0)): + model = ImuLogAnalysis( + LogData(), + _context( + { + "INS_TCAL1_ENABLE": 1.0, + "INS_ACC_ID": 1.0, + "INS_ACC1_CALTEMP": accel_caltemp, + "INS_GYR1_CALTEMP": gyro_caltemp, + "INS_TCAL1_TMIN": -15.0, + "INS_TCAL1_TMAX": 15.0, + }, + apm_doc=imu_apm_doc, + ), + ) + + outcomes = model.check_temperature_calibration() + + assert len(outcomes) == 1 + assert outcomes[0].param_name == "INS_TCAL1_ENABLE" + assert outcomes[0].value is None + assert "accelerometer/gyroscope calibration (CALTEMP) was never performed" in outcomes[0].message diff --git a/tests/log_analysis/test_data_model_log_availability_check.py b/tests/log_analysis/test_data_model_log_availability_check.py index 8e8a8e0e7..5f6390f1e 100755 --- a/tests/log_analysis/test_data_model_log_availability_check.py +++ b/tests/log_analysis/test_data_model_log_availability_check.py @@ -118,6 +118,106 @@ def test_pm_non_finite_values_are_reported_as_invalid() -> None: assert len(validation.issues) == 7 assert all("non-finite telemetry values" in issue for issue in validation.issues) assert status is not None + assert status.average_cpu_load == 0.0 + assert status.peak_cpu_load == 0.0 + assert status.scheduler_long_loops == 0 + assert status.max_loop_time_us == 0 + assert status.free_memory_bytes == 0 + assert status.healthy is None + + +@pytest.mark.parametrize("columns", [None, np.empty(0, dtype=[("Load", "f8")])]) +def test_pm_status_is_unavailable_when_message_is_missing_or_empty(columns: np.ndarray | None) -> None: # type: ignore[misc] + """PM health is unavailable when no performance-monitor samples were logged.""" + log_data = LogData() + if columns is not None: + log_data.add_message_columns("PM", columns) + + assert get_pm_status(log_data) is None + + +@pytest.mark.parametrize( + ("load", "memory", "healthy"), + [ + ((70.0, 80.0), (10_001, 12_000), True), + ((80.0, 80.0), (12_000, 12_000), False), + ((60.0, 95.0), (12_000, 12_000), False), + ((60.0, 90.0), (10_000, 12_000), False), + ], +) +def test_pm_status_checks_all_health_limits_and_summarizes_samples( + load: tuple[float, float], memory: tuple[int, int], healthy: bool +) -> None: + """PM summary uses averages, peaks, sums and strict CPU/memory health limits.""" + log_data = LogData() + log_data.add_message_columns( + "PM", + np.array( + list(zip(load, (2, 3), (500, 900), memory, strict=True)), + dtype=[("Load", "f8"), ("NLon", "i4"), ("MaxT", "i4"), ("Mem", "i4")], + ), + ) + + status = get_pm_status(log_data) + + assert status is not None + assert status.average_cpu_load == pytest.approx(sum(load) / 2) + assert status.peak_cpu_load == max(load) + assert status.scheduler_long_loops == 5 + assert status.max_loop_time_us == 900 + assert status.free_memory_bytes == min(memory) + assert status.healthy is healthy + + +def test_pm_status_defaults_missing_optional_fields_and_leaves_health_unknown() -> None: + """A partial PM schema summarizes available counters without claiming health.""" + log_data = LogData() + log_data.add_message_columns( + "PM", + np.array([(4, 500), (6, 700)], dtype=[("NLon", "i4"), ("MaxT", "i4")]), + ) + + status = get_pm_status(log_data) + + assert status is not None + assert status.average_cpu_load == 0.0 + assert status.peak_cpu_load == 0.0 + assert status.scheduler_long_loops == 10 + assert status.max_loop_time_us == 700 + assert status.free_memory_bytes == 0 + assert status.healthy is None + + +def test_pm_status_defaults_missing_loop_fields_without_reading_them() -> None: + """PM schemas without NLon or MaxT keep their summary defaults.""" + log_data = LogData() + log_data.add_message_columns( + "PM", + np.array([(70.0, 12_000)], dtype=[("Load", "f8"), ("Mem", "i4")]), + ) + + status = get_pm_status(log_data) + + assert status is not None + assert status.average_cpu_load == pytest.approx(70.0) + assert status.peak_cpu_load == pytest.approx(70.0) + assert status.scheduler_long_loops == 0 + assert status.max_loop_time_us == 0 + assert status.free_memory_bytes == 12_000 + assert status.healthy is True + + +def test_pm_status_health_is_unknown_when_load_or_memory_is_missing() -> None: + """Health requires both CPU load and free memory, even when one metric is available.""" + log_data = LogData() + log_data.add_message_columns("PM", np.array([(70.0,)], dtype=[("Load", "f8")])) + + status = get_pm_status(log_data) + + assert status is not None + assert status.average_cpu_load == pytest.approx(70.0) + assert status.peak_cpu_load == pytest.approx(70.0) + assert status.free_memory_bytes == 0 assert status.healthy is None diff --git a/tests/plugins/test_data_model_ahrs_orientation.py b/tests/plugins/test_data_model_ahrs_orientation.py index 19a74ba84..8eae8a77e 100755 --- a/tests/plugins/test_data_model_ahrs_orientation.py +++ b/tests/plugins/test_data_model_ahrs_orientation.py @@ -348,6 +348,67 @@ def test_estimation_rejects_inconsistent_capture_geometry(self, connected_flight "Place the vehicle accurately and capture the sequence again." ) + def test_estimation_reports_failure_when_pose_axes_are_degenerate(self, connected_flight_controller) -> None: + """Return a failed estimate when collinear captures cannot define three axes.""" + model = AhrsOrientationDataModel(connected_flight_controller) + model._samples = { + "LEVEL": (0.0, 0.0, -1000.0), + "NOSE DOWN": (0.0, 0.0, -1000.0), + "RIGHT": (0.0, 0.0, -1000.0), + } + + assert model.estimate_orientation() == ( + False, + None, + "Unable to estimate orientation from samples. Capture the sequence again.", + ) + + @pytest.mark.parametrize("missing_step", ["LEVEL", "NOSE DOWN", "RIGHT"]) + def test_matrix_estimation_rejects_each_unusable_pose(self, connected_flight_controller, missing_step: str) -> None: + """A zero vector in any capture makes the orientation matrix unavailable.""" + model = AhrsOrientationDataModel(connected_flight_controller) + model._samples = { + "LEVEL": (0.0, 0.0, -1000.0), + "NOSE DOWN": (-1000.0, 0.0, 0.0), + "RIGHT": (0.0, -1000.0, 0.0), + } + model._samples[missing_step] = (0.0, 0.0, 0.0) + + assert model._estimate_board_from_body_matrix() is None + + def test_best_preset_uses_first_code_when_every_score_ties(self, connected_flight_controller) -> None: + """Keep the first preset as the deterministic winner for equal scores.""" + model = AhrsOrientationDataModel(connected_flight_controller) + zero_matrix = [[0.0, 0.0, 0.0] for _row in range(3)] + + assert model._best_preset_code(zero_matrix) == (0, 0.0) + + @pytest.mark.parametrize(("axis_value", "expected_pitch"), [(-1.2, 90.0), (1.2, -90.0)]) + def test_euler_conversion_clamps_pitch_sine_to_unit_range( + self, connected_flight_controller, axis_value: float, expected_pitch: float + ) -> None: + """Clamp round-off beyond either unit boundary before applying asin.""" + model = AhrsOrientationDataModel(connected_flight_controller) + matrix = model._identity_matrix() + matrix[2][0] = axis_value + + assert model._matrix_to_euler321_deg(matrix)[1] == expected_pitch + + def test_x_rotation_matrix_has_zero_first_entry_in_its_last_row(self, connected_flight_controller) -> None: + """An X rotation changes only the Y/Z axes.""" + model = AhrsOrientationDataModel(connected_flight_controller) + + matrix = model._rot_x(90.0) + assert matrix[0] == pytest.approx([1.0, 0.0, 0.0]) + assert matrix[1] == pytest.approx([0.0, 0.0, -1.0]) + assert matrix[2] == pytest.approx([0.0, 1.0, 0.0]) + + def test_vector_at_normalization_threshold_keeps_its_direction(self, connected_flight_controller) -> None: + """Treat the exact minimum nonzero magnitude as a valid direction.""" + model = AhrsOrientationDataModel(connected_flight_controller) + + assert model._normalize((1e-6, 0.0, 0.0)) == (1.0, 0.0, 0.0) + @pytest.mark.parametrize("acceleration", [7.0, 7.5, 13.0]) def test_capture_accepts_the_documented_still_acceleration_range(connected_flight_controller, acceleration: float) -> None: diff --git a/tests/plugins/test_data_model_esc_rpm_scale.py b/tests/plugins/test_data_model_esc_rpm_scale.py index f2f1a48bd..9347358a1 100755 --- a/tests/plugins/test_data_model_esc_rpm_scale.py +++ b/tests/plugins/test_data_model_esc_rpm_scale.py @@ -10,8 +10,9 @@ SPDX-License-Identifier: GPL-3.0-or-later """ -# pylint: disable=redefined-outer-name,too-few-public-methods +# pylint: disable=protected-access,redefined-outer-name,too-few-public-methods +import codecs import json from math import inf, nan from pathlib import Path @@ -96,6 +97,9 @@ def test_user_cannot_upload_a_script_without_an_available_vehicle_directory( class TestHobbywingDetection: """Verify ESC and motor product metadata detection.""" + def test_missing_product_value_normalizes_to_empty_text(self) -> None: + assert EscRpmScaleDataModel._normalized_product_value(None) == "" + def test_detects_hobbywing_6x_se_in_esc_product(self, model, filesystem) -> None: filesystem.vehicle_components_fs.data["Components"]["ESC"] = { "Product": {"Manufacturer": "Hobbywing", "Model": "6X SE"} @@ -201,6 +205,22 @@ def test_real_motor_data_covers_every_frame_class(self) -> None: class TestScriptGeneration: """Verify pure Lua script generation and local persistence.""" + def test_script_file_uses_explicit_utf8_encoding(self, model, monkeypatch: pytest.MonkeyPatch) -> None: + """Write the generated Lua script with a stable UTF-8 encoding.""" + original_write_text = Path.write_text + encodings: list[str | None] = [] + + def record_write_text(path: Path, data: str, encoding: str | None = None) -> int: + encodings.append(encoding) + return original_write_text(path, data, encoding=encoding) + + monkeypatch.setattr(Path, "write_text", record_write_text) + model.write_script(0.714) + + assert len(encodings) == 1 + assert encodings[0] is not None + assert codecs.lookup(encodings[0]).name == "utf-8" + def test_generates_scale_calls_for_requested_esc_outputs(self, model) -> None: assert model.generate_script(0.714, 4) == ( "esc_telem:set_rpm_scale(0, 0.714)\n" diff --git a/tests/plugins/test_data_model_motor_test.py b/tests/plugins/test_data_model_motor_test.py index 64d61072c..91c2b3438 100755 --- a/tests/plugins/test_data_model_motor_test.py +++ b/tests/plugins/test_data_model_motor_test.py @@ -13,7 +13,7 @@ from logging import LogRecord from pathlib import Path from typing import Any -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock, call, patch import pytest @@ -347,6 +347,24 @@ def motor_test_model_with_corrupted_json_data(mock_flight_controller, mock_files class TestMotorTestDataModelInitialization: """Test motor test data model initialization and configuration.""" + def test_unconfigured_model_starts_with_empty_configuration_state(self, mock_flight_controller, mock_filesystem) -> None: + """Constructor defaults remain empty until loading, configuration, and settings run.""" + with ( + patch.object(MotorTestDataModel, "_load_motor_data"), + patch.object(MotorTestDataModel, "_update_frame_configuration"), + patch.object(MotorTestDataModel, "_get_test_settings_from_disk"), + ): + model = MotorTestDataModel(mock_flight_controller, mock_filesystem) + + assert model._motor_data == {} + assert (model._frame_class, model._frame_type, model._motor_count) == (0, 0, 0) + assert not model._motor_labels + assert not model._motor_numbers + assert not model._test_order + assert not model._motor_directions + assert model._frame_layout == {} + assert model._cached_frame_options is None + def test_user_can_initialize_model_with_connected_flight_controller(self, mock_flight_controller, mock_filesystem) -> None: """ User can successfully initialize motor test model with connected flight controller. @@ -470,7 +488,11 @@ def test_user_can_update_frame_configuration_successfully(self, motor_test_model THEN: Parameters should be uploaded and internal state updated """ # Arrange: Configure successful parameter setting - with patch.object(motor_test_model, "set_parameter", return_value=(True, "")): + motor_test_model._frame_type = 0 + with ( + patch.object(motor_test_model, "set_parameter", return_value=(True, "")) as set_parameter, + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_info") as info_log, + ): # Act: Update frame configuration motor_test_model.update_frame_configuration(2, 1) # Hexa X @@ -478,6 +500,14 @@ def test_user_can_update_frame_configuration_successfully(self, motor_test_model assert motor_test_model.frame_class == 2 assert motor_test_model.frame_type == 1 assert motor_test_model.motor_count == 6 # HEXA X has 6 motors + assert motor_test_model._frame_layout["Class"] == 2 + assert motor_test_model._frame_layout["Type"] == 1 + + assert set_parameter.call_args_list == [call("FRAME_CLASS", 2.0), call("FRAME_TYPE", 1.0)] + info_log.assert_called_once_with( + _("Frame configuration updated: Class=%(class)d, Type=%(type)d, Motors=%(motors)d"), + {"class": 2, "type": 1, "motors": 6}, + ) def test_user_can_update_frame_configuration_and_motor_count(self, motor_test_model) -> None: """ @@ -1850,10 +1880,9 @@ def test_set_test_duration_handles_exception_gracefully(self, motor_test_model) with pytest.raises(Exception, match="Settings save failed"): motor_test_model.set_test_duration_s(2.0) - # Assert: Error was logged - mock_log.assert_called_once() - error_call = mock_log.call_args[0] - assert "Failed to save duration setting" in error_call[0] + mock_log.assert_called_once_with( + _("Failed to save duration setting: %(error)s"), {"error": "Settings save failed"} + ) def test_set_test_throttle_handles_exception_gracefully(self, motor_test_model) -> None: """ @@ -1872,10 +1901,9 @@ def test_set_test_throttle_handles_exception_gracefully(self, motor_test_model) with pytest.raises(Exception, match="Settings save failed"): motor_test_model.set_test_throttle_pct(10) - # Assert: Error was logged - mock_log.assert_called_once() - error_call = mock_log.call_args[0] - assert "Failed to save throttle percentage setting" in error_call[0] + mock_log.assert_called_once_with( + _("Failed to save throttle percentage setting: %(error)s"), {"error": "Settings save failed"} + ) class TestMotorTestDataModelSafetyChecksAdvanced: @@ -2087,13 +2115,18 @@ def test_refresh_connection_status_handles_frame_update_exception(self, motor_te THEN: The refresh should return False without propagating the exception """ # Arrange: Mock _update_frame_configuration to raise RuntimeError - with patch.object(motor_test_model, "_update_frame_configuration", side_effect=RuntimeError("Update failed")): + with ( + patch.object(motor_test_model, "_update_frame_configuration", side_effect=RuntimeError("Update failed")), + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_warning") as warning_log, + ): # Act: Try to refresh connection status result = motor_test_model.refresh_connection_status() # Assert: Exception handled gracefully assert result is False + warning_log.assert_called_once_with(_("Failed to refresh frame configuration: %(error)s"), {"error": "Update failed"}) + def test_refresh_connection_status_succeeds_with_successful_update(self, motor_test_model) -> None: """ Connection refresh succeeds when frame configuration updates successfully. @@ -2199,6 +2232,20 @@ def _build_model( loader_cls.return_value = loader return MotorTestDataModel(mock_flight_controller, mock_filesystem) + @pytest.mark.parametrize(("duration", "throttle"), [(1, 1), (60, 100)]) + def test_persisted_settings_accept_exact_supported_boundaries( + self, motor_test_model, monkeypatch, duration, throttle + ) -> None: + """Persisted settings accept the minimum and maximum allowed values.""" + settings = {"motor_test/duration": duration, "motor_test/throttle_pct": throttle} + monkeypatch.setattr( + "ardupilot_methodic_configurator.plugins.data_model_motor_test.ProgramSettings.get_setting", + settings.get, + ) + + assert motor_test_model._get_test_duration_s() == duration + assert motor_test_model._get_test_throttle_pct() == throttle + def test_user_is_warned_when_duration_setting_missing( self, mock_flight_controller, @@ -2222,11 +2269,13 @@ def fake_get(setting: str) -> float | None: with ( patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_error") as mock_log, - pytest.raises(ReferenceError, match="duration setting not found"), + pytest.raises(ReferenceError, match=r"^Motor test duration setting not found$"), ): self._build_model(mock_flight_controller, mock_filesystem, mock_motor_data_json) - assert mock_log.call_count == 1 + mock_log.assert_called_once_with( + _("Invalid motor test duration setting: %(error)s"), {"error": "Motor test duration setting not found"} + ) def test_user_is_warned_when_duration_setting_out_of_range( self, @@ -2249,9 +2298,17 @@ def fake_get(setting: str) -> float | None: fake_get, ) - with pytest.raises(ValueError, match="at least"): + with ( + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_error") as mock_log, + pytest.raises(ValueError, match=r"^Motor test duration must be at least 1 second$"), + ): self._build_model(mock_flight_controller, mock_filesystem, mock_motor_data_json) + mock_log.assert_called_once_with( + _("Invalid motor test duration setting: %(error)s"), + {"error": "Motor test duration must be at least 1 second"}, + ) + def test_user_is_warned_when_throttle_setting_missing( self, mock_flight_controller, @@ -2275,11 +2332,14 @@ def fake_get(setting: str) -> float | None: with ( patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_error") as mock_log, - pytest.raises(ReferenceError, match="throttle percentage setting not found"), + pytest.raises(ReferenceError, match=r"^Motor test throttle percentage setting not found$"), ): self._build_model(mock_flight_controller, mock_filesystem, mock_motor_data_json) - assert mock_log.call_count == 1 + mock_log.assert_called_once_with( + _("Invalid motor test throttle percentage setting: %(error)s"), + {"error": "Motor test throttle percentage setting not found"}, + ) def test_user_is_warned_when_throttle_setting_out_of_range( self, @@ -2302,9 +2362,17 @@ def fake_get(setting: str) -> float | None: fake_get, ) - with pytest.raises(ValueError, match="must not exceed"): + with ( + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_error") as mock_log, + pytest.raises(ValueError, match=r"^Motor test throttle percentage must not exceed 100%$"), + ): self._build_model(mock_flight_controller, mock_filesystem, mock_motor_data_json) + mock_log.assert_called_once_with( + _("Invalid motor test throttle percentage setting: %(error)s"), + {"error": "Motor test throttle percentage must not exceed 100%"}, + ) + def test_user_is_warned_when_duration_setting_above_maximum( self, mock_flight_controller, @@ -2326,9 +2394,17 @@ def fake_get(setting: str) -> float | None: fake_get, ) - with pytest.raises(ValueError, match="must not exceed"): + with ( + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_error") as mock_log, + pytest.raises(ValueError, match=r"^Motor test duration must not exceed 60 seconds$"), + ): self._build_model(mock_flight_controller, mock_filesystem, mock_motor_data_json) + mock_log.assert_called_once_with( + _("Invalid motor test duration setting: %(error)s"), + {"error": "Motor test duration must not exceed 60 seconds"}, + ) + def test_user_is_warned_when_throttle_setting_below_minimum( self, mock_flight_controller, @@ -2350,9 +2426,17 @@ def fake_get(setting: str) -> float | None: fake_get, ) - with pytest.raises(ValueError, match="at least"): + with ( + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_error") as mock_log, + pytest.raises(ValueError, match=r"^Motor test throttle percentage must be at least 1%$"), + ): self._build_model(mock_flight_controller, mock_filesystem, mock_motor_data_json) + mock_log.assert_called_once_with( + _("Invalid motor test throttle percentage setting: %(error)s"), + {"error": "Motor test throttle percentage must be at least 1%"}, + ) + def test_set_test_throttle_pct_succeeds_with_valid_value(self, motor_test_model) -> None: """ Test throttle percentage setting saves successfully with valid values. @@ -3654,7 +3738,10 @@ def test_duration_below_minimum_shows_exact_message_and_keeps_previous_value(sel ): motor_test_model.set_test_duration_s(0.5) - mock_log.assert_called_once() + mock_log.assert_called_once_with( + _("Invalid motor test duration setting: %(error)s"), + {"error": "Motor test duration must be at least 1 second"}, + ) assert motor_test_model.get_test_duration_s() == 5 assert ProgramSettings.get_setting("motor_test/duration") == 5 @@ -3704,7 +3791,10 @@ def test_throttle_below_minimum_shows_exact_message_and_keeps_previous_value(sel ): motor_test_model.set_test_throttle_pct(0) - mock_log.assert_called_once() + mock_log.assert_called_once_with( + _("Invalid motor test throttle percentage setting: %(error)s"), + {"error": "Motor test throttle percentage must be at least 1%"}, + ) assert motor_test_model.get_test_throttle_pct() == 50 def test_throttle_above_maximum_shows_exact_message_and_keeps_previous_value(self, motor_test_model) -> None: @@ -4101,6 +4191,8 @@ def test_layout_missing_a_required_field_is_skipped_without_hiding_later_layouts [ {"Type": 0, "ClassName": "QUAD", "TypeName": "Plus"}, {"Type": 1, "ClassName": "QUAD"}, + {"ClassName": "QUAD", "TypeName": "Y"}, + {"Type": 2, "TypeName": "Z"}, {"Type": 1, "ClassName": "QUAD", "TypeName": "X"}, ], ) @@ -4109,7 +4201,7 @@ def test_layout_missing_a_required_field_is_skipped_without_hiding_later_layouts options = motor_test_model.get_frame_options() assert options == {"QUAD": {0: "Plus", 1: "X"}} - mock_warning.assert_called_once_with("Skipping motor layout with missing required fields") + assert mock_warning.call_args_list == [call("Skipping motor layout with missing required fields")] * 3 def test_frame_options_are_grouped_by_class_name(self, motor_test_model) -> None: """ @@ -4123,6 +4215,19 @@ def test_frame_options_are_grouped_by_class_name(self, motor_test_model) -> None assert motor_test_model.get_frame_options() == {"QUAD": {0: "Plus", 1: "X"}} + def test_frame_option_loading_logs_exact_layout_and_result_counts(self, motor_test_model) -> None: + """Frame-option debug logs preserve their messages and interpolation values.""" + _use_layouts(motor_test_model, _quad_layouts()) + + with patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_debug") as debug_log: + assert motor_test_model.get_frame_options() == {"QUAD": {0: "Plus", 1: "X"}} + + assert debug_log.call_args_list == [ + call(_("Loading frame options from motor data loader (%(count)d layouts available)"), {"count": 2}), + call(_("Successfully loaded %(count)d frame classes from motor data loader"), {"count": 1}), + call(_("Frame options loaded: %(count)d classes with %(types)d total types"), {"count": 1, "types": 2}), + ] + def test_doc_dict_fallback_parses_names_and_skips_entries_without_colon(self, motor_test_model) -> None: """ Without motor layouts, frame options come from FRAME_TYPE parameter metadata. @@ -4133,10 +4238,28 @@ def test_doc_dict_fallback_parses_names_and_skips_entries_without_colon(self, mo """ _use_layouts(motor_test_model, []) motor_test_model.filesystem.doc_dict = { - "FRAME_TYPE": {"values": {0: "Quad: Plus", "1": " quad : X ", 2: "no colon here"}} + "FRAME_TYPE": { + "values": { + 0: "Quad: Plus", + "1": " quad : X ", + 2: "no colon here", + 3: "Quad: Type: With colon", + } + } } - assert motor_test_model.get_frame_options() == {"QUAD": {0: "Plus", 1: "X"}} + with patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_debug") as debug_log: + assert motor_test_model.get_frame_options() == {"QUAD": {0: "Plus", 1: "X", 3: "Type: With colon"}} + + assert debug_log.call_args_list == [ + call(_("Loading frame options from motor data loader (%(count)d layouts available)"), {"count": 0}), + call(_("Motor data unavailable, using doc_dict as fallback for frame options")), + call( + _("Successfully loaded %(count)d frame classes from parameter metadata fallback"), + {"count": 1}, + ), + call(_("Frame options loaded: %(count)d classes with %(types)d total types"), {"count": 1, "types": 3}), + ] def test_empty_sources_log_exact_warning_and_return_nothing(self, motor_test_model) -> None: """ @@ -4154,6 +4277,13 @@ def test_empty_sources_log_exact_warning_and_return_nothing(self, motor_test_mod mock_warning.assert_called_once_with("No frame options could be loaded from motor data or parameter metadata") + def test_doc_dict_without_frame_type_values_returns_no_options(self, motor_test_model) -> None: + """Missing FRAME_TYPE values are treated as an empty metadata mapping.""" + _use_layouts(motor_test_model, []) + motor_test_model.filesystem.doc_dict = {"FRAME_TYPE": {}} + + assert motor_test_model.get_frame_options() == {} + def test_frame_options_are_cached_after_first_load(self, motor_test_model) -> None: """ Later changes to the layouts do not change already-loaded frame options. @@ -4169,6 +4299,16 @@ def test_frame_options_are_cached_after_first_load(self, motor_test_model) -> No assert motor_test_model.get_frame_options() is first + def test_cached_frame_options_log_the_cached_class_count(self, motor_test_model) -> None: + """Cached frame options log the unchanged message and number of classes.""" + options = {"QUAD": {0: "Plus"}} + motor_test_model._cached_frame_options = options + + with patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_debug") as debug_log: + assert motor_test_model.get_frame_options() is options + + debug_log.assert_called_once_with(_("Returning cached frame options with %(count)d classes"), {"count": 1}) + class TestMotorTestCurrentFrameClassTypes: """Frame types for the frame class currently on the flight controller.""" @@ -4187,6 +4327,57 @@ def test_only_types_of_the_current_frame_class_are_returned(self, motor_test_mod assert motor_test_model.get_current_frame_class_types() == {0: "Plus", 1: "X"} + def test_current_frame_class_debug_log_has_exact_count_and_identity(self, motor_test_model) -> None: + """The found-types log identifies the selected class and number of types.""" + motor_test_model._motor_data_loader.data = { + "layouts": [{"Class": 1, "ClassName": "QUAD", "Type": 0, "TypeName": "Plus"}] + } + with ( + patch.object(motor_test_model, "get_frame_options", return_value={"QUAD": {0: "Plus"}}), + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_debug") as debug_log, + ): + assert motor_test_model.get_current_frame_class_types() == {0: "Plus"} + + debug_log.assert_called_once_with( + _("Found %(count)d frame types for current frame class %(class)d (%(name)s)"), + {"count": 1, "class": 1, "name": "QUAD"}, + ) + + def test_defined_frame_class_without_matching_types_returns_empty_mapping(self, motor_test_model) -> None: + """A defined class with no frame-type options returns an empty mapping.""" + motor_test_model._motor_data_loader.data = {"layouts": [{"Class": 1, "ClassName": "QUAD"}]} + with patch.object(motor_test_model, "get_frame_options", return_value={}): + assert motor_test_model.get_current_frame_class_types() == {} + + def test_current_frame_class_requires_both_class_metadata_fields(self, motor_test_model) -> None: + """A class number without a class name cannot identify available frame types.""" + motor_test_model._motor_data_loader.data = {"layouts": [{"Class": 1, "Type": 0, "TypeName": "Plus"}]} + with ( + patch.object(motor_test_model, "get_frame_options", return_value={}), + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_warning") as warning_log, + ): + assert motor_test_model.get_current_frame_class_types() == {} + + warning_log.assert_called_once_with( + _("Current frame class %(class)d is not defined in motor configuration (max defined: %(max)d)"), + {"class": 1, "max": 0}, + ) + + def test_current_frame_class_with_non_layout_data_warns_with_zero_maximum(self, motor_test_model) -> None: + """Nonempty loader data without layouts has no defined maximum frame class.""" + motor_test_model._motor_data_loader.data = {"metadata": []} + motor_test_model.flight_controller.fc_parameters["FRAME_CLASS"] = 7 + with ( + patch.object(motor_test_model, "get_frame_options", return_value={}), + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_warning") as warning_log, + ): + assert motor_test_model.get_current_frame_class_types() == {} + + warning_log.assert_called_once_with( + _("Current frame class %(class)d is not defined in motor configuration (max defined: %(max)d)"), + {"class": 7, "max": 0}, + ) + def test_missing_frame_class_parameter_logs_exact_warning(self, motor_test_model) -> None: """ Without FRAME_CLASS, no types are returned and the warning is logged. @@ -4274,6 +4465,88 @@ def test_selecting_a_frame_type_uploads_its_code_and_updates_motor_count(self, m motor_test_model.flight_controller.set_param.assert_called_once_with("FRAME_TYPE", 0) assert motor_test_model.motor_count == 2 + def test_frame_type_parsing_requires_a_connection_with_exact_message(self, motor_test_model) -> None: + """Frame-type parsing reports the exact connection requirement.""" + motor_test_model.flight_controller.master = None + + with pytest.raises(ValidationError) as exc_info: + motor_test_model.parse_frame_type_selection("Plus") + + assert str(exc_info.value) == "Flight controller connection required for frame type parsing" + + def test_frame_type_parsing_requires_frame_class_with_exact_message(self, motor_test_model) -> None: + """Frame-type parsing reports the exact missing FRAME_CLASS error.""" + motor_test_model.flight_controller.fc_parameters.pop("FRAME_CLASS", None) + + with pytest.raises(ValidationError) as exc_info: + motor_test_model.parse_frame_type_selection("Plus") + + assert str(exc_info.value) == "FRAME_CLASS parameter not found in flight controller" + + def test_frame_type_parsing_reports_invalid_frame_class_conversion(self, motor_test_model) -> None: + """Non-numeric FRAME_CLASS values preserve their exact parsing error.""" + motor_test_model.flight_controller.fc_parameters["FRAME_CLASS"] = "not-a-number" + + with pytest.raises(ValidationError) as exc_info: + motor_test_model.parse_frame_type_selection("Plus") + + assert str(exc_info.value) == "Error parsing frame type: invalid literal for int() with base 10: 'not-a-number'" + + def test_frame_selection_preserves_callbacks_and_logs_exact_configuration(self, motor_test_model) -> None: + """Changing both frame codes forwards progress options and records the selected state.""" + _use_layouts(motor_test_model, _quad_layouts()) + motor_test_model.flight_controller.fc_parameters["FRAME_CLASS"] = 1 + motor_test_model._frame_class = 0 + motor_test_model._frame_type = 0 + progress_callback = MagicMock() + + with ( + patch.object(motor_test_model, "set_parameter", return_value=(True, "")) as set_parameter, + patch("ardupilot_methodic_configurator.plugins.data_model_motor_test.logging_info") as info_log, + ): + assert motor_test_model.update_frame_type_from_selection("X", progress_callback, 7) is True + + assert set_parameter.call_args_list == [ + call("FRAME_CLASS", 1, progress_callback, 7), + call("FRAME_TYPE", 1, progress_callback, 7), + ] + info_log.assert_called_once_with( + _("Updated frame configuration: FRAME_CLASS=%(class)d, FRAME_TYPE=%(type)d"), + {"class": 1, "type": 1}, + ) + assert motor_test_model.frame_class == 1 + assert motor_test_model.frame_type == 1 + assert motor_test_model.motor_count == 4 + assert motor_test_model._frame_layout["Type"] == 1 + + def test_frame_selection_without_layouts_keeps_motor_count_at_zero(self, motor_test_model) -> None: + """A valid frame selection with an empty layout list has no configured motors.""" + motor_test_model._motor_data_loader.data = {"layouts": []} + motor_test_model._frame_class = 0 + motor_test_model._frame_type = 0 + + with ( + patch.object(motor_test_model, "parse_frame_type_selection", return_value=(1, 1)), + patch.object(motor_test_model, "set_parameter", return_value=(True, "")), + ): + assert motor_test_model.update_frame_type_from_selection("X") is True + + assert motor_test_model._motor_count == 0 + + def test_frame_selection_with_loader_data_without_layouts_is_safe(self, motor_test_model) -> None: + """Unrelated nonempty loader data does not require a layouts key.""" + motor_test_model._motor_data_loader.data = {"metadata": []} + motor_test_model._frame_class = 0 + motor_test_model._frame_type = 0 + + with ( + patch.object(motor_test_model, "parse_frame_type_selection", return_value=(1, 1)), + patch.object(motor_test_model, "set_parameter", return_value=(True, "")), + ): + assert motor_test_model.update_frame_type_from_selection("X") is True + + assert motor_test_model._motor_count == 0 + def test_selection_matching_is_case_insensitive_and_ignores_surrounding_spaces(self, motor_test_model) -> None: """ Frame type names match regardless of case and surrounding spaces. @@ -4376,6 +4649,13 @@ def test_disabled_battery_monitor_shows_disabled_labels(self, motor_test_model) assert motor_test_model.get_battery_display_text() == ("Voltage: Disabled", "Current: Disabled") + def test_missing_battery_monitor_parameter_defaults_to_disabled(self, motor_test_model) -> None: + """A missing BATT_MONITOR parameter retains the disabled display fallback.""" + motor_test_model.flight_controller.fc_parameters.pop("BATT_MONITOR", None) + + assert motor_test_model.get_battery_display_text() == ("Voltage: Disabled", "Current: Disabled") + motor_test_model.flight_controller.get_battery_statuses.assert_not_called() + def test_battery_readings_are_shown_with_two_decimals_and_units(self, motor_test_model) -> None: """ Voltage and current are shown with two decimals and their units. @@ -4400,6 +4680,12 @@ def test_nan_readings_are_shown_as_not_available(self, motor_test_model) -> None assert motor_test_model.get_battery_display_text() == ("Voltage: N/A", "Current: 2.10A") + def test_nan_current_is_shown_as_not_available_independently(self, motor_test_model) -> None: + """A NaN current value displays N/A while a valid voltage remains visible.""" + motor_test_model.flight_controller.get_battery_statuses.return_value = ({0: (12.4, float("nan"))}, "") + + assert motor_test_model.get_battery_display_text() == ("Voltage: 12.40V", "Current: N/A") + def test_missing_battery_status_is_shown_as_not_available(self, motor_test_model) -> None: """ With no battery 1 telemetry, both readouts show N/A. @@ -4899,6 +5185,25 @@ def test_test_order_beyond_motor_count_is_excluded_from_numbering(self, motor_te assert motor_test_model.motor_numbers == [0, 5] assert motor_test_model.motor_directions == ["", "CW"] + def test_invalid_test_orders_leave_zero_based_slots_unassigned(self, motor_test_model) -> None: + """Zero and out-of-range test orders leave the initialized slots empty.""" + layout = { + "Class": 1, + "ClassName": "QUAD", + "Type": 5, + "TypeName": "Custom", + "motors": [ + {"Number": 5, "TestOrder": 0, "Rotation": "CW"}, + {"Number": 6, "TestOrder": 3, "Rotation": "CCW"}, + ], + } + + _configure_layout(motor_test_model, [layout], 1, 5) + + assert motor_test_model.motor_numbers == [0, 0] + assert motor_test_model._test_order == [0, 0] + assert motor_test_model.motor_directions == ["", ""] + class TestMotorTestTestOrderLookup: """Test order lookup accepts exactly the configured motor numbers.""" @@ -5047,6 +5352,13 @@ def test_set_parameter_without_master_raises_exact_connection_text(self, motor_t assert str(exc_info.value) == "No flight controller connection available" motor_test_model.flight_controller.set_param.assert_not_called() + def test_get_parameter_returns_none_when_disconnected_even_with_cached_parameters(self, motor_test_model) -> None: + """Cached parameter values are unavailable after the controller disconnects.""" + motor_test_model.flight_controller.fc_parameters["MOT_SPIN_ARM"] = 0.15 + motor_test_model.flight_controller.master = None + + assert motor_test_model.get_parameter("MOT_SPIN_ARM") is None + class TestMotorTestParameterRangeAndVerification: """Parameter writes validate ranges and verify readback with exact messages.""" diff --git a/tests/plugins/test_data_model_rc_receiver.py b/tests/plugins/test_data_model_rc_receiver.py index ec7ea1349..5f2f487d6 100755 --- a/tests/plugins/test_data_model_rc_receiver.py +++ b/tests/plugins/test_data_model_rc_receiver.py @@ -49,6 +49,29 @@ def status_message(present: int = _RC_BIT, enabled: int = _RC_BIT, health: int = return message +def test_model_initializes_unknown_values_and_clears_live_data(receiver_context: SimpleNamespace) -> None: + """Initialize each reading as unavailable and clear it after live telemetry.""" + model = receiver_context.model + assert model._channels == (None,) * 5 + assert model._rssi is None + assert model._rc_time is None + assert model._status_time is None + assert model._receiver_present is None + assert model._failsafe is None + + receiver_context.messages.extend([rc_message(), status_message(health=0)]) + assert model.get_receiver_state().failsafe_detected + model.clear_live_data() + + assert model._channels == (None,) * 5 + assert model._rssi is None + assert model._rc_time is None + assert model._status_time is None + assert model._receiver_present is None + assert model._failsafe is None + assert model._failsafe_detected is True + + @pytest.fixture def receiver_context(rc_controller: MagicMock) -> SimpleNamespace: """Mock only transport and time; execute the real model and MAVLink messages.""" diff --git a/tests/plugins/test_data_model_servo_out.py b/tests/plugins/test_data_model_servo_out.py index 9afdfbaab..16188411a 100755 --- a/tests/plugins/test_data_model_servo_out.py +++ b/tests/plugins/test_data_model_servo_out.py @@ -3,8 +3,7 @@ """ Behavior-driven tests for servo-output recommendations. -This file is part of ArduPilot Methodic Configurator. -https://github.com/ArduPilot/MethodicConfigurator +This file is part of ArduPilot Methodic Configurator. https://github.com/ArduPilot/MethodicConfigurator SPDX-FileCopyrightText: 2026 Amilcar do Carmo Lucas @@ -12,28 +11,27 @@ """ from collections.abc import Callable +from pathlib import Path from types import SimpleNamespace -from typing import TYPE_CHECKING, cast +from typing import cast from unittest.mock import MagicMock, patch import pytest +from ardupilot_methodic_configurator.backend_filesystem import LocalFilesystem from ardupilot_methodic_configurator.data_model_par_dict import Par, ParDict from ardupilot_methodic_configurator.data_model_parameter_editor import ( InvalidParameterNameError, OperationNotPossibleError, + ParameterEditor, ParameterValueUpdateStatus, ) from ardupilot_methodic_configurator.data_model_vehicle_components_validation import PWM_OUT_PORTS from ardupilot_methodic_configurator.plugins.data_model_servo_out import PWM_OUT_PORTS as SERVO_OUT_PWM_PORTS from ardupilot_methodic_configurator.plugins.data_model_servo_out import ServoOutDataModel, ServoOutRecommendationStatus -if TYPE_CHECKING: - from ardupilot_methodic_configurator.backend_filesystem import LocalFilesystem - from ardupilot_methodic_configurator.data_model_parameter_editor import ParameterEditor - # pytest injects fixtures by matching the test function parameter name. -# pylint: disable=redefined-outer-name,protected-access +# pylint: disable=redefined-outer-name,protected-access,too-many-lines @pytest.fixture @@ -60,7 +58,7 @@ class TestServoOutputRecommendations: # pylint: disable=too-many-public-methods def test_output_connection_types_use_the_canonical_pwm_output_choices(self) -> None: """The servo model uses the same output labels as vehicle-component validation.""" - assert SERVO_OUT_PWM_PORTS is PWM_OUT_PORTS + assert SERVO_OUT_PWM_PORTS == PWM_OUT_PORTS def test_main_out_quad_starts_motor_functions_at_first_servo_output(self, servo_model_factory, caplog) -> None: """ @@ -206,6 +204,10 @@ def test_octa_does_not_describe_motor7_as_a_tricopter_servo(self, servo_model_fa assert "tricopter" not in message.lower() + def test_recommended_message_does_not_assume_a_tricopter_yaw_servo(self) -> None: + """The default message describes motor outputs without adding tricopter guidance.""" + assert ServoOutDataModel._recommended_message(1) == "Recommended 1 motor output assignment(s)." + def test_existing_nonzero_assignment_is_preserved(self, servo_model_factory) -> None: """ Existing user assignments are never overwritten. @@ -299,6 +301,68 @@ def test_tricopter_yaw_skips_pinned_output_overwritten_by_a_later_step(self, ser assert "SERVO7_FUNCTION" not in recommendations assert "SERVO7_FUNCTION (14_later_setup.param)" in message + def test_recommendations_resume_after_assigning_a_pinned_motor(self, servo_model_factory) -> None: + """A pinned motor assignment does not prevent assigning the remaining motors.""" + model = servo_model_factory("Main Out", 1) + + recommendations = model._recommend_assignments((1, 2), (1, 2), {}, pinned={33: 1}) + + assert recommendations == {"SERVO1_FUNCTION": 33, "SERVO2_FUNCTION": 34} + + def test_recommendations_assign_each_motor_function_only_once(self, servo_model_factory) -> None: + """Duplicate layout entries cannot route one motor function to multiple outputs.""" + model = servo_model_factory("Main Out", 1) + + recommendations = model._recommend_assignments((1, 2), (1, 1), {}) + + assert recommendations == {"SERVO1_FUNCTION": 33} + + def test_missing_connection_type_defaults_to_empty_text(self, servo_model_factory) -> None: + """Missing ESC connection type is treated as an unselected value.""" + model = servo_model_factory("Main Out", 1) + del model._local_filesystem.vehicle_components_fs.data["Components"]["ESC"]["FC->ESC Connection"]["Type"] + + assert model._get_connection_type() == "" + + def test_future_function_scan_continues_after_malformed_file_parameters(self, servo_model_factory) -> None: + """Malformed later-step data does not hide valid servo assignments in subsequent files.""" + model = servo_model_factory("Main Out", 1) + model._parameter_editor.current_file = "10_servo_out.param" + model._local_filesystem.file_parameters = { + "10_servo_out.param": ParDict(), + "12_malformed.param": None, + "14_later_setup.param": ParDict({"SERVO1_FUNCTION": Par(0)}), + } + + assert model._future_step_function_files() == {"SERVO1_FUNCTION": "14_later_setup.param"} + + def test_future_function_scan_ignores_names_that_are_not_servo_function_parameters(self, servo_model_factory) -> None: + """Only complete SERVOx_FUNCTION names block future output assignments.""" + model = servo_model_factory("Main Out", 1) + model._parameter_editor.current_file = "10_servo_out.param" + model._local_filesystem.file_parameters = { + "10_servo_out.param": ParDict(), + "14_later_setup.param": ParDict({"OTHER_FUNCTION": Par(1), "SERVO1_LABEL": Par(2)}), + } + + assert model._future_step_function_files() == {} + + def test_future_function_scan_returns_empty_when_current_file_is_not_saved(self, servo_model_factory) -> None: + """A current file absent from saved project order has no future assignments.""" + model = servo_model_factory("Main Out", 1) + model._parameter_editor.current_file = "10_servo_out.param" + model._local_filesystem.file_parameters = {"14_later_setup.param": ParDict({"SERVO1_FUNCTION": Par(0)})} + + assert model._future_step_function_files() == {} + + def test_future_function_scan_handles_unavailable_saved_parameters(self, servo_model_factory) -> None: + """Unavailable saved parameter data yields no future output blockers.""" + model = servo_model_factory("Main Out", 1) + model._parameter_editor.current_file = "10_servo_out.param" + model._local_filesystem.file_parameters = None + + assert model._future_step_function_files() == {} + def test_malformed_frame_component_data_returns_a_recommendation_error(self, servo_model_factory) -> None: """Malformed nested vehicle data falls back to a clear unsupported-frame result.""" model = servo_model_factory("Main Out", 1) @@ -533,7 +597,7 @@ def test_complete_mapping_has_a_semantic_no_changes_status(self, servo_model_fac class TestServoOutputApplication: """Test applying recommendations to the current configuration file.""" - def test_user_can_add_and_apply_missing_motor_functions(self) -> None: + def test_user_can_add_and_apply_missing_motor_functions(self, tmp_path: Path) -> None: """ Missing parameters are added and receive their recommended motor functions. @@ -542,23 +606,36 @@ def test_user_can_add_and_apply_missing_motor_functions(self) -> None: THEN: The four parameters are added and updated with Motor1 through Motor4 """ # Arrange (Given) - editor = MagicMock() - editor.fc_parameters = {"FRAME_CLASS": 1} - editor.current_step_parameters = {} - editor.add_parameter_to_current_file.return_value = True - editor.update_parameter_value.return_value = SimpleNamespace(status=ParameterValueUpdateStatus.UPDATED) - filesystem = SimpleNamespace( - vehicle_components_fs=SimpleNamespace(data={"Components": {"ESC": {"FC->ESC Connection": {"Type": "Main Out"}}}}) + expected_functions = { + "SERVO1_FUNCTION": 33, + "SERVO2_FUNCTION": 34, + "SERVO3_FUNCTION": 35, + "SERVO4_FUNCTION": 36, + } + controller = MagicMock() + controller.fc_parameters = {"FRAME_CLASS": 1.0, **dict.fromkeys(expected_functions, 0.0)} + filesystem = LocalFilesystem( + str(tmp_path), + "ArduCopter", + "4.6.3", + allow_editing_template_files=False, + save_component_to_system_templates=False, + load_project=False, ) + filesystem.vehicle_components_fs.data = {"Components": {"ESC": {"FC->ESC Connection": {"Type": "Main Out"}}}} + current_file = "07_servo_outputs.param" + filesystem.file_parameters[current_file] = ParDict() + editor = ParameterEditor(current_file, controller, filesystem) model = ServoOutDataModel(filesystem, editor) # Act (When) - applied, _message, _status = model.apply_recommendations() + applied, message, status = model.apply_recommendations() # Assert (Then) - assert applied == ["SERVO1_FUNCTION", "SERVO2_FUNCTION", "SERVO3_FUNCTION", "SERVO4_FUNCTION"] - assert editor.add_parameter_to_current_file.call_count == 4 - assert editor.update_parameter_value.call_args_list[0].args == ("SERVO1_FUNCTION", "33") + assert applied == list(expected_functions) + assert status is ServoOutRecommendationStatus.APPLIED + assert message == "Applied 4 motor output assignment(s)." + assert {name: par.value for name, par in editor.get_parameters_as_par_dict().items()} == expected_functions def test_partial_application_names_assignments_that_could_not_be_applied(self) -> None: """ diff --git a/tests/plugins/test_gnss.py b/tests/plugins/test_gnss.py index bf12b1787..1ba570a6a 100755 --- a/tests/plugins/test_gnss.py +++ b/tests/plugins/test_gnss.py @@ -132,6 +132,18 @@ def test_time_secondary_receiver_and_stale_data_remain_independent(sample: Telem assert model.update(sample)[0][1] == "N/A" +def test_missing_target_system_uses_the_default_system_zero(sample: TelemetrySample) -> None: + """Use the MAVLink default system ID when a telemetry connection omits its target.""" + message = sample.messages[(1, 1, "GPS_RAW_INT")] + sample = replace( + sample, + connection=SimpleNamespace(), + messages={(0, 1, "GPS_RAW_INT"): message}, + ) + + assert GnssDataModel(MagicMock()).update(sample)[0][1] == "52.1234567" + + def test_monitor_requests_and_parses_real_gnss_packets_without_changing_stream_rates(link: SimpleNamespace) -> None: """ Shared reception provides real telemetry without blocking acknowledgment waits. diff --git a/tests/plugins/unit_data_model_battery_monitor.py b/tests/plugins/unit_data_model_battery_monitor.py index c7a75878e..a8d2a8975 100755 --- a/tests/plugins/unit_data_model_battery_monitor.py +++ b/tests/plugins/unit_data_model_battery_monitor.py @@ -20,6 +20,7 @@ import pytest from pymavlink.dialects.v20 import ardupilotmega as mavlink2 +from ardupilot_methodic_configurator import _ from ardupilot_methodic_configurator.backend_flightcontroller import FlightController from ardupilot_methodic_configurator.backend_flightcontroller_business_logic import get_battery_parameter_prefix from ardupilot_methodic_configurator.backend_flightcontroller_commands import FlightControllerCommands @@ -318,6 +319,22 @@ def test_failed_interval_change_is_retried_while_cached_readings_continue( assert [call.args[0] for call in fc.request_periodic_battery_status.call_args_list] == [71428, 71428] +def test_stopping_active_monitor_logs_and_keeps_the_configured_interval( + connected_flight_controller_with_battery_enabled: MagicMock, caplog: pytest.LogCaptureFixture +) -> None: + """Record the active interval and log when battery monitoring is stopped.""" + model = BatteryMonitorDataModel(connected_flight_controller_with_battery_enabled) + assert model.get_battery_statuses() == {0: (12.4, 2.1)} + interval = model._battery_status_interval_microseconds + assert interval == 500000 + + with caplog.at_level("DEBUG"): + model.stop_monitoring() + + assert model._battery_status_interval_microseconds == interval + assert caplog.messages == [_("Battery monitoring stopped")] + + def test_replaced_connection_requests_battery_stream_despite_default_readings( connected_flight_controller_with_battery_enabled: MagicMock, ) -> None: diff --git a/tests/plugins/unit_data_model_compass_calibration.py b/tests/plugins/unit_data_model_compass_calibration.py index 13aadcc6c..a2ae415e9 100755 --- a/tests/plugins/unit_data_model_compass_calibration.py +++ b/tests/plugins/unit_data_model_compass_calibration.py @@ -216,6 +216,26 @@ def test_user_can_detect_multiple_active_compasses_from_flight_controller_parame assert connected_compass_calibration_model.get_active_compass_ids() == [0, 1, 3] + def test_duplicate_compass_flags_return_each_compass_id_once( + self, connected_compass_calibration_model: CompassCalibrationDataModel, connected_flight_controller: MagicMock + ) -> None: + """ + Aliased flags for one compass do not duplicate its calibration target. + + GIVEN: Multiple enabled parameter names resolve to the same compass id + WHEN: The enabled compass list is requested + THEN: Each active id appears once in ascending order + """ + connected_flight_controller.fc_parameters = { + "COMPASS_ENABLE": 1, + "COMPASS_USE": 1, + "COMPASS_USE1": 1, + "COMPASS_USE3": 1, + "COMPASS_USE2": 1, + } + + assert connected_compass_calibration_model.get_active_compass_ids() == [0, 1, 2] + def test_user_sees_no_active_compasses_when_compass_calibration_is_disabled( self, connected_compass_calibration_model: CompassCalibrationDataModel, connected_flight_controller: MagicMock ) -> None: diff --git a/tests/test_backend_data_telemetry.py b/tests/test_backend_data_telemetry.py index 0a760c426..f3aa4e1e0 100755 --- a/tests/test_backend_data_telemetry.py +++ b/tests/test_backend_data_telemetry.py @@ -33,9 +33,10 @@ MessageSample, RadioSample, TelemetrySample, + TelemetryState, ) -# pylint: disable=protected-access,redefined-outer-name +# pylint: disable=protected-access,redefined-outer-name,too-many-lines @pytest.fixture @@ -817,6 +818,59 @@ def test_radio_error_rate_is_unavailable_when_reports_are_three_seconds_apart() assert state.radio_error_rate is None +def test_telemetry_model_initialization_and_clear_reset_live_state() -> None: + """Start with an empty state and clear both the snapshot and cached readings.""" + model = DataTelemetryDataModel(MagicMock()) + assert model._previous is None + assert model._state == TelemetryState() + + connection = object() + model.update(TelemetrySample(connection, 0, rx_bytes=10)) + model.clear_live_data() + + assert model._previous is None + assert model._state == TelemetryState() + + +def test_telemetry_model_baseline_produces_byte_and_error_rates() -> None: + """Measure cumulative counters only after a same-connection baseline.""" + model = DataTelemetryDataModel(MagicMock()) + connection = object() + baseline = TelemetrySample(connection, 0, rx_bytes=100, tx_bytes=50, parse_errors=2) + assert model.update(baseline).connected is True + + measured = model.update(TelemetrySample(connection, 1, rx_bytes=130, tx_bytes=62, parse_errors=4)) + + assert (measured.rx_rate, measured.tx_rate, measured.parse_error_rate) == (30, 12, 2) + + +def test_radio_counter_rewind_discards_the_previous_rate_baseline() -> None: + """Do not calculate a rate against a modem count superseded by a reset.""" + model = DataTelemetryDataModel(MagicMock()) + connection = object() + radio = RadioSample((51, 68), 0, 30, 40, 0, 0, 100, 10, 2) + model.update(TelemetrySample(connection, 0, radio=radio)) + model.update(TelemetrySample(connection, 0.5, radio=replace(radio, time=0.5, rxerrors=12))) + + reset = model.update(TelemetrySample(connection, 1, radio=replace(radio, time=1, rxerrors=11))) + + assert reset.radio_error_rate is None + + +def test_radio_counter_rewind_rebaselines_before_next_measured_interval() -> None: + """Use the rewound counter sample as the next radio-rate baseline.""" + model = DataTelemetryDataModel(MagicMock()) + connection = object() + radio = RadioSample((51, 68), 0, 30, 40, 0, 0, 100, 10, 2) + model.update(TelemetrySample(connection, 0, radio=radio)) + model.update(TelemetrySample(connection, 0.5, radio=replace(radio, time=0.5, rxerrors=12))) + model.update(TelemetrySample(connection, 0.75, radio=replace(radio, time=0.75, rxerrors=11))) + + recovered = model.update(TelemetrySample(connection, 1.25, radio=replace(radio, time=1.25, rxerrors=13))) + + assert recovered.radio_error_rate == 4 + + def test_heartbeat_sender_reuses_the_existing_encoder_lock_and_preserves_requested_mavlink_version( telemetry_link: SimpleNamespace, ) -> None: diff --git a/tests/test_backend_flightcontroller_connection.py b/tests/test_backend_flightcontroller_connection.py index 3a762f98a..62f0636b9 100755 --- a/tests/test_backend_flightcontroller_connection.py +++ b/tests/test_backend_flightcontroller_connection.py @@ -26,7 +26,6 @@ from ardupilot_methodic_configurator.backend_flightcontroller_connection import ( DEFAULT_BAUDRATE, SUPPORTED_BAUDRATES, - FakeSerialForTests, FlightControllerConnection, ) from ardupilot_methodic_configurator.backend_flightcontroller_factory_mavlink import ( @@ -1117,68 +1116,6 @@ def test_connection_with_progress_callback_none(self) -> None: assert conn.progress_callback is None -class TestFakeSerialForTests: - """Test the FakeSerialForTests helper class used in unit tests.""" - - def test_read_returns_empty_string(self) -> None: - """ - FakeSerialForTests.read always returns an empty string. - - GIVEN: A FakeSerialForTests instance - WHEN: read(n) is called for any length - THEN: An empty string should be returned - """ - fake = FakeSerialForTests("/dev/ttyUSB0") - assert fake.read(0) == "" - assert fake.read(1) == "" - assert fake.read(1024) == "" - - def test_write_always_raises_exception(self) -> None: - """ - FakeSerialForTests.write always raises an Exception to simulate write failure. - - GIVEN: A FakeSerialForTests instance - WHEN: write() is called with any buffer - THEN: An Exception should be raised - """ - fake = FakeSerialForTests("/dev/ttyUSB0") - with pytest.raises(Exception, match="write always fails"): - fake.write(b"data") - - def test_in_waiting_returns_zero(self) -> None: - """ - FakeSerialForTests.inWaiting always returns zero bytes available. - - GIVEN: A FakeSerialForTests instance - WHEN: inWaiting() is called - THEN: Zero should be returned (no bytes in buffer) - """ - fake = FakeSerialForTests("/dev/ttyUSB0") - assert fake.inWaiting() == 0 - - def test_close_does_not_raise(self) -> None: - """ - FakeSerialForTests.close completes without raising. - - GIVEN: A FakeSerialForTests instance - WHEN: close() is called - THEN: No exception should be raised - """ - fake = FakeSerialForTests("/dev/ttyUSB0") - fake.close() # Must not raise - - def test_device_attribute_is_stored(self) -> None: - """ - FakeSerialForTests stores the device string passed at construction. - - GIVEN: A device string passed to the constructor - WHEN: The device attribute is accessed - THEN: The same string should be returned - """ - fake = FakeSerialForTests("COM3") - assert fake.device == "COM3" - - class TestFlightControllerConnectionLinuxSoftlink: """Test Linux-specific soft link resolution in connect().""" diff --git a/tests/test_data_model_ardupilot_parameter.py b/tests/test_data_model_ardupilot_parameter.py index 2d9e09d1b..081440ed6 100755 --- a/tests/test_data_model_ardupilot_parameter.py +++ b/tests/test_data_model_ardupilot_parameter.py @@ -587,8 +587,9 @@ def test_set_forced_or_derived_value(param_fixture) -> None: ) # Act & Assert: System attempting to use method on regular parameter fails - with pytest.raises(ValueError, match="This method is only for forced or derived parameters"): + with pytest.raises(ValueError, match="only for forced or derived") as error: regular_param.set_forced_or_derived_value(123.0) + assert str(error.value) == "This method is only for forced or derived parameters." def test_fc_value_equals_default_value_for_bitmask_parameter(param_fixture) -> None: @@ -659,8 +660,9 @@ def test_set_new_value_bitmask_unchanged_raises() -> None: } param = ArduPilotParameter("BM_PARAM", Par(3.0, ""), bitmask_metadata) - with pytest.raises(ParameterUnchangedError): + with pytest.raises(ParameterUnchangedError) as error: param.set_new_value("3") + assert str(error.value) == "The provided bitmask value for BM_PARAM would not change the parameter." def test_set_new_value_bitmask_ignores_unknown_bits_when_flag_set() -> None: @@ -733,8 +735,9 @@ def test_set_forced_or_derived_value_readonly_raises() -> None: forced_par=Par(1.0, ""), ) - with pytest.raises(ValueError, match="Readonly"): + with pytest.raises(ValueError, match="Readonly parameters") as error: param.set_forced_or_derived_value(2.0) + assert str(error.value) == "Readonly parameters cannot be forced or derived." def test_set_forced_or_derived_change_reason_readonly_raises() -> None: @@ -758,8 +761,9 @@ def test_set_forced_or_derived_change_reason_readonly_raises() -> None: derived_par=Par(1.0, ""), ) - with pytest.raises(ValueError, match="Readonly"): + with pytest.raises(ValueError, match="Readonly parameters") as error: param.set_forced_or_derived_change_reason("new reason") + assert str(error.value) == "Readonly parameters cannot be forced or derived." def test_bitmask_helper_get_checked_keys() -> None: @@ -1131,8 +1135,9 @@ def test_set_forced_or_derived_change_reason(param_fixture) -> None: ) # Act & Assert: System attempting to use method on regular parameter fails - with pytest.raises(ValueError, match="This method is only for forced or derived parameters"): + with pytest.raises(ValueError, match="only for forced or derived") as error: regular_param.set_forced_or_derived_change_reason("Some reason") + assert str(error.value) == "This method is only for forced or derived parameters." def test_forced_or_derived_setters_make_parameter_dirty(param_fixture) -> None: @@ -1245,3 +1250,133 @@ def test_set_fc_value_maintains_comparison_state() -> None: # Assert: No longer different assert param.is_different_from_fc is False + + +@pytest.mark.parametrize("value", [math.nan, math.inf, -math.inf]) +def test_invalid_numbers_name_the_parameter_for_every_nonfinite_value(value: float) -> None: + """Given NaN or either infinity, return the same finite-number guidance with the parameter name.""" + param = ArduPilotParameter("TEST_NUMBER", Par(1.0, "")) + + assert param.is_invalid_number(value) == "The value for TEST_NUMBER must be a finite number." + + +def test_bitmask_validation_identifies_unknown_bits_and_ignores_missing_fc_values() -> None: + """Given an undeclared bit or absent controller value, report only actual unknown staged bits.""" + metadata = {"Bitmask": {1: "Second option"}, "ReadOnly": False} + param = ArduPilotParameter("TEST_MASK", Par(1.0, ""), metadata) + + assert param.has_unknown_bits_set() == "The value for TEST_MASK contains unknown bit(s)." + + missing_fc = ArduPilotParameter("TEST_MASK", Par(4.0, ""), {"Bitmask": {0: "First option"}}) + assert missing_fc.fc_value_has_unknown_bits_set() == "" + + +def test_missing_fc_value_does_not_reuse_an_out_of_range_staged_value() -> None: + """Given a staged value below minimum and no FC value, do not show controller feedback.""" + param = ArduPilotParameter("TEST_LIMIT", Par(0.0, ""), {"min": 2.0}, fc_value=None) + + assert param.fc_value_is_below_limit() == "" + + +def test_new_value_errors_include_exact_guidance_and_accept_hex_bitmasks() -> None: + """Given invalid edits, identify the parameter and preserve supported hexadecimal bitmasks.""" + forced = ArduPilotParameter("FORCED_PARAM", Par(1.0, ""), forced_par=Par(2.0, "")) + with pytest.raises(ParameterForcedOrDerivedError) as forced_error: + forced.set_new_value("3") + assert str(forced_error.value) == "This parameter is forced or derived and cannot be changed." + + with pytest.raises(TypeError) as type_error: + ArduPilotParameter("TYPE_PARAM", Par(1.0, "")).set_new_value(2) # type: ignore[arg-type] + assert str(type_error.value) == "Parameter value must be provided as a string." + + with pytest.raises(ValueError, match="Empty value") as empty_error: + ArduPilotParameter("EMPTY_PARAM", Par(1.0, "")).set_new_value(" ") + assert str(empty_error.value) == "Empty value is not allowed for EMPTY_PARAM" + + choices = ArduPilotParameter("CHOICE_PARAM", Par(1.0, ""), {"values": {"1": "One", "2": "Two"}}) + with pytest.raises(ParameterUnchangedError) as choice_error: + choices.set_new_value("1") + assert str(choice_error.value) == "The provided value for CHOICE_PARAM would not change the parameter." + + bitmask = ArduPilotParameter("MASK_PARAM", Par(0.0, ""), {"Bitmask": {1: "Second option"}}) + assert bitmask.set_new_value("0x2") == 2.0 + with pytest.raises(ParameterOutOfRangeError) as unknown_bit_error: + bitmask.set_new_value("0x4") + assert str(unknown_bit_error.value) == "The value for MASK_PARAM contains unknown bit(s)." + + with pytest.raises(ValueError, match="integer for bitmask") as bitmask_error: + bitmask.set_new_value("not-an-integer") + assert str(bitmask_error.value) == "The value for MASK_PARAM must be an integer for bitmask parameters." + + +def test_numeric_new_value_errors_include_exact_parameter_context() -> None: + """Given invalid, nonfinite, unchanged or out-of-range numeric edits, return stable guidance.""" + param = ArduPilotParameter("NUM_PARAM", Par(5.0, ""), {"min": 2.0, "max": 8.0}) + + with pytest.raises(ValueError, match="must be a number") as format_error: + param.set_new_value("not-a-number") + assert str(format_error.value) == "The value for NUM_PARAM must be a number." + + with pytest.raises(ValueError, match="finite number") as finite_error: + param.set_new_value("inf") + assert str(finite_error.value) == "The value for NUM_PARAM must be a finite number." + + with pytest.raises(ParameterUnchangedError) as unchanged_error: + param.set_new_value("5.0") + assert str(unchanged_error.value) == ( + "The provided numeric value for NUM_PARAM is within tolerance and would not change the parameter." + ) + + with pytest.raises(ParameterOutOfRangeError) as range_error: + param.set_new_value("9.0") + assert str(range_error.value) == "The value for NUM_PARAM (9.0) should be smaller than 8.0\n" + + +@pytest.mark.parametrize("forced", [True, False]) +def test_manual_override_restores_forced_or_derived_values_and_blank_reasons(forced: bool) -> None: + """Given a forced or derived value, toggle manual editing and restore its exact configured state.""" + parameter = ArduPilotParameter( + "OVERRIDE_PARAM", + Par(7.0, "file reason"), + forced_par=Par(3.0, "") if forced else None, + derived_par=Par(4.0, "") if not forced else None, + ) + + parameter.set_manual_override(True) + assert parameter.is_manual_override is True + assert parameter.get_new_value() == (3.0 if forced else 4.0) + assert parameter.change_reason == "" + + parameter.set_new_value("6.0") + parameter.set_change_reason("manual reason") + parameter.set_manual_override(False) + + assert parameter.is_manual_override is False + assert parameter.get_new_value() == (3.0 if forced else 4.0) + assert parameter.change_reason == "" + + +def test_manual_override_reloads_values_and_reason_already_saved_in_the_file() -> None: + """Given a persisted manual override, re-enabling it restores the file value and reason.""" + parameter = ArduPilotParameter( + "OVERRIDE_PARAM", + Par(7.0, "@manual_override previous user reason"), + forced_par=Par(3.0, "forced reason"), + ) + + parameter.set_manual_override(False) + parameter.set_manual_override(True) + + assert parameter.is_manual_override is True + assert parameter.get_new_value() == 7.0 + assert parameter.change_reason == "previous user reason" + + +def test_manual_override_rejects_regular_parameters_with_actionable_error() -> None: + """Given a regular parameter, manual override explains that only forced values are eligible.""" + parameter = ArduPilotParameter("REGULAR_PARAM", Par(1.0, "")) + + with pytest.raises(ValueError, match="only applicable to forced or derived") as error: + parameter.set_manual_override(True) + + assert str(error.value) == "Manual override is only applicable to forced or derived parameters." diff --git a/tests/test_data_model_configuration_step.py b/tests/test_data_model_configuration_step.py index ea8eb3584..7eb7c8ffd 100755 --- a/tests/test_data_model_configuration_step.py +++ b/tests/test_data_model_configuration_step.py @@ -341,6 +341,13 @@ def test_connection_rename_feedback_identifies_each_changed_parameter_without_ch assert duplicates == set() assert renames == [("SERIAL1_PROTOCOL", "SERIAL3_PROTOCOL"), ("SERIAL1_BAUD", "SERIAL3_BAUD")] assert len(infos) == 2 + assert infos[1] == ( + "Parameter Renamed", + ( + "The parameter 'SERIAL1_BAUD' was renamed to 'SERIAL3_BAUD'.\n" + "to obey the flight controller connection defined in the component editor window." + ), + ) logged_messages = [record.getMessage() for record in caplog.records if record.levelno == INFO] for (title, message), (old_name, new_name) in zip(infos, renames, strict=True): assert title == "Parameter Renamed" @@ -372,6 +379,9 @@ def test_failed_connection_expression_reports_the_missing_input_and_leaves_opera assert renames == [] assert "missing_connection_choice" in caplog.text assert "NameNotDefined" in caplog.text + assert any( + record.getMessage().startswith("Skipping connection renaming because evaluation failed:") for record in caplog.records + ) @pytest.fixture @@ -1251,6 +1261,19 @@ def test_generate_connection_renames_single_digit_still_works(self) -> None: # Assert assert renames == {"CAN1_DRIVER": "CAN2_DRIVER"} + def test_generate_connection_renames_short_can_names_and_replaces_only_prefix(self) -> None: + """CAN port names with no suffix still rename, while later prefix text stays unchanged.""" + parameters = ["CAN_P1", "CAN_D1", "CAN_P1_CAN_P1"] + + renames = ConfigurationStepProcessor._generate_connection_renames(parameters, "CAN3") + + assert renames == { + "CAN_P1": "CAN_P3", + "CAN_D1": "CAN_D3", + "CAN_P1_CAN_P1": "CAN_P3_CAN_P1", + } + assert ConfigurationStepProcessor._generate_connection_renames(["BRD_SER1"], "SERIAL3") == {"BRD_SER1": "BRD_SER3"} + def test_generate_connection_renames_invalid_prefix_returns_empty(self) -> None: """ A prefix with no trailing digits returns an empty rename dict. @@ -1423,6 +1446,11 @@ def test_user_receives_expresslrs_warning_when_fltmode_ch_is_5_and_expresslrs_de assert ui_infos[0][0] == "ExpressLRS Configuration Warning" assert "FLTMODE_CH must be set to a channel other than 5" in ui_infos[0][1] assert "RC5 arming channel" in ui_infos[0][1] + assert ui_infos[0][1] == ( + "FLTMODE_CH must be set to a channel other than 5 (currently set to 5).\n" + "Please change FLTMODE_CH to a different channel (e.g., 6, 7, 8, etc.)\n" + "to avoid conflicts with the required RC5 arming channel." + ) assert ui_errors == [] def test_user_does_not_receive_expresslrs_warning_when_fltmode_ch_is_not_5_and_expresslrs_detected( @@ -1749,6 +1777,8 @@ def test_deleted_parameter_is_not_auto_imported_from_fc(self, processor) -> None if passed_delete_set is None and len(call_kwargs.args) > 4: passed_delete_set = call_kwargs.args[4] assert passed_delete_set == {"BATT_OPTIONS"} + assert call_kwargs.args[0] == selected_file + assert processor.local_filesystem.compute_deletions.call_args.args[0] == selected_file def test_apply_auto_imports_skips_parameters_in_delete_set(self, processor) -> None: """ diff --git a/tests/test_data_model_fc_diagnostics.py b/tests/test_data_model_fc_diagnostics.py index 614a76ade..9386eb59a 100755 --- a/tests/test_data_model_fc_diagnostics.py +++ b/tests/test_data_model_fc_diagnostics.py @@ -18,6 +18,8 @@ from ardupilot_methodic_configurator import data_model_fc_diagnostics as diagnostics +# pylint: disable=protected-access + def test_long_status_text_preserves_utf8_and_spaces_across_chunks() -> None: """GIVEN split UTF-8 text, WHEN all chunks arrive, THEN one intact diagnostic is returned.""" @@ -107,6 +109,51 @@ def test_device_rows_show_only_present_devices_with_formatted_names_and_types() ] +def test_device_category_requires_accelerometer_or_gyroscope_for_imu() -> None: + """Ignore unrelated INS parameters and retain normalized sensor categories.""" + assert diagnostics._device_category("BARO1_DEVID") == "baro" + assert diagnostics._device_category("ARBITRARY_ACC") is None + assert diagnostics._device_category("ARSPD_DEVID") == "airspeed" + + +def test_compass_priority_accepts_device_id_range_boundaries() -> None: + """Compass IDs at both valid 24-bit boundaries keep their configured priorities.""" + assert diagnostics._compass_priorities( + { + "COMPASS_PRIO1_ID": 0, + "COMPASS_PRIO2_ID": 1, + "COMPASS_PRIO3_ID": 0x00FFFFFF, + "COMPASS_PRIO4_ID": 0x01000000, + } + ) == {1: 2, 0x00FFFFFF: 3} + + +def test_device_rows_include_the_lowest_positive_device_id() -> None: + """Device ID one is valid and must not be excluded by a stricter lower bound.""" + rows = diagnostics.device_rows({"COMPASS_DEV_ID": 1}) + + assert rows == [("COMPASS1", "I2C", 0, 0, "UNKNOWN", None, "COMPASS_DEV_ID: 1")] + + +def test_device_rows_skip_an_invalid_id_before_processing_a_valid_device() -> None: + """Skip out-of-range device IDs without discarding later valid devices.""" + rows = diagnostics.device_rows({"COMPASS_DEV_ID": 0x01000000, "COMPASS_DEV_ID2": 1}) + + assert rows == [("COMPASS2", "I2C", 0, 0, "UNKNOWN", None, "COMPASS_DEV_ID2: 1")] + + +def test_equal_device_names_keep_parameter_order() -> None: + """Stable name sorting preserves input order for two rows with the same display name.""" + compass_two_id = (7 << 16) | (30 << 8) | (2 << 3) | 1 + compass_one_id = (6 << 16) | (118 << 8) | (1 << 3) | 1 + parameters = {"COMPASS_DEV_ID": compass_two_id, "COMPASS_DEV_ID1": compass_one_id} + + rows = diagnostics.device_rows(parameters) + + assert [row[0] for row in rows] == ["COMPASS1", "COMPASS1"] + assert [row[3] for row in rows] == [30, 118] + + @pytest.mark.parametrize("parameter_name", ["INS4_ACC_ID", "INS4_GYR_ID", "INS5_ACC_ID", "INS5_GYR_ID"]) def test_device_rows_include_fourth_and_fifth_imu(parameter_name: str) -> None: """GIVEN an extra IMU ID, WHEN diagnostics opens, THEN its device and IMU type are displayed.""" @@ -345,6 +392,32 @@ def test_standalone_text_transports_decode_utf8_and_discard_null_padding(text: s assert diagnostics.StatusTextAssembler().assemble(SimpleNamespace(text=text)) == "café" +def test_missing_text_attribute_defaults_to_an_empty_payload() -> None: + """A message without either wire bytes or a text field has no diagnostic text.""" + assert diagnostics.status_text_bytes(object()) == b"" + + +@pytest.mark.parametrize("other_source", [(1, 0), (0, 1)]) +def test_missing_source_chunks_do_not_mix_with_a_real_zero_component( + other_source: tuple[int, int], +) -> None: + """Anonymous STATUSTEXT chunks remain separate from a real vehicle/component source.""" + assembler = diagnostics.StatusTextAssembler() + anonymous_start = SimpleNamespace(id=42, chunk_seq=0, _text_raw=b"A" * 50) + sourced_start = SimpleNamespace( + id=42, + chunk_seq=0, + _text_raw=b"B" * 50, + get_srcSystem=lambda: other_source[0], + get_srcComponent=lambda: other_source[1], + ) + anonymous_end = SimpleNamespace(id=42, chunk_seq=1, _text_raw=b"A tail") + + assert assembler.assemble(anonymous_start) is None + assert assembler.assemble(sourced_start) is None + assert assembler.assemble(anonymous_end) == "A" * 50 + "A tail" + + @pytest.mark.parametrize(("system", "component"), [(None, None), (1, None), (None, 1), ("1", 1), (1, "1")]) def test_incomplete_source_identifiers_are_reported_as_unknown(system: object, component: object) -> None: """ diff --git a/tests/test_data_model_firmware_upload.py b/tests/test_data_model_firmware_upload.py index ace10c18a..65469086a 100755 --- a/tests/test_data_model_firmware_upload.py +++ b/tests/test_data_model_firmware_upload.py @@ -341,19 +341,22 @@ def test_dual_region_upload_can_return_to_erasing_for_the_internal_image(self) - @pytest.mark.parametrize("stage", [fw.UploadStage.ERASING, fw.UploadStage.PROGRAMMING, fw.UploadStage.VERIFYING]) def test_user_cannot_cancel_once_the_flash_is_being_written(self, stage: fw.UploadStage) -> None: - with pytest.raises(ValueError, match="cannot cancel"): + with pytest.raises(ValueError, match=f"cannot cancel during {stage.value}") as error: fw.next_stage(stage, fw.UploadStage.CANCELLED) + assert str(error.value) == f"cannot cancel during {stage.value}" def test_any_stage_can_fail(self) -> None: assert fw.next_stage(fw.UploadStage.PROGRAMMING, fw.UploadStage.FAILED) is fw.UploadStage.FAILED def test_skipping_a_stage_is_rejected(self) -> None: - with pytest.raises(ValueError, match="illegal transition"): + with pytest.raises(ValueError, match="illegal transition inspecting -> erasing") as error: fw.next_stage(fw.UploadStage.INSPECTING, fw.UploadStage.ERASING) + assert str(error.value) == "illegal transition inspecting -> erasing" def test_terminal_stages_do_not_move(self) -> None: - with pytest.raises(ValueError, match="terminal"): + with pytest.raises(ValueError, match="completed is terminal") as error: fw.next_stage(fw.UploadStage.COMPLETED, fw.UploadStage.IDLE) + assert str(error.value) == "completed is terminal" class FakeBootloader: diff --git a/tests/test_data_model_mavlink_inspector.py b/tests/test_data_model_mavlink_inspector.py index e67bb6685..7ad69bf75 100755 --- a/tests/test_data_model_mavlink_inspector.py +++ b/tests/test_data_model_mavlink_inspector.py @@ -55,6 +55,7 @@ def test_each_heading_sorts_by_its_meaning_and_reverses( THEN its ascending order reverses without comparing formatted strings. """ model = MavlinkInspectorDataModel() + assert model.sort_descending is False model.update(TelemetryState(messages=messages)) assert model.rows == messages model.sort_by(column) @@ -244,6 +245,8 @@ def test_empty_inspector_can_be_read_and_sorted_before_telemetry_arrives(column: model = MavlinkInspectorDataModel() assert not model.rows + assert model.sort_column is None + assert model.sort_descending is False assert model.fields("1:1:HEARTBEAT") == "" if column is not None: model.sort_by(column) diff --git a/tests/test_data_model_par_dict.py b/tests/test_data_model_par_dict.py index 556969f6e..0958fa9e3 100755 --- a/tests/test_data_model_par_dict.py +++ b/tests/test_data_model_par_dict.py @@ -22,7 +22,6 @@ import pytest import ardupilot_methodic_configurator.data_model_par_dict as par_dict_module -from ardupilot_methodic_configurator import _ from ardupilot_methodic_configurator.data_model_par_dict import ( Par, ParamFileError, @@ -45,6 +44,9 @@ (b"A\0B\0C\0", 2, (1,), True), (b"A\0B\x01", 2, (1,), False), (b"\0A\0B", 2, (0,), True), + (b"A\0B", 2, (1,), False), + (b"A\x01\0\0", 4, (1, 2, 3), False), + (b"\x01\0\0A", 4, (0, 1, 2), False), ], ) def test_fixed_width_encoding_detection_checks_complete_zero_byte_pattern( @@ -60,10 +62,13 @@ def test_fixed_width_encoding_detection_checks_complete_zero_byte_pattern( (b"\xff\xfeA\0", "utf-16"), (b"\xfe\xff\0A", "utf-16"), (b"\xff\xfe\0\0A\0\0\0", "utf-32"), + (b"\0\0\xfe\xff\0\0\0A", "utf-32"), (b"A\0B\0", "utf-16-le"), (b"\0A\0B", "utf-16-be"), (b"A\0\0\0B\0\0\0", "utf-32-le"), (b"\0\0\0A\0\0\0B", "utf-32-be"), + (b"A\x01\0\0A\x01\0\0", "utf-8-sig"), + (b"\x01\0\0A\x01\0\0A", "utf-8-sig"), (b"PARAM,1.0\n", "utf-8-sig"), ], ) @@ -72,6 +77,20 @@ def test_parameter_file_encoding_detection_handles_boms_and_ascii_layouts(sample assert _detect_param_file_encoding(sample) == expected +def test_loader_detects_utf16_when_non_ascii_text_appears_after_the_sample_window() -> None: + """A later Unicode comment does not change the encoding inferred from the ASCII header.""" + contents = "".join(f"P{index},1.0\n" for index in range(40)) + "# あ\n" + with tempfile.NamedTemporaryFile(mode="wb", suffix=".param", delete=False) as parameter_file: + parameter_file.write(contents.encode("utf-16-le")) + file_path = parameter_file.name + + try: + loaded = ParDict.load_param_file_into_dict(file_path) + assert loaded == {f"P{index}": Par(1.0) for index in range(40)} + finally: + os.unlink(file_path) + + def test_editing_a_parameter_copy_preserves_the_original_snapshot() -> None: """ Preserve the loaded snapshot while derived parameters are edited independently. @@ -121,6 +140,38 @@ def test_absolute_tolerance_accepts_its_exact_boundary() -> None: assert not is_within_tolerance(2.001, 1.0, atol=1.0, rtol=0.0) +def test_custom_tolerance_is_used_for_both_mutating_and_non_mutating_comparisons() -> None: + """Custom value tolerances consistently filter near-equal parameters.""" + current = ParDict({"NEAR": Par(1.0005), "DIFFERENT": Par(2.0)}) + comparison = ParDict({"NEAR": Par(1.0), "DIFFERENT": Par(2.1)}) + + def within_one_mill(self_value: float, other_value: float) -> bool: + return abs(self_value - other_value) <= 0.001 + + assert current.get_missing_or_different(comparison, within_one_mill) == {"DIFFERENT": Par(2.0)} + + current.remove_if_value_is_similar(comparison, within_one_mill) + + assert current == {"DIFFERENT": Par(2.0)} + + +def test_documentation_filters_treat_missing_flags_as_false() -> None: + """Missing read-only and calibration flags do not classify a parameter.""" + parameters = ParDict({"READONLY": Par(1), "CALIBRATION": Par(2), "UNSPECIFIED": Par(3)}) + documentation = { + "READONLY": {"ReadOnly": True}, + "CALIBRATION": {"Calibration": True}, + "UNSPECIFIED": {}, + } + + readonly, calibration, ids, other = parameters.categorize_by_documentation(documentation, ParDict()) + + assert readonly == {"READONLY": Par(1)} + assert calibration == {"CALIBRATION": Par(2)} + assert not ids + assert other == {"UNSPECIFIED": Par(3)} + + @pytest.fixture def sample_par_objects() -> dict[str, Par]: """Fixture providing realistic Par objects for testing.""" @@ -609,8 +660,10 @@ def test_user_receives_guidance_when_parameter_file_is_not_utf8(self) -> None: bad_file = f.name try: - with pytest.raises(ParamFileError, match="UTF-8"): + with pytest.raises(ParamFileError) as exc_info: ParDict.load_param_file_into_dict(bad_file) + prefix = f"Fatal error reading {bad_file}, file must be UTF-8, UTF-16, or UTF-32 encoded: " + assert str(exc_info.value) == prefix + str(exc_info.value.__cause__) finally: os.unlink(bad_file) @@ -670,7 +723,7 @@ def test_user_receives_traceback_hint_when_parameter_assignment_fails(self) -> N original_line = "ACRO_YAW_P,4.5" with ( patch.object(ParDict, "__setitem__", side_effect=OSError("disk full"), autospec=True), - pytest.raises(ParamFileError, match="Caused by line 1"), + pytest.raises(ParamFileError) as exc_info, ): ParDict._validate_parameter( # pylint: disable=protected-access "test.param", @@ -681,6 +734,30 @@ def test_user_receives_traceback_hint_when_parameter_assignment_fails(self) -> N "ACRO_YAW_P", "4.5", ) + assert str(exc_info.value) == f"Caused by line 1 of file test.param: {original_line}" + + def test_loader_includes_the_original_source_line_when_assignment_fails(self, caplog: pytest.LogCaptureFixture) -> None: + """The loader preserves the original source line for a write-failure diagnostic.""" + original_line = "ACRO_YAW_P,4.5 # source comment" + with tempfile.NamedTemporaryFile(mode="w", suffix=".param", delete=False) as f: + f.write(original_line) + f.flush() + file_path = f.name + + try: + with ( + patch.object(ParDict, "__setitem__", side_effect=OSError("disk full"), autospec=True), + pytest.raises(ParamFileError) as exc_info, + ): + ParDict.load_param_file_into_dict(file_path) + assert str(exc_info.value) == f"Caused by line 1 of file {file_path}: {original_line}" + critical_messages = [record.getMessage() for record in caplog.records if record.levelname == "CRITICAL"] + assert len(critical_messages) == 1 + assert critical_messages[0].startswith("in line ") + assert critical_messages[0].split()[2].isdigit() + assert critical_messages[0].endswith("of file data_model_par_dict.py: disk full") + finally: + os.unlink(file_path) def test_user_can_ignore_blank_and_comment_only_lines_when_loading(self) -> None: """ @@ -874,8 +951,9 @@ def test_user_receives_error_when_appending_invalid_type(self, parameter_dict) - invalid_data = {"PARAM": Par(1.0)} # Act & Assert: User gets helpful error message - with pytest.raises(TypeError, match="Can only append another ParDict instance"): + with pytest.raises(TypeError) as exc_info: parameter_dict.append(invalid_data) + assert str(exc_info.value) == "Can only append another ParDict instance" class TestParameterComparisonWorkflows: @@ -923,8 +1001,9 @@ def test_user_receives_error_when_comparing_with_invalid_type(self, parameter_di invalid_data = {"PARAM": 1.0} # Act & Assert: User gets clear error message - with pytest.raises(TypeError, match="Can only compare with another ParDict instance"): + with pytest.raises(TypeError) as exc_info: parameter_dict.remove_if_value_is_similar(invalid_data) + assert str(exc_info.value) == "Can only compare with another ParDict instance" def test_user_can_find_missing_or_different_parameters(self, parameter_dict, alternate_parameter_dict) -> None: """ @@ -954,8 +1033,9 @@ def test_user_receives_error_when_requesting_differences_with_invalid_type(self, WHEN: They call get_missing_or_different THEN: A TypeError should explain that only ParDict instances are supported """ - with pytest.raises(TypeError, match="Can only compare with another ParDict instance"): + with pytest.raises(TypeError) as exc_info: parameter_dict.get_missing_or_different({"PARAM": Par(1.0)}) + assert str(exc_info.value) == "Can only compare with another ParDict instance" class TestParameterCreationFromDifferentSources: @@ -1155,6 +1235,8 @@ def test_user_can_sort_parameters_using_missionplanner_rules(self) -> None: assert sorted_names[1].startswith("ACRO") assert sorted_names[2].startswith("BATT") assert sorted_names[3].startswith("BATT") + assert ParDict.missionplanner_sort("SERIAL1_PROTOCOL") == ("SERIAL1", "PROTOCOL") + assert ParDict.missionplanner_sort("AA_B") == ("AA", "B") def test_user_can_format_parameters_for_missionplanner(self, parameter_dict) -> None: """ @@ -1166,13 +1248,32 @@ def test_user_can_format_parameters_for_missionplanner(self, parameter_dict) -> """ # Arrange: Parameter dictionary with mixed comments + parameter_dict["A_B"] = Par(2.0) + parameter_dict["AA"] = Par(3.0) + parameter_dict["NO_COMMENT"] = Par(0.001) + parameter_dict["PRECISION"] = Par(1.23456789, "Precision") + parameter_dict["RAW_VALUE"] = 3.251234567 + # Act: Format for Mission Planner formatted = parameter_dict._format_params("missionplanner") # pylint: disable=protected-access # Assert: Correct Mission Planner format - assert any("ACRO_YAW_P,4.5 # Yaw P gain" in line for line in formatted) - assert any("GPS_TYPE,1" in line for line in formatted) # No comment case - assert len(formatted) == 5 # All parameters formatted + assert formatted == [ + "A_B,2", + "AA,3", + "ACRO_YAW_P,4.5 # Yaw P gain", + "BATT_CAPACITY,5000 # Battery capacity in mAh", + "COMPASS_ENABLE,1 # Enable compass", + "GPS_TYPE,1 # GPS type", + "NO_COMMENT,0.001", + "PILOT_SPEED_UP,250 # Pilot controlled climb rate", + "PRECISION,1.234568 # Precision", + "RAW_VALUE,3.251235", + ] + + def test_user_gets_missionplanner_format_by_default(self, parameter_dict) -> None: + """Omitting the format selects the documented Mission Planner output.""" + assert parameter_dict._format_params() == parameter_dict._format_params("missionplanner") # pylint: disable=protected-access def test_user_can_format_parameters_for_mavproxy(self, parameter_dict) -> None: """ @@ -1184,12 +1285,28 @@ def test_user_can_format_parameters_for_mavproxy(self, parameter_dict) -> None: """ # Arrange: Parameter dictionary + parameter_dict["A_B"] = Par(2.0) + parameter_dict["AA"] = Par(3.0) + parameter_dict["NO_COMMENT"] = Par(0.001) + parameter_dict["PRECISION"] = Par(1.23456789, "Precision") + parameter_dict["RAW_VALUE"] = 3.251234567 + # Act: Format for MAVProxy formatted = parameter_dict._format_params("mavproxy") # pylint: disable=protected-access # Assert: Correct MAVProxy format (space-separated, fixed width) - yaw_line = next((line for line in formatted if "ACRO_YAW_P" in line), "") - assert yaw_line == "ACRO_YAW_P 4.500000 # Yaw P gain" + assert formatted == [ + "AA 3.000000", + "ACRO_YAW_P 4.500000 # Yaw P gain", + "A_B 2.000000", + "BATT_CAPACITY 5000.000000 # Battery capacity in mAh", + "COMPASS_ENABLE 1.000000 # Enable compass", + "GPS_TYPE 1.000000 # GPS type", + "NO_COMMENT 0.001000", + "PILOT_SPEED_UP 250.000000 # Pilot controlled climb rate", + "PRECISION 1.234568 # Precision", + "RAW_VALUE 3.251235", + ] def test_user_receives_error_for_unsupported_format(self, parameter_dict) -> None: """ @@ -1202,8 +1319,9 @@ def test_user_receives_error_for_unsupported_format(self, parameter_dict) -> Non # Arrange: Invalid format string # Act & Assert: User gets error for unsupported format - with pytest.raises(ParamFileError, match="Unsupported file format"): + with pytest.raises(ParamFileError) as exc_info: parameter_dict._format_params("invalid_format") # pylint: disable=protected-access + assert str(exc_info.value) == "ERROR: Unsupported file format invalid_format" def test_user_can_annotate_parameters_with_comments(self, parameter_dict) -> None: """ @@ -1274,13 +1392,27 @@ def test_user_gets_cli_pagination_when_running_as_main(self, monkeypatch) -> Non monkeypatch.setattr(par_dict_module, "__name__", "__main__") mock_input = MagicMock(return_value="") monkeypatch.setattr("builtins.input", mock_input) + events = [] with patch("builtins.print") as mock_print: + mock_print.side_effect = lambda text: events.append(("print", text)) + mock_input.side_effect = lambda prompt: events.append(("input", prompt)) or "" ParDict.print_out([f"PARAM_{i},1.0" for i in range(6)], "CLI Parameters") - assert mock_input.call_count >= 1 - assert mock_get_terminal_size.call_count >= 2 # Initial size read and refresh after pagination pause - mock_print.assert_any_call("\nCLI Parameters has 6 parameters:") + prompt = "\nCLI Parameters list is long hit enter to continue" + assert [call.args[0] for call in mock_input.call_args_list] == [prompt, prompt] + assert mock_get_terminal_size.call_count == 3 + assert events == [ + ("print", "\nCLI Parameters has 6 parameters:"), + ("input", prompt), + ("print", "PARAM_0,1.0"), + ("print", "PARAM_1,1.0"), + ("print", "PARAM_2,1.0"), + ("input", prompt), + ("print", "PARAM_3,1.0"), + ("print", "PARAM_4,1.0"), + ("print", "PARAM_5,1.0"), + ] class TestParameterCategorization: @@ -1344,6 +1476,14 @@ def always_within_tolerance(_value1: float, _value2: float) -> bool: class TestParameterCommentAnnotation: """Test parameter comment annotation workflows.""" + def test_annotation_preserves_values_and_keeps_missing_comments_blank(self) -> None: + """Annotations keep parameter values and normalize absent comments to blank text.""" + original = ParDict({"NO_COMMENT": Par(7.5, None), "EMPTY_COMMENT": Par(8.5, "")}) + + annotated = original.annotate_with_comments({}) + + assert annotated == {"NO_COMMENT": Par(7.5, ""), "EMPTY_COMMENT": Par(8.5, "")} + def test_user_can_annotate_parameters_with_new_comments(self, parameter_dict) -> None: """ User can add or update comments on parameters from a lookup table. @@ -1432,6 +1572,54 @@ def test_user_gets_consistent_parameter_sorting_with_underscore_parts(self) -> N class TestParameterParsingEdgeCases: """Test edge cases in parameter file parsing.""" + @pytest.mark.parametrize( + ("content", "invalid_name"), + [ + ("ACRO\tYAW_P 4.5", "ACRO\tYAW_P"), + ("ACRO\fYAW_P\t4.5", "ACRO\fYAW_P"), + ], + ) + def test_loader_reports_mixed_whitespace_inside_parameter_names(self, content: str, invalid_name: str) -> None: + """Whitespace inside a parameter name is rejected with a name-specific diagnostic.""" + with tempfile.NamedTemporaryFile(mode="w", suffix=".param", delete=False) as parameter_file: + parameter_file.write(content) + file_path = parameter_file.name + + try: + with pytest.raises(ParamFileError) as exc_info: + ParDict.load_param_file_into_dict(file_path) + assert str(exc_info.value) == f"Invalid characters in parameter name {invalid_name} in {file_path} line 1" + finally: + os.unlink(file_path) + + def test_loader_preserves_additional_hashes_in_comments(self) -> None: + """Only the first hash starts a comment; later hashes remain part of it.""" + content = "ACRO_YAW_P,4.5 # first note # retained note" + with tempfile.NamedTemporaryFile(mode="w", suffix=".param", delete=False) as f: + f.write(content) + f.flush() + file_path = f.name + + try: + assert ParDict.load_param_file_into_dict(file_path) == {"ACRO_YAW_P": Par(4.5, "first note # retained note")} + finally: + os.unlink(file_path) + + def test_loader_keeps_extra_commas_in_the_value_for_validation(self) -> None: + """The first comma separates a name and value; the invalid remainder gets a clear error.""" + content = "ACRO_YAW_P,4.5,6.0" + with tempfile.NamedTemporaryFile(mode="w", suffix=".param", delete=False) as f: + f.write(content) + f.flush() + file_path = f.name + + try: + with pytest.raises(ParamFileError) as exc_info: + ParDict.load_param_file_into_dict(file_path) + assert str(exc_info.value) == f"Invalid parameter value '4.5,6.0' in {file_path} line 1" + finally: + os.unlink(file_path) + def test_user_can_parse_parameters_with_tab_separators(self) -> None: """ User can parse parameter files that use tab separators. @@ -1478,8 +1666,9 @@ def test_user_receives_clear_error_for_missing_separators(self) -> None: try: # Act & Assert: Clear error for missing separator - with pytest.raises(ParamFileError, match="Missing parameter-value separator"): + with pytest.raises(ParamFileError) as exc_info: ParDict.load_param_file_into_dict(f.name) + assert str(exc_info.value) == f"Missing parameter-value separator: {malformed_content} in {f.name} line 1" finally: os.unlink(f.name) @@ -1502,8 +1691,9 @@ def test_user_receives_error_for_too_long_parameter_names(self) -> None: try: # Act & Assert: Error for too long parameter name - with pytest.raises(ParamFileError, match="Too long parameter name"): + with pytest.raises(ParamFileError) as exc_info: ParDict.load_param_file_into_dict(f.name) + assert str(exc_info.value) == f"Too long parameter name: {long_name} in {f.name} line 1" finally: os.unlink(f.name) @@ -1525,8 +1715,9 @@ def test_user_receives_error_for_invalid_parameter_name_characters(self) -> None try: # Act & Assert: Error for invalid characters - with pytest.raises(ParamFileError, match="Invalid characters in parameter name"): + with pytest.raises(ParamFileError) as exc_info: ParDict.load_param_file_into_dict(f.name) + assert str(exc_info.value) == f"Invalid characters in parameter name invalid_name in {f.name} line 1" finally: os.unlink(f.name) @@ -1548,8 +1739,9 @@ def test_user_receives_error_for_duplicate_parameter_names(self) -> None: try: # Act & Assert: Error for duplicate parameters - with pytest.raises(ParamFileError, match="Duplicated parameter"): + with pytest.raises(ParamFileError) as exc_info: ParDict.load_param_file_into_dict(f.name) + assert str(exc_info.value) == f"Duplicated parameter ACRO_YAW_P in {f.name} line 2" finally: os.unlink(f.name) @@ -1742,8 +1934,9 @@ def test_parameter_validation_rejects_invalid_values(self) -> None: try: # Act & Assert: Invalid values rejected - with pytest.raises(ParamFileError, match=_("Invalid parameter value {value!r}").format(value="not_a_number")): + with pytest.raises(ParamFileError) as exc_info: ParDict.load_param_file_into_dict(file_path) + assert str(exc_info.value) == f"Invalid parameter value 'not_a_number' in {file_path} line 1" finally: os.unlink(file_path) @@ -1766,7 +1959,12 @@ def test_parameter_validation_rejects_non_finite_values(self) -> None: file_path = f.name try: - with pytest.raises(ParamFileError, match=_("Non-finite parameter value {value!r}").format(value=bad_value)): + with pytest.raises(ParamFileError) as exc_info: ParDict.load_param_file_into_dict(file_path) + parsed_value = float(bad_value) + assert str(exc_info.value) == ( + f"Non-finite parameter value {bad_value!r} (parsed as {parsed_value}) " + f"for VALID_PARAM in {file_path} line 1" + ) finally: os.unlink(file_path) diff --git a/tests/test_data_model_parameter_upgrade.py b/tests/test_data_model_parameter_upgrade.py index 8729703c4..47033f041 100755 --- a/tests/test_data_model_parameter_upgrade.py +++ b/tests/test_data_model_parameter_upgrade.py @@ -20,6 +20,7 @@ from ardupilot_methodic_configurator.data_model_parameter_upgrade import ( PARAM_UPGRADE_DICT_46, PARAM_UPGRADE_DICT_47, + _process_sr_parameter, build_sr_to_mav_mapping, upgrade_file_parameters_46, upgrade_file_parameters_47, @@ -201,6 +202,23 @@ def test_mavlink_ports_are_deduplicated_and_sorted_numerically_across_files() -> assert ports == {0, 2, 10} +@pytest.mark.parametrize( + ("name", "mapping", "ports", "expected_is_sr_param"), + [ + ("NOT_A_STREAM_RATE", {}, set(), False), + ("SR3_RAW_SENS", {}, set(), True), + ], +) +def test_stream_rate_processing_returns_no_target_when_not_remapped( + name: str, mapping: dict[str, str], ports: set[int], expected_is_sr_param: bool +) -> None: + """Given an unrelated or disabled SR parameter, report that no target parameter exists.""" + is_sr_param, _, new_par = _process_sr_parameter(name, Par(1), mapping, ports) + + assert is_sr_param is expected_is_sr_param + assert new_par is None + + @pytest.fixture def sample_parameters_45() -> dict[str, ParDict]: """ diff --git a/tests/test_data_model_vehicle_components_base.py b/tests/test_data_model_vehicle_components_base.py index 36bc45bdc..c94afd76c 100755 --- a/tests/test_data_model_vehicle_components_base.py +++ b/tests/test_data_model_vehicle_components_base.py @@ -16,7 +16,7 @@ from unittest.mock import MagicMock, Mock import pytest -from test_data_model_vehicle_components_common import BasicTestMixin, ComponentDataModelFixtures, RealisticDataTestMixin +from test_data_model_vehicle_components_common import ComponentDataModelFixtures from ardupilot_methodic_configurator import __version__ from ardupilot_methodic_configurator.backend_filesystem_vehicle_components import VehicleComponents @@ -28,8 +28,8 @@ # pylint: disable=protected-access,too-many-public-methods,too-many-lines -class TestComponentDataModelBase(BasicTestMixin, RealisticDataTestMixin): - """Tests for the ComponentDataModel class.""" +class TestComponentDataModelBase: + """Tests for the ComponentDataModelBase class.""" @pytest.fixture def empty_model(self) -> ComponentDataModelBase: @@ -46,7 +46,6 @@ def realistic_model(self) -> ComponentDataModelBase: """Create a realistic vehicle data model based on the JSON file.""" return ComponentDataModelFixtures.create_realistic_model(ComponentDataModelBase) - # Additional tests specific to ComponentDataModelBase that aren't covered by mixins def test_system_sets_component_values_at_nested_paths(self, basic_model) -> None: """ System correctly sets component values at various nested path levels. @@ -72,6 +71,74 @@ def test_system_sets_component_values_at_nested_paths(self, basic_model) -> None basic_model.set_component_value(("Flight Controller", "Notes"), None) assert basic_model._data["Components"]["Flight Controller"]["Notes"] == "" + def test_empty_initial_data_starts_with_blank_battery_chemistry(self) -> None: + """A new model has no selected battery chemistry until project data supplies one.""" + schema = Mock(spec=VehicleComponentsJsonSchema) + + model = ComponentDataModelBase({}, {}, schema) + + assert model._battery_chemistry == "" + + def test_none_for_numeric_component_remains_blank(self, basic_model) -> None: + """Clearing a typed numeric field stores the blank value rather than numeric zero.""" + path = ("Battery", "Specifications", "Capacity mAh") + + basic_model.set_component_value(path, None) + + assert basic_model.get_component_value(path) == "" + + def test_missing_component_datatype_path_returns_none(self, basic_model) -> None: + """Incomplete datatype metadata is treated as an unknown component type.""" + basic_model._component_datatypes = {"Battery": {}} + + assert basic_model._get_component_datatype(("Battery", "Missing", "Capacity")) is None + assert basic_model._get_component_datatype(("Missing", "Specifications", "Capacity")) is None + + def test_missing_components_key_returns_empty_mapping(self, basic_model) -> None: + """Models without a Components section expose an empty component mapping.""" + basic_model._data.pop("Components") + + assert basic_model.get_all_components() == {} + + def test_model_with_one_component_reports_components_present(self, basic_model) -> None: + """A single component is enough for the model to report component data.""" + basic_model._data["Components"] = {"Battery": {}} + + assert basic_model.has_components() + + def test_invalid_battery_chemistry_log_names_the_rejected_value( + self, basic_model, caplog: pytest.LogCaptureFixture + ) -> None: + """The chemistry warning identifies the value that was replaced by the default.""" + basic_model._data["Components"]["Battery"]["Specifications"]["Chemistry"] = "UnavailableCell" + + basic_model.init_battery_chemistry() + + record = next(record for record in caplog.records if record.levelname == "ERROR") + assert record.msg == "Invalid battery chemistry %s, defaulting to Lipo" + assert record.args == ("UnavailableCell",) + assert basic_model._battery_chemistry == "Lipo" + + def test_setting_a_configuration_template_marks_the_project_as_new(self, basic_model) -> None: + """Selecting a configuration template marks the project as newly configured.""" + basic_model.set_configuration_template("Copter/Quad") + + assert basic_model.get_component_data()["Configuration template"] == "Copter/Quad" + assert basic_model.is_new_project() is True + + def test_save_passes_component_data_and_vehicle_directory(self, basic_model) -> None: + """Saving forwards the current component mapping and its project directory.""" + filesystem = MagicMock() + filesystem.vehicle_dir = "/vehicle/project" + filesystem.save_vehicle_components_json_data.return_value = (True, "saved") + + result = basic_model.save_to_filesystem(filesystem) + + assert result == (True, "saved") + filesystem.save_vehicle_components_json_data.assert_called_once_with( + basic_model.get_component_data(), "/vehicle/project" + ) + def test_system_retrieves_component_values_from_nested_paths(self, basic_model) -> None: """ System correctly retrieves component values from nested paths. @@ -231,37 +298,39 @@ def test_user_can_modify_existing_components_and_add_new_ones(self, basic_model) # Tests for specific ComponentDataModelBase methods - def test_system_updates_json_structure_for_old_file_formats(self, empty_model) -> None: + def test_system_updates_json_structure_for_old_file_formats(self) -> None: """ System updates JSON structure to add missing required fields from old formats. GIVEN: Component data with minimal or missing structure - WHEN: Calling update_json_structure + WHEN: Initializing the legacy project THEN: All required component fields should be added AND: Default values should be set for missing fields - AND: Program version field should be added + AND: Version fields should be added """ - # Start with minimal data - empty_model._data = {"Components": {}} - - empty_model.update_json_structure() - - # Check that all required fields are added - assert "Battery" in empty_model._data["Components"] - assert "Specifications" in empty_model._data["Components"]["Battery"] - assert "Chemistry" in empty_model._data["Components"]["Battery"]["Specifications"] - assert empty_model._data["Components"]["Battery"]["Specifications"]["Chemistry"] == "Lipo" + # Arrange: Load a legacy project with an empty component list + model = ComponentDataModelBase({"Components": {}}, {}, ComponentDataModelFixtures.create_schema()) + assert not model.has_components() - assert "Frame" in empty_model._data["Components"] - assert "Specifications" in empty_model._data["Components"]["Frame"] - assert "TOW min Kg" in empty_model._data["Components"]["Frame"]["Specifications"] - assert "TOW max Kg" in empty_model._data["Components"]["Frame"]["Specifications"] - - assert "Flight Controller" in empty_model._data["Components"] - assert "Specifications" in empty_model._data["Components"]["Flight Controller"] - assert "MCU Series" in empty_model._data["Components"]["Flight Controller"]["Specifications"] + # Act: Initialize the loaded project + model.post_init({}) - assert "Program version" in empty_model._data + # Assert: Required components have usable default values + components = model.get_all_components() + assert model.has_components() + assert set(components) == {"Battery", "Frame", "Flight Controller"} + assert components["Battery"]["Specifications"] == {"Chemistry": "Lipo", "Capacity mAh": 0} + assert components["Frame"]["Specifications"]["TOW min Kg"] == 1 + assert components["Frame"]["Specifications"]["TOW max Kg"] == 1 + assert components["Flight Controller"] == { + "Product": {}, + "Firmware": {}, + "Specifications": {"MCU Series": "Unknown"}, + "Notes": "", + } + data = model.get_component_data() + assert data["Format version"] == 1 + assert data["Program version"] == __version__ def test_system_migrates_old_gnss_receiver_key_to_new_format(self, basic_model) -> None: """ @@ -803,28 +872,31 @@ def test_system_initializes_battery_chemistry_with_validation(self, basic_model) basic_model.init_battery_chemistry() assert basic_model._battery_chemistry == "Lipo" # Should default to Lipo for invalid chemistry - def test_system_provides_multiple_component_access_methods(self, realistic_model) -> None: + def test_user_can_access_saved_component_specifications(self, realistic_model: ComponentDataModelBase) -> None: """ - System provides various methods to access and check components. + A saved project exposes its component specifications. - GIVEN: Model with components - WHEN: Using different access methods (get_all_components, has_components) - THEN: get_all_components should return dict of all components - AND: has_components should return True when components exist - AND: has_components should return False for empty models + GIVEN: A vehicle project with populated component data + WHEN: Reading the initialized model + THEN: The saved flight-controller, battery, frame, and motor values are available """ - # Test accessing all top-level components + # Act: Read the initialized project components components = realistic_model.get_all_components() - assert isinstance(components, dict) - assert len(components) > 0 - # Test has_components method - assert realistic_model.has_components() is True - - # Test with model that has no components - mock_schema = Mock(spec=VehicleComponentsJsonSchema) - empty_components = ComponentDataModelBase({"Components": {}, "Format version": 1}, {}, mock_schema) - assert empty_components.has_components() is False + # Assert: Saved values survive project initialization + controller = components["Flight Controller"] + assert controller["Product"]["Manufacturer"] == "Matek" + assert controller["Product"]["Model"] == "H743 SLIM" + assert controller["Firmware"]["Type"] == "ArduCopter" + assert controller["Specifications"]["MCU Series"] == "STM32H7xx" + battery = components["Battery"]["Specifications"] + assert battery["Chemistry"] == "Lipo" + assert battery["Number of cells"] == 4 + assert battery["Capacity mAh"] == 1800 + assert battery["Volt per cell max"] == 4.2 + assert realistic_model.get_component_value(("Frame", "Specifications", "TOW min Kg")) == 0.6 + assert realistic_model.get_component_value(("Frame", "Specifications", "TOW max Kg")) == 0.6 + assert realistic_model.get_component_value(("Motors", "Specifications", "Poles")) == 14 def test_system_preserves_version_fields_as_strings(self, basic_model) -> None: """ diff --git a/tests/test_data_model_vehicle_components_common.py b/tests/test_data_model_vehicle_components_common.py index 72aef0b13..b16774c92 100755 --- a/tests/test_data_model_vehicle_components_common.py +++ b/tests/test_data_model_vehicle_components_common.py @@ -282,195 +282,3 @@ def create_display_model_with_mock_schema(mock_schema: MagicMock) -> ComponentDa model = ComponentDataModelDisplay(initial_data, component_datatypes, schema) model.schema = mock_schema return model - - -class CommonAssertions: - """Common assertion helpers for component data model tests.""" - - @staticmethod - def assert_basic_structure(model) -> None: - """Assert basic component data structure is valid.""" - data = model.get_component_data() - assert isinstance(data, dict) - assert "Components" in data - assert isinstance(data["Components"], dict) - assert "Format version" in data - - @staticmethod - def assert_basic_components(model) -> None: - """Assert basic auto-populated components are present and correct.""" - data = model.get_component_data() - components = data["Components"] - - # Check auto-populated Battery component - assert "Battery" in components - assert components["Battery"]["Specifications"]["Chemistry"] == "Lipo" - assert components["Battery"]["Specifications"]["Capacity mAh"] == 0 - - # Check auto-populated Frame component - assert "Frame" in components - assert components["Frame"]["Specifications"]["TOW min Kg"] == 1 - assert components["Frame"]["Specifications"]["TOW max Kg"] == 1 - - # Check auto-populated Flight Controller component - assert "Flight Controller" in components - assert components["Flight Controller"]["Specifications"]["MCU Series"] == "Unknown" - assert components["Flight Controller"]["Product"] == {} - assert components["Flight Controller"]["Firmware"] == {} - assert components["Flight Controller"]["Notes"] == "" - - @staticmethod - def assert_empty_components(model) -> None: - """Assert model has minimal auto-populated components structure.""" - data = model.get_component_data() - # After post_init, even "empty" models have auto-populated components - # due to update_json_structure() ensuring backward compatibility - expected_auto_components = {"Battery", "Frame", "Flight Controller"} - actual_components = set(data["Components"].keys()) - - # Check that only auto-populated components exist - assert actual_components == expected_auto_components - assert data["Format version"] == 1 - - @staticmethod - def assert_realistic_flight_controller(model) -> None: - """Assert realistic flight controller data is present and correct.""" - components = model.get_component_data()["Components"] - fc_data = components["Flight Controller"] - assert fc_data["Product"]["Manufacturer"] == "Matek" - assert fc_data["Product"]["Model"] == "H743 SLIM" - assert fc_data["Firmware"]["Type"] == "ArduCopter" - assert fc_data["Specifications"]["MCU Series"] == "STM32H7xx" - - @staticmethod - def assert_realistic_frame_specs(model) -> None: - """Assert realistic frame specifications are correct.""" - frame_tow_min = model.get_component_value(("Frame", "Specifications", "TOW min Kg")) - frame_tow_max = model.get_component_value(("Frame", "Specifications", "TOW max Kg")) - assert frame_tow_min == 0.6 - assert frame_tow_max == 0.6 - - @staticmethod - def assert_realistic_battery_specs(model) -> None: - """Assert realistic battery specifications are correct.""" - components = model.get_component_data()["Components"] - battery_specs = components["Battery"]["Specifications"] - assert battery_specs["Chemistry"] == "Lipo" - assert battery_specs["Number of cells"] == 4 - assert battery_specs["Capacity mAh"] == 1800 - assert battery_specs["Volt per cell max"] == 4.2 - - @staticmethod - def assert_realistic_motor_specs(model) -> None: - """Assert realistic motor specifications are correct.""" - motor_poles = model.get_component_value(("Motors", "Specifications", "Poles")) - assert motor_poles == 14 - - -# Common test methods that can be mixed into test classes -class BasicTestMixin: - """Mixin class providing common test methods for basic functionality.""" - - def test_user_can_initialize_model_with_basic_data(self, basic_model) -> None: - """ - User can initialize data model with basic component data. - - GIVEN: Basic component data with Battery, Frame, and Flight Controller - WHEN: Model is initialized - THEN: Model structure should be valid - AND: Basic components should be present - AND: Format version should be set correctly - """ - CommonAssertions.assert_basic_structure(basic_model) - CommonAssertions.assert_basic_components(basic_model) - data = basic_model.get_component_data() - assert data["Format version"] == 1 - - def test_user_can_initialize_empty_model(self, empty_model) -> None: - """ - User can initialize data model with minimal data. - - GIVEN: Empty component data - WHEN: Model is initialized - THEN: Model structure should be valid - AND: Auto-populated components should be present - """ - CommonAssertions.assert_basic_structure(empty_model) - CommonAssertions.assert_empty_components(empty_model) - - def test_user_can_retrieve_component_data(self, basic_model) -> None: - """ - User can retrieve complete component data from model. - - GIVEN: Initialized data model - WHEN: Retrieving component data - THEN: Data structure should be valid - """ - CommonAssertions.assert_basic_structure(basic_model) - - def test_system_validates_component_data_structure(self, basic_model, empty_model) -> None: - """ - System validates component data structure for all model types. - - GIVEN: Both basic and empty models - WHEN: Checking data structure - THEN: Both should have valid structure - """ - CommonAssertions.assert_basic_structure(basic_model) - CommonAssertions.assert_basic_structure(empty_model) - - def test_user_can_retrieve_all_components(self, basic_model, empty_model) -> None: - """ - User can retrieve all components from model. - - GIVEN: Models with basic or empty data - WHEN: Retrieving all components - THEN: Auto-populated components should be present - AND: Component names should match expected set - """ - # Test with basic model - should have auto-populated components - components = basic_model.get_all_components() - expected_auto_components = {"Battery", "Frame", "Flight Controller"} - actual_components = set(components.keys()) - assert actual_components == expected_auto_components - - # Test with empty data - should have same auto-populated components - empty_components = empty_model.get_all_components() - assert set(empty_components.keys()) == expected_auto_components - - -class RealisticDataTestMixin: - """Mixin class providing common test methods for realistic data functionality.""" - - def test_user_can_access_realistic_vehicle_components(self, realistic_model) -> None: - """ - User can access all components from realistic vehicle configuration. - - GIVEN: Realistic vehicle data with complete component specifications - WHEN: Accessing component data - THEN: Flight controller data should be accessible - AND: Frame specifications should be accessible - AND: Battery specifications should be accessible - AND: Motor specifications should be accessible - """ - CommonAssertions.assert_realistic_flight_controller(realistic_model) - CommonAssertions.assert_realistic_frame_specs(realistic_model) - CommonAssertions.assert_realistic_battery_specs(realistic_model) - CommonAssertions.assert_realistic_motor_specs(realistic_model) - - def test_system_detects_when_model_has_components(self, realistic_model, empty_model) -> None: - """ - System correctly detects whether model has components. - - GIVEN: Models with realistic or empty data - WHEN: Checking if components exist - THEN: Realistic model should have components - AND: Empty model should have auto-populated components - """ - # Realistic data should have components - assert realistic_model.has_components() - - # Empty data should have auto-populated components after post_init - # so has_components() will return True - assert empty_model.has_components() - assert empty_model.has_components() diff --git a/tests/test_data_model_vehicle_components_display.py b/tests/test_data_model_vehicle_components_display.py index f4f50949e..c640cb69a 100755 --- a/tests/test_data_model_vehicle_components_display.py +++ b/tests/test_data_model_vehicle_components_display.py @@ -153,6 +153,14 @@ def mock_description(path) -> tuple[str, bool]: # Assert: Parent component is displayed because it contains required nested fields assert result is True + def test_nested_display_does_not_recheck_the_top_level_component_list(self, display_model) -> None: + """Given a nested component, only its schema fields determine simple-mode visibility.""" + display_model.schema.get_component_property_description.return_value = ("Required", False) + display_model.get_all_components = MagicMock(return_value=["Child"]) + + assert display_model.should_display_in_simple_mode("Child", {"Required": "value"}, ["Parent"], "simple") + display_model.get_all_components.assert_not_called() + class TestLeafComponentDisplay: """Test leaf component display logic.""" @@ -239,6 +247,7 @@ def test_system_prepares_correct_non_leaf_widget_config(self, display_model) -> assert config["description"] == "Flight controller description" assert config["is_optional"] is False assert config["is_toplevel"] is True + display_model.schema.get_component_property_description.assert_called_once_with(("Flight Controller",)) def test_system_prepares_correct_leaf_widget_config(self, display_model) -> None: """ @@ -263,6 +272,22 @@ def test_system_prepares_correct_leaf_widget_config(self, display_model) -> None assert config["path"] == ("Flight Controller", "Product", "Manufacturer") assert config["description"] == "Manufacturer description" assert config["is_optional"] is False + display_model.schema.get_component_property_description.assert_called_once_with( + ("Flight Controller", "Product", "Manufacturer") + ) + + def test_user_gets_an_empty_description_without_translation(self, display_model, monkeypatch) -> None: + """Given a blank schema description, keep the tooltip blank and skip translation.""" + translate = MagicMock(side_effect=lambda text: f"translated:{text}") + monkeypatch.setattr("ardupilot_methodic_configurator.data_model_vehicle_components_display._", translate) + display_model.schema.get_component_property_description.return_value = ("", False) + + leaf = display_model.prepare_leaf_widget_config("Manufacturer", "Holybro", ["Flight Controller", "Product"]) + section = display_model.prepare_non_leaf_widget_config("Product", {}, ["Flight Controller"]) + + assert leaf["description"] == "" + assert section["description"] == "" + translate.assert_not_called() def test_system_enhances_optional_component_descriptions(self, display_model) -> None: """ @@ -283,7 +308,7 @@ def test_system_enhances_optional_component_descriptions(self, display_model) -> # Assert: Description is enhanced for optional field assert "MCU series description" in config["description"] - assert "optional" in config["description"].lower() + assert config["description"] == ("MCU series description\nThis is optional and can be left blank") assert config["is_optional"] is True def test_system_handles_empty_descriptions_gracefully(self, display_model) -> None: @@ -446,8 +471,7 @@ def test_user_receives_appropriate_guidance_for_optional_fields(self, display_mo config = display_model.prepare_leaf_widget_config("Optional Field", "value", ["Component"]) # Assert: User receives clear optional field guidance - assert "optional" in config["description"].lower() - assert "blank" in config["description"].lower() + assert config["description"] == "This is an optional field\nThis is optional and can be left blank" assert config["is_optional"] is True def test_system_hides_components_with_only_optional_fields_in_simple_mode(self, display_model) -> None: @@ -487,9 +511,4 @@ def test_system_enhances_optional_field_descriptions_when_description_exists(sel config = display_model.prepare_leaf_widget_config("optional_field", "value", ["Component"]) # Assert: Description is enhanced with optional guidance - description = config["description"] - assert "Existing description" in description - assert "optional" in description.lower() - assert "blank" in description.lower() - # Specifically test that the enhancement was applied - assert "\n" in description # The enhancement adds a newline + assert config["description"] == "Existing description\nThis is optional and can be left blank" diff --git a/tests/test_data_model_vehicle_components_import.py b/tests/test_data_model_vehicle_components_import.py index 5943a7baa..b0aa2f17a 100755 --- a/tests/test_data_model_vehicle_components_import.py +++ b/tests/test_data_model_vehicle_components_import.py @@ -15,11 +15,7 @@ from unittest.mock import patch import pytest -from test_data_model_vehicle_components_common import ( - BasicTestMixin, - ComponentDataModelFixtures, - RealisticDataTestMixin, -) +from test_data_model_vehicle_components_common import ComponentDataModelFixtures import ardupilot_methodic_configurator.data_model_vehicle_components_import as _import_module from ardupilot_methodic_configurator.battery_cell_voltages import BatteryCell @@ -32,7 +28,7 @@ # pylint: disable=protected-access,too-many-public-methods,too-many-lines -class TestComponentDataModelImport(BasicTestMixin, RealisticDataTestMixin): +class TestComponentDataModelImport: """Tests for the ComponentDataModelImport class.""" @pytest.fixture @@ -378,15 +374,24 @@ def test_system_imports_esc_on_main_outputs(self, realistic_model) -> None: fc_parameters = { "MOT_PWM_TYPE": 6, "SERVO1_FUNCTION": 33, # Motor1 + "SERVO15_FUNCTION": 33, # Outside the AIO output range } doc = {"MOT_PWM_TYPE": {"values": {"6": "DShot600"}}} + realistic_model.set_component_value(("ESC", "FC->ESC Connection", "Type"), "AIO") + realistic_model.set_component_value(("ESC", "FC->ESC Connection", "Protocol"), "PWM") + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Type"), "None") + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Protocol"), "None") realistic_model._set_esc_type_from_fc_parameters(fc_parameters, doc) esc_type = realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Type")) esc_protocol = realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Protocol")) + telemetry_type = realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Type")) + telemetry_protocol = realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Protocol")) assert esc_type == "Main Out" assert esc_protocol == "DShot600" + assert telemetry_type == "Main Out" + assert telemetry_protocol == "BDShotOnly" @patch( "ardupilot_methodic_configurator.data_model_vehicle_components_import.get_esc_connection_sub_dict", @@ -410,12 +415,20 @@ def test_system_imports_esc_aio_configuration(self, realistic_model) -> None: } doc: dict[str, Any] = {} + realistic_model.set_component_value(("ESC", "FC->ESC Connection", "Type"), "Main Out") + realistic_model.set_component_value(("ESC", "FC->ESC Connection", "Protocol"), "PWM") + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Type"), "None") + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Protocol"), "None") realistic_model._set_esc_type_from_fc_parameters(fc_parameters, doc) esc_type = realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Type")) esc_protocol = realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Protocol")) + telemetry_type = realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Type")) + telemetry_protocol = realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Protocol")) assert esc_type == "AIO" assert esc_protocol == "DShot600" + assert telemetry_type == "AIO" + assert telemetry_protocol == "BDShotOnly" def test_user_can_import_frame_class_from_fc(self, realistic_model) -> None: """Given FRAME_CLASS from FC, set Frame.Specifications.Class.""" @@ -570,6 +583,8 @@ def test_user_can_import_motor_poles_for_dshot(self, realistic_model) -> None: WHEN: User imports FC parameters THEN: Motor poles should be set from SERVO_BLH_POLES parameter """ + realistic_model.set_component_value(("Flight Controller", "Firmware", "Type"), "ArduCopter") + realistic_model.set_component_value(("Motors", "Specifications", "Poles"), 99) fc_parameters = {"MOT_PWM_TYPE": 6, "SERVO_BLH_POLES": 14} doc = {"MOT_PWM_TYPE": {"values": {"6": "DShot600"}}} @@ -587,6 +602,7 @@ def test_user_can_import_motor_poles_for_fettec(self, realistic_model) -> None: WHEN: User imports FC parameters THEN: Motor poles should be set from SERVO_FTW_POLES parameter """ + realistic_model.set_component_value(("Motors", "Specifications", "Poles"), 99) fc_parameters = {"MOT_PWM_TYPE": 0, "SERVO_FTW_MASK": 15, "SERVO_FTW_POLES": 12} doc: dict[str, Any] = {} @@ -604,6 +620,7 @@ def test_user_can_import_motor_poles_for_hobbywing(self, realistic_model) -> Non WHEN: User imports FC parameters THEN: Motor poles should be set from ESC_HW_POLES parameter """ + realistic_model.set_component_value(("Motors", "Specifications", "Poles"), 99) fc_parameters = {"ESC_HW_POLES": 28, "MOT_PWM_TYPE": 0} doc: dict[str, Any] = {} @@ -722,8 +739,14 @@ def test_system_handles_esc_protocol_not_found(self, realistic_model) -> None: fc_parameters = {"MOT_PWM_TYPE": 999} # Non-existent type doc = {"MOT_PWM_TYPE": {"values": {"6": "DShot600"}}} # Doesn't contain 999 + realistic_model.set_component_value(("ESC", "FC->ESC Connection", "Protocol"), "DShot600") + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Type"), "AIO") + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Protocol"), "BDShotOnly") realistic_model._set_esc_type_from_fc_parameters(fc_parameters, doc) - # Should handle gracefully without setting protocol + + assert realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Protocol")) == "DShot600" + assert realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Type")) == "None" + assert realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Protocol")) == "None" def test_system_handles_battery_monitor_key_error(self, realistic_model) -> None: """ @@ -833,6 +856,7 @@ def test_system_handles_battery_monitor_type_error(self, realistic_model) -> Non realistic_model._set_battery_type_from_fc_parameters(fc_parameters) # pylint: enable=duplicate-code + # pylint: disable=duplicate-code # These behavior checks complement the matching low-level unit tests. def test_user_can_import_battery_capacity_from_fc_parameters(self, realistic_model) -> None: """ User can import battery capacity from flight controller parameters. @@ -894,6 +918,8 @@ def test_system_handles_none_battery_capacity(self, realistic_model) -> None: with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): realistic_model._set_battery_type_from_fc_parameters(fc_parameters) + # pylint: enable=duplicate-code + def test_system_handles_negative_battery_capacity(self, realistic_model) -> None: """ System ignores negative battery capacity from FC parameters. @@ -1204,26 +1230,49 @@ def test_user_can_import_complete_vehicle_configuration(self, realistic_model, s "SERVO2_FUNCTION": 34, # Motor2 on main out "SERVO_BLH_POLES": 14, # Motor poles for DShot "BATT_MONITOR": 4, # Analog voltage and current + "FRAME_CLASS": 3, # Octa } doc = { "SERIAL1_PROTOCOL": sample_doc_dict["SERIAL1_PROTOCOL"], "BATT_MONITOR": sample_doc_dict["BATT_MONITOR"], "GPS_TYPE": sample_doc_dict["GPS_TYPE"], + "GPS1_TYPE": sample_doc_dict["GPS_TYPE"], "MOT_PWM_TYPE": sample_doc_dict["MOT_PWM_TYPE"], "RC_PROTOCOLS": sample_doc_dict["RC_PROTOCOLS"], + "FRAME_CLASS": {"values": {"3": "Octa"}}, } - with patch.object(realistic_model, "_verify_dict_is_uptodate", return_value=True): + with patch.object(realistic_model, "_verify_dict_is_uptodate", return_value=True) as verify_documentation: realistic_model.process_fc_parameters(fc_parameters, doc) + verification_calls = [call.args for call in verify_documentation.call_args_list] + firmware_type = str(realistic_model.get_component_value(("Flight Controller", "Firmware", "Type"))) + expected_verifications = [ + (doc, _import_module.SERIAL_PROTOCOLS_DICT, "SERIAL1_PROTOCOL", "values"), + (doc, _import_module.BATT_MONITOR_CONNECTION, "BATT_MONITOR", "values"), + (doc, _import_module.GNSS_RECEIVER_CONNECTION, "GPS1_TYPE", "values"), + (doc, _import_module.get_esc_connection_sub_dict(firmware_type), "MOT_PWM_TYPE", "values"), + (doc, _import_module.RC_PROTOCOLS_DICT, "RC_PROTOCOLS", "Bitmask"), + ( + doc, + _import_module.get_frame_class_as_protocol_dict(firmware_type), + "FRAME_CLASS", + "values", + ), + ] + assert all(expected in verification_calls for expected in expected_verifications) + # Verify all components were configured correctly assert realistic_model.get_component_value(("GNSS Receiver", "FC Connection", "Type")) == "SERIAL2" + assert realistic_model.get_component_value(("GNSS Receiver", "FC Connection", "Protocol")) == "uBlox" assert realistic_model.get_component_value(("RC Receiver", "FC Connection", "Type")) == "SERIAL3" assert realistic_model.get_component_value(("RC Receiver", "FC Connection", "Protocol")) == "CRSF" assert realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Type")) == "Main Out" assert realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Protocol")) == "DShot600" assert realistic_model.get_component_value(("Motors", "Specifications", "Poles")) == 14 + assert realistic_model.get_component_value(("Frame", "Specifications", "Frame class")) == "Octa" + assert realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Type")) == "Analog" assert ( realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Protocol")) == "Analog Voltage and Current" @@ -1738,6 +1787,20 @@ def test_user_can_import_complete_battery_configuration(self, realistic_model) - assert capacity == 6500 assert cell_count == 6 + def test_user_can_import_voltage_evidence_that_corrects_template_battery_chemistry(self, realistic_model) -> None: + """ + Imported pack voltage corrects an incompatible template chemistry. + + GIVEN: A vehicle template marked as LiIon and a 12-cell LiIonSS critical-voltage threshold + WHEN: Battery settings are imported + THEN: Chemistry should match the clearly different voltage evidence + """ + realistic_model.set_component_value(("Battery", "Specifications", "Chemistry"), "LiIon") + + realistic_model._set_battery_type_from_fc_parameters({"BATT_MONITOR": 0, "BATT_CRT_VOLT": 32.4}) + + assert realistic_model.get_component_value(("Battery", "Specifications", "Chemistry")) == "LiIonSS" + # ---- Tests for new battery arm/min voltage import (PR: Batt specifications) ---- def test_user_can_import_arm_voltage_from_batt_arm_volt(self, basic_model) -> None: @@ -2113,8 +2176,12 @@ def test_system_warns_when_i2c_bus_index_is_out_of_range(self, realistic_model) with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warn: realistic_model._set_battery_type_from_fc_parameters(fc_parameters) - texts = " ".join(str(c) for c in mock_warn.call_args_list) - assert "out of range" in texts or "BATT_I2C_BUS" in texts + mock_warn.assert_called_once_with( + "BATT_I2C_BUS value %d out of range (0-%d), defaulting to first bus", + 99, + len(_import_module.BATT_MONITOR_CONNECTION["5"]["type"]) - 1, + ) + assert realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Type")) == "I2C1" def test_system_warns_when_i2c_bus_value_is_not_an_integer(self, realistic_model) -> None: """ @@ -2129,8 +2196,7 @@ def test_system_warns_when_i2c_bus_value_is_not_an_integer(self, realistic_model with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warn: realistic_model._set_battery_type_from_fc_parameters(fc_parameters) - texts = " ".join(str(c) for c in mock_warn.call_args_list) - assert "Invalid BATT_I2C_BUS" in texts or "defaulting" in texts + mock_warn.assert_called_once_with("Invalid BATT_I2C_BUS value, defaulting to first bus") def test_system_warns_when_batt_monitor_parameter_is_absent(self, basic_model) -> None: """ @@ -2171,7 +2237,7 @@ def test_system_logs_error_for_invalid_voltage_type_in_import_bat_voltage(self, with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_err: basic_model.import_bat_voltage(specs, "MOT_BAT_VOLT_MAX", "not_a_valid_type") - mock_err.assert_called() + mock_err.assert_called_once_with("Invalid voltage type %s for battery voltage import", "not_a_valid_type") # ------------------------------------------------------------------ # _estimate_battery_cell_count - BATT_ARM_VOLT and MOT_BAT_VOLT_MIN fallbacks @@ -2321,21 +2387,44 @@ def test_system_uses_mot_pwm_type_dict_fallback_when_doc_has_no_mot_pwm_type(sel # _set_battery_type_from_fc_parameters — valid I2C bus index (line 363) # and non-I2C list type (Analog) (line 376) # ------------------------------------------------------------------ - def test_system_selects_i2c_bus_by_index_when_batt_i2c_bus_is_valid(self, basic_model) -> None: + def test_system_selects_second_i2c_bus_when_batt_i2c_bus_is_one(self, basic_model) -> None: """ _set_battery_type_from_fc_parameters uses BATT_I2C_BUS index to select the I2C bus. - GIVEN: BATT_MONITOR=5 (Solo, I2C type) and BATT_I2C_BUS=1 (selects I2C2 = index 1) + GIVEN: BATT_MONITOR=5 (Solo, I2C type) and BATT_I2C_BUS=1 WHEN: _set_battery_type_from_fc_parameters is called - THEN: FC Connection Type should be set to 'I2C2' (fc_conn_type[1]) (line 363 exercised) + THEN: FC Connection Type should be I2C2 without an out-of-range warning """ fc_parameters: dict[str, Any] = {"BATT_MONITOR": 5, "BATT_I2C_BUS": 1} - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning"): + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warn: basic_model._set_battery_type_from_fc_parameters(fc_parameters) result = basic_model.get_component_value(("Battery Monitor", "FC Connection", "Type")) assert result == "I2C2" + mock_warn.assert_not_called() + + def test_system_selects_first_i2c_bus_when_batt_i2c_bus_is_zero(self, basic_model) -> None: + """A zero BATT_I2C_BUS index selects the first I2C bus.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warn: + basic_model._set_battery_type_from_fc_parameters({"BATT_MONITOR": 5, "BATT_I2C_BUS": 0}) + + assert basic_model.get_component_value(("Battery Monitor", "FC Connection", "Type")) == "I2C1" + mock_warn.assert_not_called() + + def test_system_defaults_to_first_i2c_bus_when_index_equals_bus_count(self, basic_model) -> None: + """An index equal to the number of I2C choices is out of range.""" + i2c_choices = _import_module.BATT_MONITOR_CONNECTION["5"]["type"] + bus_count = len(i2c_choices) + + with ( + patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warn, + patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"), + ): + basic_model._set_battery_type_from_fc_parameters({"BATT_MONITOR": 5, "BATT_I2C_BUS": bus_count}) + + mock_warn.assert_called_once() + assert basic_model.get_component_value(("Battery Monitor", "FC Connection", "Type")) == "I2C1" def test_system_defaults_to_first_element_for_non_i2c_list_battery_type(self, basic_model) -> None: """ @@ -2395,12 +2484,11 @@ def test_system_logs_error_when_gnss_conn_type_is_neither_serial_nor_can(self, b fake_gnss_conn: dict[str, Any] = {"99": {"type": ["USB"], "protocol": "Unknown"}} monkeypatch.setattr(_import_module, "GNSS_RECEIVER_CONNECTION", fake_gnss_conn) + basic_model.set_component_value(("GNSS Receiver", "FC Connection", "Type"), "SERIAL3") with patch.object(_import_module, "logging_error") as mock_err: basic_model._set_gnss_type_from_fc_parameters({"GPS_TYPE": 99}) - # Verify error was logged about invalid connection type - logged_text = " ".join(str(call) for call in mock_err.call_args_list) - assert "Invalid GNSS connection type" in logged_text + mock_err.assert_called_once_with("Invalid GNSS connection type %s", ["USB"]) result = basic_model.get_component_value(("GNSS Receiver", "FC Connection", "Type")) assert result == "None" @@ -2543,3 +2631,281 @@ def test_system_skips_second_rc_receiver_serial_assignment(self, basic_model) -> result = basic_model.get_component_value(("RC Receiver", "FC Connection", "Type")) assert result == "SERIAL1" # Only first RC Receiver assigned + + @pytest.mark.parametrize( + "fc_parameters", + [ + {"GPS1_TYPE": 9, "CAN_D1_PROTOCOL": 1}, + {"GPS1_TYPE": 9, "CAN_P1_DRIVER": 1}, + {"GPS1_TYPE": 9, "CAN_P2_DRIVER": 1}, + ], + ) + def test_gnss_can_assignment_requires_both_protocol_and_driver(self, basic_model, fc_parameters: dict[str, int]) -> None: + """An incomplete DroneCAN configuration must not be accepted as a connected GNSS receiver.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as log_error: + basic_model._set_gnss_type_from_fc_parameters(fc_parameters) + + log_error.assert_called_once_with( + "Invalid CAN_Dx_PROTOCOL %s and CAN_Px_DRIVER %s for GNSS Receiver", + fc_parameters.get("CAN_D1_PROTOCOL"), + fc_parameters.get("CAN_P1_DRIVER"), + ) + assert basic_model.get_component_value(("GNSS Receiver", "FC Connection", "Type")) == "None" + + def test_missing_gnss_type_uses_disabled_default_without_error(self, basic_model) -> None: + """When neither GPS type parameter is present, the documented zero default disables GNSS.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as log_error: + basic_model._set_gnss_type_from_fc_parameters({}) + + log_error.assert_not_called() + assert basic_model.get_component_value(("GNSS Receiver", "FC Connection", "Type")) == "None" + assert basic_model.get_component_value(("GNSS Receiver", "FC Connection", "Protocol")) == "None" + + def test_process_fc_parameters_checks_all_protocol_dictionaries_with_exact_metadata_keys(self, realistic_model) -> None: + """The top-level importer verifies each protocol map against the matching documentation key.""" + realistic_model.set_component_value(("Flight Controller", "Firmware", "Type"), "ArduPlane") + fc_parameters = {"Q_FRAME_CLASS": 1, "Q_ENABLE": 0} + doc = {"GPS_TYPE": {"values": {}}, "Q_FRAME_CLASS": {"values": {}}} + esc_protocols = {"esc": {"protocol": "DShot"}} + frame_protocols = {"frame": {"protocol": "Quad"}} + + with ( + patch.object(realistic_model, "_verify_dict_is_uptodate", return_value=True) as verify, + patch.object(_import_module, "get_esc_connection_sub_dict", return_value=esc_protocols) as esc_dict, + patch.object(_import_module, "get_frame_class_as_protocol_dict", return_value=frame_protocols) as frame_dict, + patch.object(_import_module, "get_frame_info", return_value=("frame", None)) as frame_info, + ): + realistic_model.process_fc_parameters(fc_parameters, doc) + + assert [call.args for call in verify.call_args_list] == [ + (doc, _import_module.SERIAL_PROTOCOLS_DICT, "SERIAL1_PROTOCOL", "values"), + (doc, _import_module.BATT_MONITOR_CONNECTION, "BATT_MONITOR", "values"), + (doc, _import_module.GNSS_RECEIVER_CONNECTION, "GPS_TYPE", "values"), + (doc, esc_protocols, "MOT_PWM_TYPE", "values"), + (doc, _import_module.RC_PROTOCOLS_DICT, "RC_PROTOCOLS", "Bitmask"), + (doc, frame_protocols, "Q_FRAME_CLASS", "values"), + ] + esc_dict.assert_any_call("ArduPlane") + frame_dict.assert_called_once_with("ArduPlane") + frame_info.assert_called_once_with(fc_parameters, "ArduPlane") + + def test_arduplane_without_frame_parameters_clears_template_frame_class(self, realistic_model) -> None: + """An ArduPlane import without frame data clears the template's stale Quad frame class.""" + realistic_model.set_component_value(("Flight Controller", "Firmware", "Type"), "ArduPlane") + realistic_model.set_component_value(("Frame", "Specifications", "Frame class"), "Quad") + + with patch.object(realistic_model, "_verify_dict_is_uptodate", return_value=True): + realistic_model.process_fc_parameters({}, {}) + + assert realistic_model.get_component_value(("Frame", "Specifications", "Frame class")) == "Undefined" + + @pytest.mark.parametrize( + ("param_name", "voltage_type", "value", "expected_cell"), + [ + ("BATT_ARM_VOLT", "Volt per cell arm", 18.0, 4.5), + ("BATT_LOW_VOLT", "Volt per cell low", 10.0, 2.5), + ], + ) + def test_import_battery_voltage_logs_exact_out_of_range_values( + self, basic_model, param_name: str, voltage_type: str, value: float, expected_cell: float + ) -> None: + """Out-of-range per-cell values report the computed value, chemistry, and limits.""" + specs = BatteryVoltageSpecs(4, 3.0, 4.2, "Lipo", {param_name: value}) + + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as log_warning: + basic_model.import_bat_voltage(specs, param_name, voltage_type) + + log_warning.assert_called_once_with( + "Calculated %s voltage %.2f V is out of expected range for %s chemistry (%.2f - %.2f V)", + voltage_type, + expected_cell, + "Lipo", + 3.0, + 4.2, + ) + + @pytest.mark.parametrize( + ("value", "expected_message"), + [ + (None, "unsupported operand type(s) for /: 'NoneType' and 'int'"), + ("not-a-number", "unsupported operand type(s) for /: 'str' and 'int'"), + ], + ) + def test_import_battery_voltage_logs_parameter_and_conversion_error( + self, basic_model, value: object, expected_message: str + ) -> None: + """Invalid FC voltage values retain the parameter name and conversion error in logs.""" + specs = BatteryVoltageSpecs(4, 3.0, 4.2, "Lipo", {"BATT_ARM_VOLT": value}) # type: ignore[dict-item] + + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as log_error: + basic_model.import_bat_voltage(specs, "BATT_ARM_VOLT", "Volt per cell arm") + + log_error.assert_called_once_with("Error processing %s parameter: %s", "BATT_ARM_VOLT", expected_message) + + def test_battery_chemistry_detection_ignores_zero_priority_voltage_and_uses_arm_voltage( + self, basic_model, monkeypatch + ) -> None: + """A zero high-priority voltage is skipped while a valid lower-priority clue is scored.""" + scored_voltages: list[float] = [] + monkeypatch.setattr( + BatteryCell, + "chemistry_voltage_score", + staticmethod(lambda _chemistry, voltage, _voltage_type: scored_voltages.append(voltage) or float("nan")), + ) + monkeypatch.setattr(BatteryCell, "best_chemistry_for_voltage", staticmethod(lambda _voltage, _kind: None)) + + assert ( + basic_model._detect_battery_chemistry_from_voltages({"MOT_BAT_VOLT_MAX": 0, "BATT_ARM_VOLT": 15.2}, "Lipo") is None + ) + assert scored_voltages == [15.2] + + def test_battery_chemistry_detection_scores_one_volt_before_lower_priority_clue(self, basic_model, monkeypatch) -> None: + """Exactly one volt is still evaluated because only nonpositive readings are skipped.""" + scored_voltages: list[float] = [] + monkeypatch.setattr( + BatteryCell, + "chemistry_voltage_score", + staticmethod(lambda _chemistry, voltage, _voltage_type: scored_voltages.append(voltage) or float("nan")), + ) + monkeypatch.setattr(BatteryCell, "best_chemistry_for_voltage", staticmethod(lambda _voltage, _kind: None)) + + basic_model._detect_battery_chemistry_from_voltages({"MOT_BAT_VOLT_MAX": 1.0, "BATT_ARM_VOLT": 15.2}, "Lipo") + + assert scored_voltages == [1.0, 15.2] + + def test_battery_chemistry_nan_score_warning_identifies_chemistry_and_voltage_type(self, basic_model, monkeypatch) -> None: + """A NaN compatibility score is logged with the exact chemistry and input voltage type.""" + monkeypatch.setattr( + BatteryCell, + "chemistry_voltage_score", + staticmethod(lambda _chemistry, _voltage, _voltage_type: float("nan")), + ) + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as log_warning: + basic_model._detect_battery_chemistry_from_voltages({"BATT_ARM_VOLT": 15.2}, "Lipo") + + log_warning.assert_called_once_with( + "Current chemistry %s does not have valid volt per cell for %s, ignoring current chemistry", + "Lipo", + "Volt per cell arm", + ) + + @pytest.mark.parametrize("value", [0, -1]) + def test_cell_estimation_logs_exact_invalid_voltage(self, basic_model, value: int) -> None: + """Zero and negative pack voltages are rejected with their parameter and value.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as log_warning: + result = basic_model._estimate_cells_from_voltage_param_default( + "BATT_LOW_VOLT", value, "Volt per cell low", "Lipo" + ) + + assert result is None + log_warning.assert_called_once_with("Voltage value for %s is zero or invalid: %s", "BATT_LOW_VOLT", value) + + def test_cell_estimation_logs_exact_unreasonable_cell_count(self, basic_model) -> None: + """Pack estimates beyond the supported 50-cell range identify the estimate and parameter.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as log_warning: + result = basic_model._estimate_cells_from_voltage_param_default("BATT_LOW_VOLT", 220, "Volt per cell low", "Lipo") + + assert result is None + log_warning.assert_called_once_with("Estimated cell count %d from %s seems unreasonable", 61, "BATT_LOW_VOLT") + + @pytest.mark.parametrize("recommended_voltage", [float("nan"), 0.0]) + def test_cell_estimation_rejects_missing_or_zero_recommended_voltage( + self, basic_model, monkeypatch, recommended_voltage: float + ) -> None: + """Unavailable and nonpositive per-cell defaults cannot produce a pack estimate.""" + monkeypatch.setattr( + BatteryCell, + "recommended_cell_voltage", + staticmethod(lambda _chemistry, _kind: recommended_voltage), + ) + + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as log_error: + result = basic_model._estimate_cells_from_voltage_param_default("BATT_LOW_VOLT", 18.0, "Volt per cell low", "Lipo") + + assert result is None + log_error.assert_called_once_with("No recommended voltage for %s %s", "Lipo", "Volt per cell low") + + def test_cell_estimation_rejects_one_volt_pack_at_zero_boundary(self, basic_model) -> None: + """A one-volt total reading is rejected as invalid before cell estimation.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as log_warning: + result = basic_model._estimate_cells_from_voltage_param_default("BATT_LOW_VOLT", 1.0, "Volt per cell low", "Lipo") + + assert result is None + log_warning.assert_called_once_with("Estimated cell count %d from %s seems unreasonable", 0, "BATT_LOW_VOLT") + + @pytest.mark.parametrize( + ("value", "expected_error"), + [ + (None, "float() argument must be a string or a real number, not 'NoneType'"), + ("not-a-number", "could not convert string to float: 'not-a-number'"), + ], + ) + def test_cell_estimation_logs_exact_parameter_conversion_error( + self, basic_model, value: object, expected_error: str + ) -> None: + """Unparsable pack voltages report the source parameter and original conversion exception.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as log_error: + result = basic_model._estimate_cells_from_voltage_param_default( + "BATT_LOW_VOLT", + value, + "Volt per cell low", + "Lipo", # type: ignore[arg-type] + ) + + assert result is None + log_error.assert_called_once_with("Error processing %s parameter: %s", "BATT_LOW_VOLT", expected_error) + + def test_import_battery_voltage_accepts_exact_minimum_cell_voltage(self, basic_model) -> None: + """A cell voltage exactly at the chemistry minimum is valid and stored.""" + specs = BatteryVoltageSpecs(4, 3.0, 4.2, "Lipo", {"BATT_ARM_VOLT": 12.0}) + + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as log_warning: + basic_model.import_bat_voltage(specs, "BATT_ARM_VOLT", "Volt per cell arm") + + assert basic_model.get_component_value(("Battery", "Specifications", "Volt per cell arm")) == pytest.approx(3.0) + log_warning.assert_not_called() + + def test_import_battery_voltage_rounds_per_cell_value_to_four_places(self, basic_model) -> None: + """Imported per-cell voltages use the four-decimal precision stored by battery specs.""" + specs = BatteryVoltageSpecs(4, 3.0, 4.2, "Lipo", {"BATT_ARM_VOLT": 12.4938}) + + with patch.object(basic_model, "set_component_value", wraps=basic_model.set_component_value) as set_value: + basic_model.import_bat_voltage(specs, "BATT_ARM_VOLT", "Volt per cell arm") + + set_value.assert_called_once_with(("Battery", "Specifications", "Volt per cell arm"), 3.1235) + + def test_chemistry_detection_continues_after_nan_score_to_lower_priority_voltage(self, basic_model, monkeypatch) -> None: + """A NaN score for a higher-priority voltage does not suppress a later usable clue.""" + scored_types: list[str] = [] + monkeypatch.setattr( + BatteryCell, + "chemistry_voltage_score", + staticmethod( + lambda _chemistry, _voltage, voltage_type: ( + scored_types.append(voltage_type) or (float("nan") if voltage_type == "Volt per cell max" else 0.5) + ) + ), + ) + monkeypatch.setattr( + BatteryCell, + "best_chemistry_for_voltage", + staticmethod(lambda _voltage, voltage_type: "LiIon" if voltage_type == "Volt per cell arm" else None), + ) + + result = basic_model._detect_battery_chemistry_from_voltages({"MOT_BAT_VOLT_MAX": 16.8, "BATT_ARM_VOLT": 15.2}, "Lipo") + + assert result == "LiIon" + assert scored_types == ["Volt per cell max", "Volt per cell arm"] + + def test_chemistry_detection_does_not_preserve_current_chemistry_at_exact_score_threshold( + self, basic_model, monkeypatch + ) -> None: + """A chemistry score equal to 0.40 is not within the keep-current threshold.""" + monkeypatch.setattr( + BatteryCell, + "chemistry_voltage_score", + staticmethod(lambda _chemistry, _voltage, _kind: 0.40), + ) + monkeypatch.setattr(BatteryCell, "best_chemistry_for_voltage", staticmethod(lambda _voltage, _kind: "LiIon")) + + assert basic_model._detect_battery_chemistry_from_voltages({"BATT_ARM_VOLT": 15.2}, "Lipo") == "LiIon" diff --git a/tests/test_data_model_vehicle_components_templates.py b/tests/test_data_model_vehicle_components_templates.py index cff797117..255b81eb8 100755 --- a/tests/test_data_model_vehicle_components_templates.py +++ b/tests/test_data_model_vehicle_components_templates.py @@ -11,7 +11,7 @@ """ import pytest -from test_data_model_vehicle_components_common import BasicTestMixin, ComponentDataModelFixtures, RealisticDataTestMixin +from test_data_model_vehicle_components_common import ComponentDataModelFixtures from ardupilot_methodic_configurator.data_model_vehicle_components_base import ComponentDataModelBase from ardupilot_methodic_configurator.data_model_vehicle_components_templates import ComponentDataModelTemplates @@ -19,7 +19,7 @@ # pylint: disable=too-many-public-methods,too-many-lines -class TestComponentDataModelTemplates(BasicTestMixin, RealisticDataTestMixin): +class TestComponentDataModelTemplates: """Tests for the ComponentDataModelTemplates class.""" @pytest.fixture @@ -650,6 +650,26 @@ def test_system_converts_values_to_correct_types(self, empty_model) -> None: assert result["Specifications"]["Chemistry"] == "LiPo" # string assert result["Specifications"]["Discharge"] == 25 # int + def test_extract_uses_schema_boolean_type_for_false_text(self) -> None: + """Use the configured bool datatype instead of preserving the text value.""" + component_datatypes = {"Sensor": {"Settings": {"Enabled": bool}}} + model = ComponentDataModelTemplates({}, component_datatypes, ComponentDataModelFixtures.create_schema()) + + result = model.extract_component_data_from_entries("Sensor", {("Sensor", "Settings", "Enabled"): "false"}) + + assert result == {"Settings": {"Enabled": False}} + + def test_schema_cast_failure_reports_the_component_entry_path(self, caplog: pytest.LogCaptureFixture) -> None: + """Keep the entry path in diagnostics when a schema-directed conversion fails.""" + component_datatypes = {"Sensor": {"Settings": {"Gain": float}}} + model = ComponentDataModelTemplates({}, component_datatypes, ComponentDataModelFixtures.create_schema()) + + with caplog.at_level("WARNING"): + result = model.extract_component_data_from_entries("Sensor", {("Sensor", "Settings", "Gain"): "invalid"}) + + assert result == {"Settings": {"Gain": "invalid"}} + assert "path ('Sensor', 'Settings', 'Gain')" in caplog.text + def test_system_trims_whitespace_from_values(self, empty_model) -> None: """ System extraction handles whitespace correctly. diff --git a/tests/test_data_model_vehicle_components_validation.py b/tests/test_data_model_vehicle_components_validation.py index ce8efd810..7411e0766 100755 --- a/tests/test_data_model_vehicle_components_validation.py +++ b/tests/test_data_model_vehicle_components_validation.py @@ -14,13 +14,9 @@ from unittest.mock import patch as _patch import pytest -from test_data_model_vehicle_components_common import ( - SAMPLE_DOC_DICT, - BasicTestMixin, - ComponentDataModelFixtures, - RealisticDataTestMixin, -) +from test_data_model_vehicle_components_common import SAMPLE_DOC_DICT, ComponentDataModelFixtures +import ardupilot_methodic_configurator.data_model_vehicle_components_validation as validation_module from ardupilot_methodic_configurator.backend_filesystem_vehicle_components import VehicleComponents from ardupilot_methodic_configurator.battery_cell_voltages import BatteryCell from ardupilot_methodic_configurator.data_model_vehicle_components_json_schema import VehicleComponentsJsonSchema @@ -31,7 +27,7 @@ ESC_TELEMETRY_SERIAL_PORTS = tuple(f"SERIAL{number}" for number in range(1, 9)) -class TestComponentDataModelValidation(BasicTestMixin, RealisticDataTestMixin): +class TestComponentDataModelValidation: """Tests for the ComponentDataModelValidation class.""" @pytest.fixture @@ -299,6 +295,31 @@ def test_init_possible_choices_fallbacks(self, empty_model) -> None: # Should have fallback choices for missing parameters assert isinstance(model._possible_choices, dict) + def test_correct_display_values_recurses_through_nested_component_data(self, empty_model) -> None: + """Loaded serial display labels are corrected inside nested component records.""" + display, serial_port = next(iter(validation_module.SERIAL_DISPLAY_TO_KEY.items())) + nested_component = {"FC Connection": {"Type": display}} + + empty_model._correct_values_recursive(nested_component, ("Telemetry",)) + + assert nested_component["FC Connection"]["Type"] == serial_port + + def test_init_possible_choices_does_not_log_errors_without_metadata(self, empty_model, caplog) -> None: + """Offline fallback choices initialize without reporting missing optional metadata as an error.""" + empty_model.init_possible_choices({}) + + assert not [record for record in caplog.records if record.levelname == "ERROR"] + + def test_init_possible_choices_logs_the_missing_frame_class_values(self, empty_model, caplog) -> None: + """Unavailable frame-class metadata logs both the missing values and missing fallback names.""" + empty_model.init_possible_choices({"FRAME_CLASS": {}}) + + errors = [record for record in caplog.records if record.levelname == "ERROR"] + assert [(record.msg, record.args) for record in errors] == [ + ("No values found for %s in the metadata", ("FRAME_CLASS",)), + ("No fallback values found for %s", ("FRAME_CLASS",)), + ] + # Test validate_entry_limits method def test_validate_entry_limits_valid_values(self, realistic_model) -> None: """ @@ -375,6 +396,14 @@ def test_validate_entry_limits_value_errors(self, realistic_model) -> None: assert error_msg != "" assert corrected_value is None + @pytest.mark.parametrize("field", ["min", "max"]) + @pytest.mark.parametrize("value", ["heavy", "not-a-number"]) + def test_validate_entry_limits_reports_the_field_and_type(self, realistic_model, field: str, value: str) -> None: + """Invalid numeric values identify the field and expected data type.""" + path = ("Frame", "Specifications", f"TOW {field} Kg") + + assert realistic_model.validate_entry_limits(value, path) == ("Invalid float value for Takeoff Weight", None) + def test_validate_entry_limits_tow_relationships(self, realistic_model) -> None: """ Test validate_entry_limits for takeoff weight relationships. @@ -420,9 +449,13 @@ def test_validate_entry_limits_non_validation_paths(self, realistic_model) -> No model = realistic_model # Test with a path not in VALIDATION_RULES - error_msg, corrected_value = model.validate_entry_limits("any_value", ("Unknown", "Path", "Value")) - assert error_msg == "" - assert corrected_value is None + for path in ( + ("Unknown", "Path", "Value"), + ("Battery", "Specifications", "TOW min Kg"), + ): + error_msg, corrected_value = model.validate_entry_limits("any_value", path) + assert error_msg == "" + assert corrected_value is None # Test validate_cell_voltage method def test_validate_cell_voltage_valid_voltages(self, realistic_model) -> None: @@ -876,6 +909,53 @@ def test_validate_all_data_duplicate_connections(self, realistic_model) -> None: assert len(errors) > 0 assert "Duplicate FC connection" in errors[0] + def test_validate_all_data_reports_every_duplicate_connection(self, realistic_model) -> None: + """Validation continues after a duplicate so users see every conflicting field.""" + realistic_model.init_possible_choices({}) + entries = { + ("RC Receiver", "FC Connection", "Type"): "SERIAL3", + ("GNSS Receiver", "FC Connection", "Type"): "SERIAL3", + ("ESC", "FC->ESC Connection", "Type"): "SERIAL3", + } + + is_valid, errors = realistic_model.validate_all_data(entries) + + assert is_valid is False + assert errors == [ + "Duplicate FC connection type 'SERIAL3' for GNSS Receiver>FC Connection>Type", + "Duplicate FC connection type 'SERIAL3' for ESC>FC->ESC Connection>Type", + ] + + def test_validate_all_data_keeps_checking_after_an_allowed_shared_connection(self, realistic_model) -> None: + """An allowed telemetry/receiver pair does not stop later connection checks.""" + realistic_model.init_possible_choices({}) + entries = { + ("Telemetry", "FC Connection", "Type"): "SERIAL1", + ("RC Receiver", "FC Connection", "Type"): "SERIAL1", + ("GNSS Receiver", "FC Connection", "Type"): "SERIAL1", + } + + is_valid, errors = realistic_model.validate_all_data(entries) + + assert is_valid is False + assert errors == ["Duplicate FC connection type 'SERIAL1' for GNSS Receiver>FC Connection>Type"] + + @pytest.mark.parametrize("connection", ["I2C1", "I2C2", "I2C3", "I2C4"]) + def test_validate_all_data_allows_shared_i2c_connections(self, realistic_model, connection: str) -> None: + """I2C buses can be shared by FC components without duplicate-port errors.""" + realistic_model.init_possible_choices({}) + realistic_model._possible_choices[("RC Receiver", "FC Connection", "Type")] = (connection,) + realistic_model._possible_choices[("GNSS Receiver", "FC Connection", "Type")] = (connection,) + is_valid, errors = realistic_model.validate_all_data( + { + ("RC Receiver", "FC Connection", "Type"): connection, + ("GNSS Receiver", "FC Connection", "Type"): connection, + } + ) + + assert is_valid is True + assert errors == [] + def test_validate_all_data_allowed_duplicates(self, realistic_model) -> None: """ Test validate_all_data with allowed duplicate connections. @@ -897,6 +977,31 @@ def test_validate_all_data_allowed_duplicates(self, realistic_model) -> None: assert is_valid is True assert len(errors) == 0 + @pytest.mark.parametrize( + ("path", "value"), + [ + (("Frame", "Specifications", "TOW max Kg"), "1000"), + (("Battery", "Specifications", "Volt per cell max"), "9.0"), + ], + ) + def test_limit_validation_reports_errors_and_stores_clamped_values( + self, realistic_model, path: tuple[str, str, str], value: str + ) -> None: + """General limit validation reports the specific validator result and stores its correction.""" + model = realistic_model + if path[0] == "Battery": + model.set_component_value(("Battery", "Specifications", "Chemistry"), "Lipo") + expected_error, correction = ( + model.validate_entry_limits(value, path) if path[0] == "Frame" else model.validate_cell_voltage(value, path) + ) + errors: list[str] = [] + + model._validate_limits_and_voltages(path, value, ">".join(path), errors) + + assert errors == [expected_error] + assert correction is not None + assert model.get_component_value(path) == correction + def test_validate_all_data_telemetry_rc_combinations(self, realistic_model) -> None: """ Test validate_all_data with allowed Telemetry/RC Receiver combinations. @@ -1005,7 +1110,7 @@ def test_validate_all_data_motor_poles_invalid_values(self, realistic_model) -> is_valid, errors = model.validate_all_data(invalid_entries) assert is_valid is False assert len(errors) > 0 - assert "must be even" in errors[0] + assert errors == ["Number of magnetic rotor poles must be even for Motors>Specifications>Poles"] def test_validate_all_data_motor_poles_invalid_string(self, realistic_model) -> None: """ @@ -1025,7 +1130,7 @@ def test_validate_all_data_motor_poles_invalid_string(self, realistic_model) -> is_valid, errors = model.validate_all_data(invalid_entries) assert is_valid is False assert len(errors) > 0 - assert "Invalid int value" in errors[0] + assert errors == ["Invalid int value for Motor Poles"] # Test get_combobox_values_for_path method (inherited from base class) def test_get_combobox_values_for_path(self, realistic_model) -> None: @@ -1789,11 +1894,14 @@ def test_set_component_value_non_firmware_type_does_not_update_frame_class_choic model.init_possible_choices({}) model.set_component_value(("Flight Controller", "Firmware", "Type"), "ArduCopter") choices_before = model._possible_choices.get(("Frame", "Specifications", "Frame class"), ()) + chemistry_before = model._battery_chemistry model.set_component_value(("Frame", "Specifications", "TOW min Kg"), 0.5) + model.set_component_value(("Frame", "Notes"), "ArduPlane") choices_after = model._possible_choices.get(("Frame", "Specifications", "Frame class"), ()) assert choices_after == choices_before + assert model._battery_chemistry == chemistry_before def test_init_possible_choices_includes_frame_class_for_default_firmware_type(self, empty_model) -> None: """ @@ -2423,6 +2531,62 @@ def test_user_switches_from_can_to_pwm_and_receives_current_telemetry_choices( class TestFirmwareMetadataChoices: """Firmware metadata and offline defaults supply the component editor's choices.""" + def test_esc_protocol_choices_match_the_selected_output_type_and_keep_order( + self, choice_model: ComponentDataModelValidation, monkeypatch: pytest.MonkeyPatch + ) -> None: + """ESC output choices include only matching tuple types and preserve unique protocol order.""" + choice_model.set_component_value(("Flight Controller", "Firmware", "Type"), "ArduCopter") + requested_firmware_types: list[str] = [] + + def connection_options(firmware_type: str) -> dict: + requested_firmware_types.append(firmware_type) + return { + "first": {"type": ("SERIAL1", "Main Out"), "protocol": "Shared"}, + "duplicate": {"type": ("Main Out",), "protocol": "Shared"}, + "second": {"type": ("Main Out",), "protocol": "DShot"}, + } + + monkeypatch.setattr(validation_module, "get_esc_connection_sub_dict", connection_options) + + assert choice_model._get_esc_connection_protocols_for_type("Main Out") == ("Shared", "DShot") + assert requested_firmware_types == ["ArduCopter"] + + def test_none_esc_telemetry_type_only_allows_none_protocol(self, choice_model: ComponentDataModelValidation) -> None: + """Disabling ESC telemetry exposes only the None protocol.""" + protocol_path = ("ESC", "ESC->FC Telemetry", "Protocol") + + choice_model._update_esc_telemetry_type_protocol_choices("None", protocol_path) + + assert choice_model.get_combobox_values_for_path(protocol_path) == ("None",) + + @pytest.mark.parametrize( + ("component", "section", "expected"), + [ + ("Battery Monitor", "FC Connection", ("Disabled",)), + ("GNSS Receiver", "FC Connection", ("None",)), + ], + ) + def test_disabled_battery_and_gnss_connections_keep_their_protocol_fallbacks( + self, choice_model: ComponentDataModelValidation, component: str, section: str, expected: tuple[str, ...] + ) -> None: + """Selecting None retains the defined disabled protocol choice for each component.""" + protocol_path = (component, section, "Protocol") + + choice_model._update_possible_choices_for_path((component, section, "Type"), "None") + + assert choice_model.get_combobox_values_for_path(protocol_path) == expected + + @pytest.mark.parametrize("component", ["Battery Monitor", "GNSS Receiver"]) + def test_unsupported_battery_and_gnss_connections_fall_back_to_none( + self, choice_model: ComponentDataModelValidation, component: str + ) -> None: + """Unknown connection types retain a safe None protocol option.""" + protocol_path = (component, "FC Connection", "Protocol") + + choice_model._update_possible_choices_for_path((component, "FC Connection", "Type"), "unsupported") + + assert choice_model.get_combobox_values_for_path(protocol_path) == ("None",) + @pytest.fixture def choice_model(self) -> ComponentDataModelValidation: """Provide a real model with no saved connection types to override initial choices.""" @@ -2590,6 +2754,97 @@ def test_user_sees_loaded_motor_protocols_when_selecting_a_pwm_output( assert choice_model.get_combobox_values_for_path(("ESC", "FC->ESC Connection", "Protocol")) == expected + @pytest.mark.parametrize("mode", ["union", "specific"]) + def test_pwm_telemetry_choices_keep_supported_mappings_in_order( + self, choice_model: ComponentDataModelValidation, monkeypatch: pytest.MonkeyPatch, mode: str + ) -> None: + """PWM telemetry choices preserve supported mappings in order.""" + choice_model.set_component_value(("Flight Controller", "Firmware", "Type"), "") + entries = { + "serial-only": {"type": ("SERIAL8",), "protocol": "FETtecOneWire", "ESC_to_FC": {}}, + "mapped-pwm": { + "type": validation_module.PWM_OUT_PORTS, + "protocol": "Normal", + "ESC_to_FC": { + ("same_as_FC_to_ESC",): "BDShotOnly", + ("SERIAL1",): "Scripting", + ("SERIAL3",): "ESC Telemetry", + }, + }, + } + requested_firmware_types: list[str] = [] + + def connection_options(firmware_type: str) -> dict: + requested_firmware_types.append(firmware_type) + return entries + + monkeypatch.setattr(validation_module, "get_esc_connection_sub_dict", connection_options) + + if mode == "union": + choices = choice_model._compute_esc_telemetry_choices_union_pwm("Main Out") + else: + choices = choice_model._compute_esc_telemetry_choices_pwm("Main Out", "Normal") + + assert requested_firmware_types == [""] + assert choices == ( + ("None", "Main Out", "SERIAL1", "SERIAL3"), + ("None", "BDShotOnly", "Scripting", "ESC Telemetry"), + ) + + @pytest.mark.parametrize("mode", ["union", "specific"]) + def test_pwm_telemetry_choices_use_the_active_firmware_metadata( + self, choice_model: ComponentDataModelValidation, monkeypatch: pytest.MonkeyPatch, mode: str + ) -> None: + """PWM back-channel choices come from the active firmware's metadata.""" + choice_model.set_component_value(("Flight Controller", "Firmware", "Type"), "ArduCopter") + requested_firmware_types: list[str] = [] + + def connection_options(firmware_type: str) -> dict: + requested_firmware_types.append(firmware_type) + return { + "control": { + "type": validation_module.PWM_OUT_PORTS, + "protocol": "Normal", + "ESC_to_FC": {("same_as_FC_to_ESC",): "BDShotOnly"}, + } + } + + monkeypatch.setattr(validation_module, "get_esc_connection_sub_dict", connection_options) + choices = ( + choice_model._compute_esc_telemetry_choices_union_pwm("Main Out") + if mode == "union" + else choice_model._compute_esc_telemetry_choices_pwm("Main Out", "Normal") + ) + + assert requested_firmware_types == ["ArduCopter"] + assert choices[1] == ("None", "BDShotOnly") + + def test_serial_telemetry_choices_use_the_active_firmware_metadata( + self, choice_model: ComponentDataModelValidation, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Serial back-channel choices use the current control protocol's firmware mapping.""" + choice_model.set_component_value(("Flight Controller", "Firmware", "Type"), "ArduCopter") + choice_model.set_component_value(("ESC", "FC->ESC Connection", "Type"), "Main Out") + choice_model.set_component_value(("ESC", "FC->ESC Connection", "Protocol"), "Normal") + requested_firmware_types: list[str] = [] + + def connection_options(firmware_type: str) -> dict: + requested_firmware_types.append(firmware_type) + return { + "control": { + "type": ("Main Out",), + "protocol": "Normal", + "ESC_to_FC": {("SERIAL1",): "Scripting"}, + } + } + + monkeypatch.setattr(validation_module, "get_esc_connection_sub_dict", connection_options) + + choice_model._update_esc_telemetry_type_protocol_choices("SERIAL1", ("ESC", "ESC->FC Telemetry", "Protocol")) + + assert choice_model.get_combobox_values_for_path(("ESC", "ESC->FC Telemetry", "Protocol")) == ("Scripting",) + assert requested_firmware_types == ["ArduCopter"] + @pytest.mark.parametrize("motor_metadata", [None, {}, {"values": {}}]) def test_user_keeps_offline_pwm_protocols_when_motor_metadata_is_missing_or_empty( self, choice_model: ComponentDataModelValidation, motor_metadata: dict[str, dict[str, str]] | None diff --git a/tests/test_frontend_tkinter_file_browser.py b/tests/test_frontend_tkinter_file_browser.py index 15619e309..429a7c803 100755 --- a/tests/test_frontend_tkinter_file_browser.py +++ b/tests/test_frontend_tkinter_file_browser.py @@ -207,6 +207,23 @@ def _headless_browser_window(mock_tkinter_context) -> typing.Iterator[FileBrowse yield window +@pytest.fixture(name="real_widget_browser") +def _real_widget_browser( + tk_root: tk.Tk, +) -> typing.Iterator[tuple[FileBrowserWindow, MagicMock]]: + """Build a real browser window and capture its user-facing tooltip guidance.""" + parameter_editor = MagicMock() + parameter_editor.get_vehicle_directory.return_value = str(Path.cwd()) + with patch("ardupilot_methodic_configurator.frontend_tkinter_file_browser.show_tooltip") as add_tooltip: + window = FileBrowserWindow(tk_root, parameter_editor, MagicMock(), task_runner=ImmediateTaskRunner()) + try: + yield window, add_tooltip + finally: + with contextlib.suppress(tk.TclError): + window.root.grab_release() + window.root.destroy() + + class TestFileBrowserWindow: """Verify browser interactions, lifecycle, and backend dispatch.""" @@ -266,6 +283,107 @@ def test_action_layout_and_help_link(self, tk_root: tk.Tk) -> None: window.root.grab_release() window.root.destroy() + def test_user_sees_side_by_side_local_and_remote_panels(self, real_widget_browser) -> None: + """ + The browser gives both local and flight-controller files a usable directory view. + + GIVEN: A user opens the file browser + WHEN: The browser lays out its two file panels + THEN: Both directories are visible side by side with working entry fields + """ + window, _tooltips = real_widget_browser + remote_panel = window.remote_tree.master + local_panel = window.local_tree.master + panels = remote_panel.master + + assert isinstance(panels, ttk.PanedWindow) + assert str(panels.cget("orient")) == "horizontal" + assert panels.panes() == (str(remote_panel), str(local_panel)) + assert int(panels.pane(remote_panel)["weight"]) == 1 + assert int(panels.pane(local_panel)["weight"]) == 1 + assert panels.pack_info()["side"] == "top" + assert panels.pack_info()["fill"] == "both" + assert bool(int(panels.pack_info()["expand"])) + assert int(panels.pack_info()["padx"]) == 8 + assert tuple(map(int, panels.pack_info()["pady"])) == (8, 4) + assert window.remote_directory_var.get() == FileBrowserWindow.DEFAULT_REMOTE_DIRECTORY + assert window.local_directory_var.get() == str(Path.cwd()) + assert window.remote_directory_entry.master.master is remote_panel + assert window.local_directory_entry.master.master is local_panel + assert window.remote_directory_entry.bind("") + assert window.local_directory_entry.bind("") + for entry in (window.remote_directory_entry, window.local_directory_entry): + assert entry.pack_info()["side"] == "left" + assert entry.pack_info()["fill"] == "x" + assert bool(int(entry.pack_info()["expand"])) + + def test_user_can_navigate_and_select_files_in_either_panel(self, real_widget_browser) -> None: + """Each panel offers its own directory navigation and multi-file selection controls.""" + window, _tooltips = real_widget_browser + assert window.remote_parent_button.cget("text") == "↑" + assert int(window.remote_parent_button.cget("width")) == 3 + assert window.remote_parent_button.cget("command") + assert window.local_parent_button.cget("text") == "↑" + assert int(window.local_parent_button.cget("width")) == 3 + assert window.local_parent_button.cget("command") + assert window.browse_local_button.cget("text") == "Browse" + assert window.browse_local_button.cget("command") + remote_controls = [ + widget for widget in window.remote_directory_entry.master.winfo_children() if isinstance(widget, ttk.Button) + ] + local_controls = [ + widget for widget in window.local_directory_entry.master.winfo_children() if isinstance(widget, ttk.Button) + ] + assert [button.cget("text") for button in remote_controls] == ["↑", "⟳", "Select all"] + assert [button.cget("text") for button in local_controls] == ["↑", "Browse", "⟳", "Select all"] + assert all(button.cget("command") for button in (*remote_controls, *local_controls)) + assert window.remote_tree.master is window.remote_directory_entry.master.master + assert window.local_tree.master is window.local_directory_entry.master.master + for tree in (window.remote_tree, window.local_tree): + assert tuple(tree.cget("columns")) == ("name", "type", "size", "modified") + assert str(tree.cget("selectmode")) == "extended" + + def test_user_can_transfer_files_and_choose_transfer_verification(self, real_widget_browser) -> None: + """The action area labels transfers clearly and links checksum verification to its setting.""" + window, _tooltips = real_widget_browser + assert window.download_button.cget("text") == "Download selected →" + assert window.upload_button.cget("text") == "← Upload selected" + assert window.verify_checkbox.cget("text") == "Verify transfers with CRC32" + assert window.verify_checkbox.cget("variable") == str(window.verify_transfers_var) + assert window.download_button.cget("command") + assert window.upload_button.cget("command") + assert window.last_log_button.cget("text") == "Download last FC log" + assert window.help_button.cget("text") == "Help" + assert window.close_button.cget("text") == "Close" + action_frame = window.download_button.master + assert action_frame.pack_info()["side"] == "bottom" + assert action_frame.pack_info()["fill"] == "x" + assert int(action_frame.pack_info()["padx"]) == 8 + assert tuple(map(int, action_frame.pack_info()["pady"])) == (4, 8) + for column in range(4): + assert int(action_frame.grid_columnconfigure(column, "weight")) == 1 + assert action_frame.grid_columnconfigure(column, "uniform") == "action" + + def test_browser_help_explains_directory_controls_and_file_actions(self, real_widget_browser) -> None: + """Tooltips explain where files move and what each directory control does.""" + _window, add_tooltip = real_widget_browser + expected_tooltips = [ + "Download selected files and directories from the flight controller to the local computer", + "Upload selected files and directories from the local computer to the flight controller", + "Compare local and flight-controller checksums after each transfer", + "Download the last flight-controller .bin log file", + "Open the MAVFTP file browser user manual", + "Close the file browser", + "Go to the parent directory on the flight controller", + "Open the remote directory and refresh its contents", + "Select all remote files and directories", + "Go to the parent directory on the local computer", + "Choose a local directory", + "Refresh the local directory contents", + "Select all local files and directories", + ] + assert sorted(tooltip.args[1] for tooltip in add_tooltip.call_args_list) == sorted(expected_tooltips) + def test_local_panel_defaults_to_current_vehicle_directory(self) -> None: """The local browser starts in the vehicle directory used by the editor.""" parameter_editor = MagicMock() @@ -399,6 +517,83 @@ def test_user_sees_two_fully_navigable_file_panels(self, headless_browser_window assert window.help_button is not None assert window.close_button is not None + @pytest.mark.parametrize("remote", [False, True], ids=["local-panel", "remote-panel"]) + def test_each_tree_has_expected_options_bindings_and_context_panel(self, remote: bool) -> None: + """ + Each file panel's tree is configured for multi-selection and routes navigation to that panel. + + GIVEN: A browser window creating either its local or remote tree + WHEN: The panel tree is created + THEN: Its options, keyboard bindings, context menu, and scrollbar are connected + """ + window = _bare_window() + parent = MagicMock() + tree = MagicMock() + scrollbar = MagicMock() + window._configure_tree_columns = MagicMock() + window._show_context_menu = MagicMock(return_value="break") + window._remember_panel = MagicMock() + window._remember_panel_from_click = MagicMock() + window._remember_panel_from_selection = MagicMock() + + with ( + patch( + "ardupilot_methodic_configurator.frontend_tkinter_file_browser.ttk.Treeview", + return_value=tree, + ) as make_tree, + patch( + "ardupilot_methodic_configurator.frontend_tkinter_file_browser.ttk.Scrollbar", + return_value=scrollbar, + ) as make_scrollbar, + ): + result = window._create_tree(parent, remote=remote) + + assert result is tree + make_tree.assert_called_once_with( + parent, + columns=("name", "type", "size", "modified"), + show="headings", + selectmode="extended", + ) + window._configure_tree_columns.assert_called_once_with(tree, "remote" if remote else "local") + tree.pack.assert_called_once_with(side="left", fill="both", expand=True) + make_scrollbar.assert_called_once_with(parent, orient="vertical", command=tree.yview) + scrollbar.pack.assert_called_once_with(side="right", fill="y") + tree.configure.assert_called_once_with(yscrollcommand=scrollbar.set) + + bindings = {binding.args[0]: binding.args[1] for binding in tree.bind.call_args_list} + expected_events = [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ] + if sys.platform == "darwin": + expected_events.append("") + expected_events.extend(("", "", "<>")) + assert list(bindings) == expected_events + expected_double_click = ( + FileBrowserWindow._on_remote_double_click if remote else FileBrowserWindow._on_local_double_click + ) + actual_double_click = bindings[""] + assert actual_double_click.__self__ is window + assert actual_double_click.__func__ is expected_double_click + event = MagicMock() + assert bindings[""](event) == "break" + window._show_context_menu.assert_called_once_with(event, remote) + bindings[""](None) + window._remember_panel.assert_called_once_with("remote" if remote else "local") + bindings[""](event) + window._remember_panel_from_click.assert_called_once_with("remote" if remote else "local", event) + bindings["<>"](None) + window._remember_panel_from_selection.assert_called_once_with("remote" if remote else "local") + def test_last_log_without_logs_does_not_report_disconnected_fc(self) -> None: """A live MAVFTP link need not have downloaded parameters or flight logs.""" window = _bare_window() @@ -1013,10 +1208,166 @@ def test_duplicate_download_targets_are_reported_before_transfer(self, tmp_path: title, message = window.ui.show_error.call_args.args assert title == "Download error" - assert "Several selected entries map to the same local target:" in message - assert str(target) in message + assert message == f"Several selected entries map to the same local target:\n\n{target}" window.parameter_editor.download_remote_file.assert_not_called() + @pytest.mark.parametrize( + ("result", "error", "expected_message"), + [ + (None, RuntimeError("remote listing failed"), "remote listing failed"), + (object(), None, "Could not prepare the selected remote entries."), + ], + ids=["preflight-error", "invalid-preflight-result"], + ) + def test_download_preflight_failures_show_exact_guidance( + self, tmp_path: Path, result: object, error: Exception | None, expected_message: str + ) -> None: + """ + A failed or malformed download preflight gives the user a clear error. + + GIVEN: A selected remote file and a failed or malformed preflight result + WHEN: The preflight callback completes + THEN: The browser shows the corresponding error and does not start a transfer + """ + window = _bare_window() + entry = FlightControllerLogFile("log.bin", "/APM/LOGS/log.bin", 1) + window.remote_entries = [entry] + window.remote_tree = MagicMock() + window.remote_tree.selection.return_value = ("0",) + window.local_directory_var = MagicMock() + window.local_directory_var.get.return_value = str(tmp_path) + window.parameter_editor = MagicMock() + window.ui = MagicMock() + window._start_remote_task = MagicMock() + window._run_transfer_batch = MagicMock() + + window.download_selected_remote_entries() + completion = window._start_remote_task.call_args.args[1] + completion(result, error) + + window.ui.show_error.assert_called_once_with("Download error", expected_message) + window._run_transfer_batch.assert_not_called() + + def test_download_confirmation_uses_exact_overwrite_prompt(self, tmp_path: Path) -> None: + """ + Existing local entries are protected by a clear overwrite confirmation. + + GIVEN: The download preflight finds an existing local target + WHEN: The user is asked whether to continue + THEN: The browser uses the overwrite title and message and honors a refusal + """ + window = _bare_window() + entry = FlightControllerLogFile("log.bin", "/APM/LOGS/log.bin", 1) + target = tmp_path / entry.name + window.remote_entries = [entry] + window.remote_tree = MagicMock() + window.remote_tree.selection.return_value = ("0",) + window.local_directory_var = MagicMock() + window.local_directory_var.get.return_value = str(tmp_path) + window.parameter_editor = MagicMock() + window.ui = MagicMock() + window.ui.ask_yesno.return_value = False + window._start_remote_task = MagicMock() + window._run_transfer_batch = MagicMock() + + window.download_selected_remote_entries() + completion = window._start_remote_task.call_args.args[1] + completion(RemoteDownloadPreflight(RemoteDownloadPlan((), ((entry, target),)), (), (target,)), None) + + window.ui.ask_yesno.assert_called_once_with( + "Overwrite existing local entries?", "Some local entries already exist. Overwrite them?" + ) + window._run_transfer_batch.assert_not_called() + + def test_empty_download_plan_shows_the_download_summary(self, tmp_path: Path) -> None: + """ + A valid plan with no transferable entries reports its accumulated failures. + + GIVEN: A selected remote entry whose preflight produces an empty plan + WHEN: The preflight callback completes + THEN: The user sees the download summary without a transfer window + """ + window = _bare_window() + entry = FlightControllerLogFile("log.bin", "/APM/LOGS/log.bin", 1) + window.remote_entries = [entry] + window.remote_tree = MagicMock() + window.remote_tree.selection.return_value = ("0",) + window.local_directory_var = MagicMock() + window.local_directory_var.get.return_value = str(tmp_path) + window.parameter_editor = MagicMock() + window.ui = MagicMock() + window._start_remote_task = MagicMock() + window._show_summary = MagicMock() + window._run_transfer_batch = MagicMock() + + window.download_selected_remote_entries() + completion = window._start_remote_task.call_args.args[1] + completion(RemoteDownloadPreflight(RemoteDownloadPlan((), (), failed=["unreadable.bin"]), (), ()), None) + + window._show_summary.assert_called_once_with("Download summary", [], ["unreadable.bin"]) + window._run_transfer_batch.assert_not_called() + + def test_download_transfer_request_contains_user_facing_batch_labels(self, tmp_path: Path) -> None: + """ + A prepared download uses consistent progress, summary, retry, and direction labels. + + GIVEN: A selected remote file and a nonempty download plan + WHEN: The preflight callback starts the transfer batch + THEN: The transfer request carries the expected user-facing text and download direction + """ + window = _bare_window() + entry = FlightControllerLogFile("log.bin", "/APM/LOGS/log.bin", 1) + target = tmp_path / entry.name + plan = RemoteDownloadPlan((), ((entry, target),)) + window.remote_entries = [entry] + window.remote_tree = MagicMock() + window.remote_tree.selection.return_value = ("0",) + window.local_directory_var = MagicMock() + window.local_directory_var.get.return_value = str(tmp_path) + window.parameter_editor = MagicMock() + window.ui = MagicMock() + window._start_remote_task = MagicMock() + window._run_transfer_batch = MagicMock() + + window.download_selected_remote_entries() + completion = window._start_remote_task.call_args.args[1] + completion(RemoteDownloadPreflight(plan, (), ()), None) + + request = window._run_transfer_batch.call_args.args[0] + assert request.batch == plan + assert request.ui.title == "Downloading selected entries" + assert request.ui.progress_message == "Downloaded {} of {} bytes" + assert request.ui.summary_title == "Download summary" + assert request.ui.retry_prompt == ( + "Retry failed downloads?", + "Retry only the failed file downloads?", + ) + assert request.ui.direction is TransferDirection.DOWNLOAD + + def test_download_reports_when_the_local_destination_is_missing(self, tmp_path: Path) -> None: + """ + A remote download cannot start when its selected local destination is missing. + + GIVEN: A selected remote log and a local destination that does not exist + WHEN: The user starts downloading the selected entry + THEN: The browser explains the missing destination and does not start preflight + """ + window = _bare_window() + entry = FlightControllerLogFile("log.bin", "/APM/LOGS/log.bin", 1) + window.remote_entries = [entry] + window.remote_tree = MagicMock() + window.remote_tree.selection.return_value = ("0",) + window.local_directory_var = MagicMock() + window.local_directory_var.get.return_value = str(tmp_path / "missing") + window.parameter_editor = MagicMock() + window.ui = MagicMock() + window._start_remote_task = MagicMock() + + window.download_selected_remote_entries() + + window.ui.show_error.assert_called_once_with("Download error", "The selected local directory does not exist.") + window._start_remote_task.assert_not_called() + def test_summary_cap_keeps_failures_visible(self) -> None: """Successful entries cannot hide failures.""" window = _bare_window() @@ -1739,7 +2090,9 @@ def test_download_preflight_aborts_if_local_destination_changes(self, tmp_path: window._task_runner.finish() window.parameter_editor.download_remote_file.assert_not_called() - window.ui.show_error.assert_called() + window.ui.show_error.assert_called_once_with( + "Download error", "The local destination changed while preparing the download. Please try again." + ) window.ui.ask_yesno.assert_not_called() def test_retry_replaces_failed_crc_with_successful_verification(self, tmp_path: Path) -> None: diff --git a/tests/test_frontend_tkinter_log_analysis_rendering.py b/tests/test_frontend_tkinter_log_analysis_rendering.py new file mode 100755 index 000000000..dd1524e2a --- /dev/null +++ b/tests/test_frontend_tkinter_log_analysis_rendering.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +""" +Focused rendering assertions for the detailed log analysis report. + +This file is part of ArduPilot Methodic Configurator. https://github.com/ArduPilot/MethodicConfigurator + +SPDX-FileCopyrightText: 2024-2026 Amilcar do Carmo Lucas + +SPDX-FileCopyrightText: 2026 Omkar Sarkar + +SPDX-License-Identifier: GPL-3.0-or-later +""" + +# pylint: disable=protected-access, redefined-outer-name, duplicate-code + +from __future__ import annotations + +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, call, patch + +import pytest +from test_frontend_tkinter_log_analysis import ( + _make_analysis_result, + _make_availability_issue, + _make_availability_result, +) + +from ardupilot_methodic_configurator.frontend_tkinter_log_analysis import LogAnalysisReportWindow, Severity + +if TYPE_CHECKING: + from pytest_mock import MockerFixture + +MODULE = "ardupilot_methodic_configurator.frontend_tkinter_log_analysis" + + +@pytest.fixture +def patched_widgets(mocker: MockerFixture) -> dict[str, MagicMock]: + """Patch the widgets constructed by the report window.""" + return { + "frame": mocker.patch(f"{MODULE}.ttk.Frame", return_value=MagicMock()), + "label": mocker.patch(f"{MODULE}.ttk.Label", return_value=MagicMock(pack=MagicMock())), + "label_frame": mocker.patch(f"{MODULE}.ttk.LabelFrame", return_value=MagicMock(pack=MagicMock())), + "button": mocker.patch(f"{MODULE}.ttk.Button", return_value=MagicMock(pack=MagicMock(), configure=MagicMock())), + "combobox": mocker.patch(f"{MODULE}.AutoResizeCombobox", return_value=MagicMock()), + "scroll_frame": mocker.patch( + f"{MODULE}.ScrollFrame", return_value=MagicMock(view_port=MagicMock(winfo_children=MagicMock(return_value=[]))) + ), + "show_tooltip": mocker.patch(f"{MODULE}.show_tooltip"), + } + + +@pytest.fixture +def bare_window() -> LogAnalysisReportWindow: + """Create a report window without initializing a physical Tk window.""" + window = LogAnalysisReportWindow.__new__(LogAnalysisReportWindow) + window.root = MagicMock() + window.main_frame = MagicMock() + window.summary = MagicMock(related_parameter_values={}) + window.body_frame = MagicMock(winfo_children=MagicMock(return_value=[])) + return window + + +class TestFocusedReportRendering: + """Check user visible report header, legend, and subsystem details.""" + + def test_header_explains_and_configures_subsystem_selection(self, patched_widgets: dict[str, MagicMock]) -> None: + """ + The report header identifies the page and offers the available subsystem choices. + + GIVEN: A report window with Battery and GPS subsystem summaries + WHEN: The header is built + THEN: The selector lists both names, starts at Battery, and explains how to use it + """ + window = LogAnalysisReportWindow.__new__(LogAnalysisReportWindow) + window.main_frame = MagicMock() + window.subsystem_names = ["Battery", "GPS"] + created_frames: list[MagicMock] = [] + + def make_frame(*_args: object, **_kwargs: object) -> MagicMock: + frame = MagicMock() + created_frames.append(frame) + return frame + + patched_widgets["frame"].side_effect = make_frame + + window._build_header() + + selector = patched_widgets["combobox"].return_value + assert patched_widgets["combobox"].call_args.args[1:4] == ( + ["Battery", "GPS"], + "Battery", + "Select a subsystem to view its details", + ) + assert patched_widgets["combobox"].call_args.kwargs == { + "state": "readonly", + "width": 30, + } + selector.bind.assert_called_once() + assert selector.bind.call_args.args[0] == "<>" + labels = [call.kwargs.get("text") for call in patched_widgets["label"].call_args_list] + assert "Log Analysis" in labels + assert "Subsystem:" in labels + header, left_column, selector_row, right_column = ( + created_frames[0], + created_frames[1], + created_frames[2], + created_frames[3], + ) + assert patched_widgets["frame"].call_args_list[:4] == [ + call(window.main_frame), + call(header), + call(left_column), + call(header), + ] + assert header.pack.call_args == call(side="top", fill="x", padx=20, pady=(16, 4)) + assert left_column.pack.call_args == call(side="left", anchor="nw") + assert selector_row.pack.call_args == call(anchor="w", pady=(8, 0)) + assert right_column.pack.call_args == call(side="right", anchor="ne") + title_call, subsystem_call = patched_widgets["label"].call_args_list[:2] + assert title_call.args[0] == left_column + assert title_call.kwargs == {"text": "Log Analysis", "font": ("TkDefaultFont", 16, "bold")} + assert subsystem_call.args[0] == selector_row + assert subsystem_call.kwargs == {"text": "Subsystem:", "font": ("TkDefaultFont", 13, "bold")} + assert patched_widgets["label"].return_value.pack.call_args_list[0] == call(anchor="w") + + def test_legend_shows_each_severity_with_its_color_and_guidance( # pylint: disable=too-many-locals + self, patched_widgets: dict[str, MagicMock] + ) -> None: + """ + Each report severity has a visible label, matching marker color, and explanatory tooltip. + + GIVEN: A report header that includes the severity legend + WHEN: The legend is built + THEN: Users can distinguish all severity levels and read their guidance + """ + window = LogAnalysisReportWindow.__new__(LogAnalysisReportWindow) + parent = MagicMock() + created_frames: list[MagicMock] = [] + + def make_frame(*_args: object, **_kwargs: object) -> MagicMock: + frame = MagicMock() + created_frames.append(frame) + return frame + + patched_widgets["frame"].side_effect = make_frame + + window._build_legend(parent) + + labels = [call.kwargs for call in patched_widgets["label"].call_args_list] + assert patched_widgets["show_tooltip"].call_args_list[0] == call( + patched_widgets["label_frame"].return_value, + "Severity of a finding", + position_below=False, + ) + tooltips = [call.args[1] for call in patched_widgets["show_tooltip"].call_args_list] + for _severity, label, color, guidance in ( + (Severity.SEVERE, "Severe", "red3", "A serious issue that should be fixed before further flights"), + (Severity.NEEDS_ATTENTION, "Needs attention", "dark orange", "Worth reviewing, may or may not need action"), + (Severity.INFORMATIONAL, "Informational", "gray50", "For your information only, no action expected"), + ): + assert any(item.get("text") == label for item in labels) + assert any(item.get("text") == "■" and item.get("foreground") == color for item in labels) + assert guidance in tooltips + patched_widgets["label_frame"].assert_called_once_with(parent, text="Legend") + patched_widgets["label_frame"].return_value.pack.assert_called_once_with(side="left", anchor="n", padx=(0, 20)) + assert len(created_frames) == len(Severity) + assert all(frame.pack.call_args == call(anchor="w", padx=8, pady=2) for frame in created_frames) + assert patched_widgets["show_tooltip"].call_count == 1 + 2 * len(Severity) + for row_index, row in enumerate(created_frames): + marker_call, label_call = patched_widgets["label"].call_args_list[2 * row_index : 2 * row_index + 2] + assert marker_call.args[0] == row + assert label_call.args[0] == row + + def test_report_details_include_component_issues_and_documentation_links( + self, bare_window: LogAnalysisReportWindow + ) -> None: + """ + A subsystem report brings its hardware, availability issues, analysis, and help links together. + + GIVEN: A Battery subsystem with a component, one availability issue, and wiki and guide links + WHEN: The user opens its detailed report + THEN: Each detail appears in the appropriate report section + """ + window = bare_window + window.body_frame = MagicMock(winfo_children=MagicMock(return_value=[])) + issue = _make_availability_issue(message="Voltage samples are sparse") + availability = _make_availability_result(name="Battery", issues=[issue]) + analysis = _make_analysis_result(name="Battery analysis", reason="Cell balance is acceptable") + window.pairs = [(availability, analysis)] + window.report = { + "vehicle_components": { + "Battery": {"Product": {"Manufacturer": "GEN X POWER", "Model": "6S"}}, + } + } + window.summary.component_keys_for_subsystem.return_value = ["Battery"] + window._report_availability_by_name = { + "Battery": { + "issues": [ + { + "step_info": { + "wiki_url": "https://example.test/wiki", + "wiki_text": "Battery setup", + "blog_url": "https://example.test/guide", + "blog_text": "Battery guide", + } + } + ] + } + } + window._report_analysis_by_name = {"Battery": {"outcomes": []}} + + with ( + patch.object(window, "_section_heading") as heading, + patch.object(window, "_section_body") as body, + patch.object(window, "_section_link") as link, + patch.object(window, "_bullet_line") as bullet, + ): + window._render_subsystem("Battery") + + assert heading.call_args_list == [ + call("Links"), + call("Hardware & Connections"), + call("Availability"), + call("Analysis"), + ] + assert link.call_args_list == [ + call("Wiki", "Battery setup", "https://example.test/wiki"), + call("Guide", "Battery guide", "https://example.test/guide"), + ] + body.assert_any_call("Battery", bold=True) + body.assert_any_call("Cell balance is acceptable") + assert bullet.call_args_list == [call("GEN X POWER 6S"), call("Voltage samples are sparse")] diff --git a/tests/test_frontend_tkinter_mavlink_inspector.py b/tests/test_frontend_tkinter_mavlink_inspector.py index 6e1bc65ea..0f431d191 100755 --- a/tests/test_frontend_tkinter_mavlink_inspector.py +++ b/tests/test_frontend_tkinter_mavlink_inspector.py @@ -139,6 +139,70 @@ def test_radio_panel_shows_three_name_value_unit_tuples(inspector: MavlinkInspec assert all(panel.values[key].grid_info() for key, _name, _unit in panel._RADIO_METRICS) +def test_inspector_initializes_its_window_guidance_and_fields(inspector: MavlinkInspectorWindow) -> None: + """The inspector opens with its identifying title, usable size, and fresh-data guidance.""" + assert inspector.root.title() == _("MAVLink inspector") + if sys.platform != "darwin": # Window geometry requires rendering, unsafe on headless macOS CI + expected_geometry = inspector.calculate_scaled_geometry(750, 650).split("+", maxsplit=1)[0] + assert inspector.root.geometry().split("+", maxsplit=1)[0] == expected_geometry + assert inspector._state == TelemetryState() + assert inspector._closed is False + assert inspector._hovered_cell is None + assert inspector._timer_id is None + assert inspector._minimum_section_height == round(60 * inspector.dpi_scaling_factor) + assert inspector.root.protocol("WM_DELETE_WINDOW") + assert inspector.root.bind("") + assert inspector.status.cget("text") == _("No current MAVLink messages. Check the telemetry connection.") + assert int(inspector.status.cget("width")) == 1 + assert inspector.status.master is inspector.main_frame + assert inspector.status.pack_info()["fill"] == "x" + assert int(inspector.status.pack_info()["padx"]) == 8 + assert int(inspector.status.pack_info()["pady"]) == 8 + assert inspector.connection_note.cget("text") == _( + "A USB connection measures USB traffic, not the telemetry radio link. " + "Connect through the telemetry link you want to test." + ) + assert int(inspector.connection_note.cget("width")) == 1 + assert inspector.message_contents.title == _("MAVLink message contents") + assert int(inspector.fields.cget("height")) == 8 + assert inspector.fields.cget("wrap") == "word" + assert inspector.fields.cget("state") == "disabled" + + +def test_message_table_has_expected_columns_headings_and_scrolling(inspector: MavlinkInspectorWindow) -> None: + """The table exposes its seven documented columns with sorting and scrolling controls.""" + expected_headings = ("System", "Component", "Message", "Count", "Hz", "B/s", "Age (s)") + assert tuple(inspector.table.cget("columns")) == tuple(frontend.MESSAGE_COLUMNS) + assert str(inspector.table.cget("show")[0]) == "headings" + assert str(inspector.table.cget("selectmode")) == "browse" + assert int(inspector.table.cget("height")) == 12 + + for column, heading in zip(frontend.MESSAGE_COLUMNS, expected_headings, strict=True): + assert inspector.table.heading(column, "text") == _(heading) + assert inspector.table.heading(column, "command") + assert int(inspector.table.column(column, "width")) == (220 if column == "message" else 85) + assert bool(int(inspector.table.column(column, "stretch"))) + + assert int(inspector.section_panes.panecget(inspector.table_frame, "minsize")) == inspector._minimum_section_height + assert inspector.section_panes.panecget(inspector.table_frame, "stretch") == "always" + assert inspector.section_panes.panecget(inspector.table_frame, "sticky") == "nesw" + assert inspector.table.master is inspector.table_frame + assert str(inspector.table.tag_configure("striped", "background")) == "#eeeeee" + assert inspector.table.pack_info()["fill"] == "both" + assert bool(int(inspector.table.pack_info()["expand"])) + assert inspector.table_scrollbar.master is inspector.table_frame + assert inspector.table_scrollbar.pack_info()["side"] == "right" + assert inspector.table_scrollbar.pack_info()["fill"] == "y" + assert str(inspector.table_scrollbar.cget("orient")) == "vertical" + assert inspector.table_scrollbar.cget("command") + assert inspector.table.cget("yscrollcommand") + assert inspector.table.bind("<>") + assert inspector.table.bind("") + assert inspector.table.bind("") + for sequence in ("", "", ""): + assert inspector.table.bind(sequence) + + @pytest.mark.parametrize("with_radio", [False, True]) @pytest.mark.skipif(sys.platform == "darwin", reason="Window geometry requires rendering, unsafe on headless macOS CI") def test_radio_explanation_wraps_when_window_narrows(inspector: MavlinkInspectorWindow, with_radio: bool) -> None: @@ -188,6 +252,63 @@ def test_every_inspector_control_and_reading_has_beginner_help(inspector: Mavlin assert "Errors/s is a count rate" in hints[inspector.radio_status.values["rx_error_rate"]].text assert "not editable parameters" in hints[inspector.fields].text + # pylint: disable=duplicate-code # Keep exact help copy covered by its UI regression assertion. + fields_help = _( + "Latest decoded fields of the selected message. These are received data, not editable parameters. " + "Field units depend on the message; Help links to the reference." + ) + pane_help = _( + "Drag the horizontal divider to give more height to the message table or decoded fields. The " + "status footer stays visible." + ) + # pylint: enable=duplicate-code + expected_tooltips = { + inspector.main_frame: _( + "Monitor messages reaching AMC through its active connection. Use Help for a step-by-step introduction." + ), + inspector.status: _( + "Shows whether recent MAVLink messages are arriving. Increasing counts and small ages indicate fresh data." + ), + inspector.connection_note: _( + "To test a wireless telemetry link, connect AMC through that link. Direct USB traffic measures the USB path." + ), + inspector.section_panes: pane_help, + inspector.table_frame: MavlinkInspectorWindow._TABLE_HELP, + inspector.table: MavlinkInspectorWindow._TABLE_HELP, + inspector.table_scrollbar: _( + "Drag to scroll through received message types. Scrolling does not change the selected message." + ), + inspector._message_fields_pane: fields_help, + inspector.message_contents: fields_help, + inspector.message_contents.content_frame: fields_help, + inspector.fields: fields_help, + inspector.fields_scrollbar: _( + "Scroll through all decoded fields of the selected message. Select another table row to " + "inspect a different message." + ), + inspector.footer: _( + "Connection traffic and radio readings stay visible here while the message table and decoded fields are resized." + ), + inspector.buttons_frame: _( + "Help opens the beginner's manual. Close returns to AMC, or ends the standalone inspector." + ), + inspector.help_button: _( + "Open the MAVLink inspector beginner's manual in your web browser. It explains the " + "columns, radio readings and connection checks; internet access is needed." + ), + inspector.close_button: _( + "Stop monitoring and close this window. AMC keeps its connection; the standalone " + "inspector closes its own connection." + ), + } + for widget, expected_text in expected_tooltips.items(): + assert hints[widget].text == expected_text + + assert inspector.message_contents.header_tooltip.text == _( + "Click to hide or restore decoded message fields and give the table more room. You can also " + "focus this title with Tab and press Enter or Space." + ) + @pytest.mark.parametrize("region", ["heading", "cell"]) @pytest.mark.parametrize( @@ -269,20 +390,27 @@ def test_table_help_stays_stable_until_the_pointer_moves_or_scrolls(inspector: M assert tooltip.timers["show"] != timer -def test_usb_connection_guidance_is_visible_and_wraps_safely(inspector: MavlinkInspectorWindow) -> None: +@pytest.mark.parametrize(("width", "expected_wraplength"), [(0, 1), (400, 384), (750, 734)]) +def test_usb_connection_guidance_is_visible_and_wraps_safely( + inspector: MavlinkInspectorWindow, width: int, expected_wraplength: int +) -> None: """ Explain the measurement path before a beginner interprets the traffic readings. GIVEN an inspector for any active transport, WHEN its guidance is read or the window becomes narrow, - THEN it explains USB traffic versus the radio link and keeps positive wrapping widths. + THEN it explains USB traffic versus the radio link and both notices fit the available width. """ assert len(inspector.connection_note.pack_info()) > 0 assert "USB connection measures USB traffic, not the telemetry radio link" in inspector.connection_note.cget("text") - inspector._resize_notices(SimpleNamespace(width=0)) - assert int(inspector.connection_note.cget("wraplength")) == 1 - inspector._resize_notices(SimpleNamespace(width=400)) - assert int(inspector.connection_note.cget("wraplength")) == 384 + if sys.platform == "darwin": + # Headless macOS CI suppresses layout, so synthetic Configure events are not delivered reliably. + inspector._resize_notices(SimpleNamespace(width=width)) # type: ignore[arg-type] + else: + # Deliver the resize through its binding without waiting for native window layout. + inspector.main_frame.event_generate("", width=width) + assert int(inspector.status.cget("wraplength")) == expected_wraplength + assert int(inspector.connection_note.cget("wraplength")) == expected_wraplength @pytest.mark.skipif(sys.platform == "darwin", reason="Window geometry requires rendering, unsafe on headless macOS CI") diff --git a/tests/test_frontend_tkinter_parameter_editor_table.py b/tests/test_frontend_tkinter_parameter_editor_table.py index cf9153dea..92ca0a576 100755 --- a/tests/test_frontend_tkinter_parameter_editor_table.py +++ b/tests/test_frontend_tkinter_parameter_editor_table.py @@ -18,7 +18,7 @@ from tkinter import ttk from types import SimpleNamespace from typing import Any, Literal, cast -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock, call, patch import pytest from conftest import PARAMETER_EDITOR_TABLE_HEADERS_ADVANCED, PARAMETER_EDITOR_TABLE_HEADERS_SIMPLE @@ -3637,12 +3637,102 @@ def test_single_parameter_addition_refreshes_only_after_the_model_accepts_it( table._pending_scroll_to_bottom = False assert table._confirm_parameter_addition("TEST_PARAM") is added - assert table._pending_scroll_to_bottom is added assert table.parameter_editor_window.repopulate_parameter_table.call_count == int(added) table._dialogs.show_error.assert_not_called() +def test_parameter_add_dialog_widgets_explain_filtering_and_selection() -> None: + """ + The add-parameter dialog shows a searchable multi-select list with clear instructions. + + GIVEN: A parameter table opening its add-parameter dialog + WHEN: The dialog widgets are created + THEN: The filter, selection guidance, list scrollbar, and disabled add button are configured + """ + table = ParameterEditorTable.__new__(ParameterEditorTable) + window = SimpleNamespace(main_frame=MagicMock()) + search_var = MagicMock() + search_entry = MagicMock() + dialog_frame = MagicMock() + listbox = MagicMock() + scrollbar = MagicMock() + add_button = MagicMock() + + with ( + patch("ardupilot_methodic_configurator.frontend_tkinter_parameter_editor_table.tk.StringVar", return_value=search_var), + patch( + "ardupilot_methodic_configurator.frontend_tkinter_parameter_editor_table.ttk.Label", + return_value=MagicMock(pack=MagicMock()), + ) as label, + patch( + "ardupilot_methodic_configurator.frontend_tkinter_parameter_editor_table.ttk.Entry", + return_value=search_entry, + ) as entry, + patch( + "ardupilot_methodic_configurator.frontend_tkinter_parameter_editor_table.ttk.Frame", + return_value=dialog_frame, + ), + patch( + "ardupilot_methodic_configurator.frontend_tkinter_parameter_editor_table.tk.Listbox", + return_value=listbox, + ) as make_listbox, + patch( + "ardupilot_methodic_configurator.frontend_tkinter_parameter_editor_table.ttk.Scrollbar", + return_value=scrollbar, + ) as make_scrollbar, + patch( + "ardupilot_methodic_configurator.frontend_tkinter_parameter_editor_table.ttk.Button", + return_value=add_button, + ) as button, + patch("ardupilot_methodic_configurator.frontend_tkinter_parameter_editor_table.show_tooltip") as show_tooltip, + ): + result = table._create_parameter_add_dialog_widgets(window) + + assert result == (search_var, search_entry, listbox, add_button) + assert label.call_args_list == [ + call(window.main_frame, text=_("Name filter:")), + call( + window.main_frame, + text=_("(Use Ctrl/Shift for multiple selection)"), + font=("TkDefaultFont", 8), + ), + ] + entry.assert_called_once_with(window.main_frame, textvariable=search_var) + search_entry.pack.assert_called_once_with(fill="x", padx=10) + dialog_frame.pack.assert_called_once_with(fill="both", expand=True, padx=10, pady=5) + make_listbox.assert_called_once_with(dialog_frame, selectmode=tk.EXTENDED) + listbox.pack.assert_called_once_with(side="left", fill="both", expand=True) + make_scrollbar.assert_called_once_with(dialog_frame, orient="vertical", command=listbox.yview) + scrollbar.pack.assert_called_once_with(side="right", fill="y") + listbox.configure.assert_called_once_with(yscrollcommand=scrollbar.set) + button.assert_called_once_with(window.main_frame, text=_("No parameter selected"), state="disabled") + add_button.pack.assert_called_once_with(pady=10) + # pylint: disable=duplicate-code # The complete user-facing tooltip text is asserted verbatim. + assert show_tooltip.call_args_list == [ + call( + search_entry, + _( + "Type part of a parameter name to filter the list.\n" + "Press Enter to add all filtered parameters,\n" + "or only the selected ones if any are selected." + ), + ), + call( + listbox, + _( + "Double-click to add single parameter\n" + "Ctrl+click to select multiple one-by-one\n" + "Shift+click to select multiple by range\n" + "Ctrl+A: Select all\n" + "Ctrl+D: Deselect all\n" + "Return: Add selected" + ), + ), + ] + # pylint: enable=duplicate-code + + def test_parameter_dialog_parent_resolution_reports_when_no_toplevel_exists( parameter_editor_table: ParameterEditorTable, ) -> None: diff --git a/tests/test_frontend_tkinter_template_overview.py b/tests/test_frontend_tkinter_template_overview.py index 80dd44ab2..cafbd1171 100755 --- a/tests/test_frontend_tkinter_template_overview.py +++ b/tests/test_frontend_tkinter_template_overview.py @@ -13,7 +13,8 @@ import tkinter as tk from collections.abc import Generator from tkinter import ttk -from unittest.mock import ANY, MagicMock, patch +from typing import cast +from unittest.mock import ANY, MagicMock, call, patch import pytest @@ -310,7 +311,11 @@ def test_sorting_helps_users_find_templates(self, template_window) -> None: template_window._sort_by_column("Frame", reverse=False) # Assert: Items are reordered (Airplane, Helicopter, QuadCopter) - assert template_window.tree.move.call_count == 3 + assert template_window.tree.move.call_args_list == [ + call("item2", "", 0), + call("item3", "", 1), + call("item1", "", 2), + ] # Verify ascending sort indicator is shown template_window.tree.heading.assert_called_with("Frame", command=ANY) @@ -860,48 +865,65 @@ def test_event_binding_creates_all_required_handlers(self, template_window) -> N class TestSortingBehaviorDetails: """Test detailed sorting behavior.""" - def test_numeric_sorting_works_with_float_values(self, template_window) -> None: + @pytest.mark.parametrize( + ("reverse", "expected_order"), + [(False, ("item1", "item3", "item2")), (True, ("item2", "item3", "item1"))], + ids=["ascending", "descending"], + ) + def test_numeric_sorting_works_with_float_values( + self, template_window: TemplateOverviewWindow, reverse: bool, expected_order: tuple[str, ...] + ) -> None: """ Numeric sorting should work with float values. GIVEN: A treeview with numeric data WHEN: User sorts by numeric column - THEN: Values should be sorted numerically, not alphabetically + THEN: Decimal values are ordered by magnitude in the requested direction """ # Arrange: Mock tree with numeric data - template_window.tree.get_children.return_value = ["item1", "item2", "item3"] - template_window.tree.set.side_effect = lambda item, col: { + tree = cast("MagicMock", template_window.tree) + tree.get_children.return_value = ["item1", "item2", "item3"] + tree.set.side_effect = lambda item, col: { ("item1", "Size"): "1.5", ("item2", "Size"): "10.2", ("item3", "Size"): "2.0", }.get((item, col), "0") # Act: Sort by Size column - template_window._sort_by_column("Size", reverse=False) - - # Assert: Items were moved (sorted) - assert template_window.tree.move.call_count == 3 - - def test_string_sorting_fallback_handles_non_numeric_data(self, template_window) -> None: + template_window._sort_by_column("Size", reverse=reverse) + + # Assert: Each row is moved to its numerically sorted position + assert tree.move.call_args_list == [call(item, "", index) for index, item in enumerate(expected_order)] + + @pytest.mark.parametrize( + ("reverse", "expected_order"), + [(False, ("item2", "item3", "item1")), (True, ("item1", "item3", "item2"))], + ids=["ascending", "descending"], + ) + def test_sorting_text_column_orders_rows_alphabetically( + self, template_window: TemplateOverviewWindow, reverse: bool, expected_order: tuple[str, ...] + ) -> None: """ - String sorting should work as fallback for non-numeric data. + A text column sorts alphabetically. GIVEN: A treeview with non-numeric data WHEN: User sorts by text column - THEN: Values should be sorted alphabetically + THEN: Values are ordered alphabetically in the requested direction """ # Arrange: Mock tree with text data - template_window.tree.get_children.return_value = ["item1", "item2"] - template_window.tree.set.side_effect = lambda item, col: { + tree = cast("MagicMock", template_window.tree) + tree.get_children.return_value = ["item1", "item2", "item3"] + tree.set.side_effect = lambda item, col: { ("item1", "Name"): "Zebra", ("item2", "Name"): "Alpha", + ("item3", "Name"): "Mango", }.get((item, col), "") # Act: Sort by Name column - template_window._sort_by_column("Name", reverse=False) + template_window._sort_by_column("Name", reverse=reverse) - # Assert: String sorting was used (move was called) - assert template_window.tree.move.call_count == 2 + # Assert: Each row is moved to its alphabetically sorted position + assert tree.move.call_args_list == [call(item, "", index) for index, item in enumerate(expected_order)] def test_sorting_indicators_update_properly(self, template_window) -> None: """ diff --git a/tests/unit_data_model_vehicle_components_base.py b/tests/unit_data_model_vehicle_components_base.py index c06532539..db31adba1 100755 --- a/tests/unit_data_model_vehicle_components_base.py +++ b/tests/unit_data_model_vehicle_components_base.py @@ -485,6 +485,12 @@ def realistic_model(self) -> ComponentDataModelBase: """Create a realistic ComponentDataModelBase fixture for testing.""" return ComponentDataModelFixtures.create_realistic_model(ComponentDataModelBase) + def test_system_initializes_model_state_and_schema(self, basic_model) -> None: + """A new model starts with empty PWM types and a false new-project flag.""" + assert basic_model._mot_pwm_types == () + assert basic_model._is_new_project is False + assert isinstance(basic_model.schema, VehicleComponentsJsonSchema) + def test_system_converts_list_value_to_string_in_get_component_value(self, basic_model) -> None: """ System converts non-primitive component values to strings. diff --git a/tests/unit_data_model_vehicle_components_display.py b/tests/unit_data_model_vehicle_components_display.py index e825e29ce..0d2d92d61 100755 --- a/tests/unit_data_model_vehicle_components_display.py +++ b/tests/unit_data_model_vehicle_components_display.py @@ -95,6 +95,29 @@ def test_system_recurses_into_nested_dicts_in_non_toplevel_path(self, display_mo assert result is True + def test_top_level_recursion_uses_the_nested_component_path(self, display_model) -> None: + """Given nested schema fields, resolve required status using their complete path.""" + display_model.schema.get_component_property_description.return_value = ("Required", False) + display_model.get_all_components = MagicMock(return_value=["Flight Controller"]) + + assert display_model.should_display_in_simple_mode( + "Flight Controller", {"Product": {"Manufacturer": "Holybro"}}, [], "simple" + ) + display_model.schema.get_component_property_description.assert_called_once_with( + ("Flight Controller", "Product", "Manufacturer") + ) + + def test_nested_recursion_uses_the_full_non_top_level_path(self, display_model) -> None: + """Given a required nested leaf, retain every parent in the schema lookup path.""" + display_model.schema.get_component_property_description.return_value = ("Required", False) + + assert display_model.should_display_in_simple_mode( + "Specifications", {"Nested": {"Required": "value"}}, ["Flight Controller"], "simple" + ) + display_model.schema.get_component_property_description.assert_called_once_with( + ("Flight Controller", "Specifications", "Nested", "Required") + ) + # ------------------------------------------------------------------ # prepare_non_leaf_widget_config - optional field with description (line 122) # ------------------------------------------------------------------ @@ -110,10 +133,7 @@ def test_system_appends_optional_hint_to_non_leaf_description(self, display_mode config = display_model.prepare_non_leaf_widget_config("Product", {"Manufacturer": "Test"}, ["Flight Controller"]) - assert "Section info" in config["description"] - assert "optional" in config["description"].lower() - assert "\n" in config["description"] - assert "blank" in config["description"].lower() + assert config["description"] == "Section info\nThis is optional and can be left blank" # ------------------------------------------------------------------ # should_display_in_simple_mode - branch 57->54: top-level loop continues diff --git a/tests/unit_data_model_vehicle_components_import.py b/tests/unit_data_model_vehicle_components_import.py index 595401801..1a9923bbf 100755 --- a/tests/unit_data_model_vehicle_components_import.py +++ b/tests/unit_data_model_vehicle_components_import.py @@ -20,11 +20,12 @@ import pytest from test_data_model_vehicle_components_common import ComponentDataModelFixtures +import ardupilot_methodic_configurator.data_model_vehicle_components_import as _import_module from ardupilot_methodic_configurator.battery_cell_voltages import BATTERY_DEFAULT_CHEMISTRY, BatteryCell -from ardupilot_methodic_configurator.data_model_vehicle_components_import import ComponentDataModelImport +from ardupilot_methodic_configurator.data_model_vehicle_components_import import BatteryVoltageSpecs, ComponentDataModelImport from ardupilot_methodic_configurator.data_model_vehicle_components_validation import ComponentDataModelValidation -# pylint: disable=protected-access,too-many-public-methods +# pylint: disable=protected-access,too-many-public-methods,too-many-lines class TestComponentDataModelImportInternals: @@ -74,8 +75,11 @@ def test_reverse_key_search_returns_fallbacks_for_missing_values(self, realistic WHEN: Searching for non-existent protocol names THEN: Fallback keys should be returned """ - result = realistic_model._reverse_key_search(sample_doc_dict, "SERIAL1_PROTOCOL", ["NonExistent"], [99]) + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: + result = realistic_model._reverse_key_search(sample_doc_dict, "SERIAL1_PROTOCOL", ["NonExistent"], [99]) + assert result == [99] + mock_log.assert_called_once_with("No values found for %s in the metadata", "SERIAL1_PROTOCOL") def test_reverse_key_search_handles_mismatched_lengths(self, realistic_model, sample_doc_dict) -> None: """ @@ -93,7 +97,7 @@ def test_reverse_key_search_handles_mismatched_lengths(self, realistic_model, sa ["GPS", "RCIN"], [5], # Mismatched lengths ) - mock_log.assert_called() + mock_log.assert_called_once_with("Length of values %u and fallbacks %u differ for %s", 2, 1, "SERIAL1_PROTOCOL") assert result == [5, 23] def test_reverse_key_search_handles_empty_documentation(self, realistic_model) -> None: @@ -143,6 +147,21 @@ def test_reverse_key_search_handles_empty_values(self, realistic_model) -> None: result = realistic_model._reverse_key_search(empty_values_doc, "PARAM", ["value"], [99]) assert result == [99] + @pytest.mark.parametrize( + ("parameters", "voltage_type", "expected"), + [ + ({}, "Volt per cell max", ""), + ({"MOT_BAT_VOLT_MAX": 16.8}, "Volt per cell max", "MOT_BAT_VOLT_MAX"), + ({"MOT_BAT_VOLT_MAX": 16.8, "Q_M_BAT_VOLT_MAX": 16.8}, "Volt per cell max", "Q_M_BAT_VOLT_MAX"), + ({"MOT_BAT_VOLT_MIN": 12.0}, "Volt per cell min", "MOT_BAT_VOLT_MIN"), + ], + ) + def test_motor_battery_voltage_parameter_uses_priority_and_empty_string_fallback( + self, parameters: dict[str, float], voltage_type: str, expected: str + ) -> None: + """The preferred motor voltage key is returned, with an empty string when none is present.""" + assert ComponentDataModelImport._get_motor_battery_voltage_parameter(parameters, voltage_type) == expected + def test_verify_dict_matches_documentation(self, realistic_model, sample_doc_dict) -> None: """ Internal dictionary verification confirms matching dictionaries. @@ -175,9 +194,12 @@ def test_verify_dict_detects_mismatches(self, realistic_model, sample_doc_dict) "5": {"protocol": "GPS"}, "23": {"protocol": "RCIN"}, } - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warning: result = realistic_model._verify_dict_is_uptodate(sample_doc_dict, dict_mismatch, "SERIAL1_PROTOCOL", "values") assert result is False + mock_warning.assert_called_once_with( + "Protocol %s does not match %s in %s metadata", "Wrong Protocol", "MAVLink1", "SERIAL1_PROTOCOL" + ) def test_verify_dict_accepts_arduplane_47_ina2xx_label(self, realistic_model) -> None: """Accept the expanded INA2XX label introduced in ArduPilot 4.7.x metadata.""" @@ -247,11 +269,41 @@ def test_verify_dict_detects_incomplete_dictionaries(self, realistic_model) -> N "1": {"protocol": "Protocol1"}, # Missing key "2" and "3" } - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warning: result = realistic_model._verify_dict_is_uptodate(doc, incomplete_dict, "PARAM", "values") assert result is False + assert [call.args for call in mock_warning.call_args_list] == [ + ("Protocol %s (%s) not found in %s code dictionary (firmware may be newer)", "Protocol2", "2", "PARAM"), + ("Protocol %s (%s) not found in %s code dictionary (firmware may be newer)", "Protocol3", "3", "PARAM"), + ] + + def test_verify_bitmask_protocols_expands_bit_positions_and_continues_after_invalid_keys(self, realistic_model) -> None: + """Bitmask metadata maps positions to powers of two and skips malformed positions.""" + doc = {"RC_PROTOCOLS": {"Bitmask": {"invalid": "Ignored", "0": "Unexpected", "2": "Third"}}} + protocols = {"1": {"protocol": "First"}, "4": {"protocol": "Third"}} + + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warning: + result = realistic_model._verify_dict_is_uptodate(doc, protocols, "RC_PROTOCOLS", "Bitmask") + + assert result is False + assert [call.args for call in mock_warning.call_args_list] == [ + ("Invalid bit position %s in %s metadata", "invalid", "RC_PROTOCOLS"), + ("Protocol %s does not match %s in %s metadata", "First", "Unexpected", "RC_PROTOCOLS"), + ] - def test_set_gnss_type_handles_invalid_gps_type_value(self, realistic_model) -> None: + def test_verify_protocol_rename_does_not_skip_later_mismatches(self, realistic_model) -> None: + """A documented rename exception does not hide a mismatch later in the same metadata.""" + doc = {"PARAM": {"values": {"1": "MAV", "2": "Different"}}} + protocols = {"1": {"protocol": "MAVLink"}, "2": {"protocol": "Expected"}} + + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warning: + result = realistic_model._verify_dict_is_uptodate(doc, protocols, "PARAM", "values") + + assert result is False + mock_warning.assert_called_once_with("Protocol %s does not match %s in %s metadata", "Expected", "Different", "PARAM") + + @pytest.mark.parametrize("param_name", ["GPS_TYPE", "GPS1_TYPE"]) + def test_set_gnss_type_handles_invalid_gps_type_value(self, realistic_model, param_name: str) -> None: # type: ignore[misc] """ Internal GNSS type setter handles invalid GPS_TYPE value. @@ -260,13 +312,17 @@ def test_set_gnss_type_handles_invalid_gps_type_value(self, realistic_model) -> THEN: Error should be logged AND: GNSS type should default to None """ - fc_parameters = {"GPS_TYPE": "invalid"} - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + fc_parameters = {param_name: "invalid"} + realistic_model.set_component_value(("GNSS Receiver", "FC Connection", "Type"), "SERIAL3") + realistic_model.set_component_value(("GNSS Receiver", "FC Connection", "Protocol"), "uBlox") + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: realistic_model._set_gnss_type_from_fc_parameters(fc_parameters) - gnss_type = realistic_model.get_component_value(("GNSS Receiver", "FC Connection", "Type")) - assert gnss_type == "None" + mock_log.assert_called_once_with("Invalid non-integer value for %s: %s", param_name, "invalid") + assert realistic_model.get_component_value(("GNSS Receiver", "FC Connection", "Type")) == "None" + assert realistic_model.get_component_value(("GNSS Receiver", "FC Connection", "Protocol")) == "None" - def test_set_gnss_type_handles_unknown_gps_type(self, realistic_model) -> None: + @pytest.mark.parametrize("param_name", ["GPS_TYPE", "GPS1_TYPE"]) + def test_set_gnss_type_handles_unknown_gps_type(self, realistic_model, param_name: str) -> None: # type: ignore[misc] """ Internal GNSS type setter handles unknown GPS_TYPE value. @@ -275,9 +331,10 @@ def test_set_gnss_type_handles_unknown_gps_type(self, realistic_model) -> None: THEN: Error should be logged AND: GNSS type should default to None """ - fc_parameters = {"GPS_TYPE": 999} - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + fc_parameters = {param_name: 999} + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: realistic_model._set_gnss_type_from_fc_parameters(fc_parameters) + mock_log.assert_called_once_with("%s value %u not in GNSS_RECEIVER_CONNECTION", param_name, 999) gnss_type = realistic_model.get_component_value(("GNSS Receiver", "FC Connection", "Type")) assert gnss_type == "None" @@ -291,8 +348,13 @@ def test_set_serial_type_handles_invalid_rc_protocols_value(self, realistic_mode AND: System should not crash """ fc_parameters = {"RC_PROTOCOLS": "invalid"} - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + realistic_model.set_component_value(("RC Receiver", "FC Connection", "Type"), "SERIAL2") + realistic_model.set_component_value(("RC Receiver", "FC Connection", "Protocol"), "CRSF") + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: realistic_model._set_serial_type_from_fc_parameters(fc_parameters) + mock_log.assert_called_once_with("Invalid non-integer value for RC_PROTOCOLS %s", "invalid") + assert realistic_model.get_component_value(("RC Receiver", "FC Connection", "Type")) == "SERIAL2" + assert realistic_model.get_component_value(("RC Receiver", "FC Connection", "Protocol")) == "CRSF" def test_set_serial_type_handles_multiple_rc_protocols(self, realistic_model) -> None: """ @@ -303,8 +365,25 @@ def test_set_serial_type_handles_multiple_rc_protocols(self, realistic_model) -> THEN: Protocol should not be set due to ambiguity """ fc_parameters = {"RC_PROTOCOLS": 3} # Not a power of 2 - realistic_model._set_serial_type_from_fc_parameters(fc_parameters) - # Should not set protocol for non-power of 2 values + realistic_model.set_component_value(("RC Receiver", "FC Connection", "Type"), "SERIAL2") + realistic_model.set_component_value(("RC Receiver", "FC Connection", "Protocol"), "CRSF") + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: + realistic_model._set_serial_type_from_fc_parameters(fc_parameters) + mock_log.assert_called_once_with( + "RC_PROTOCOLS has multiple protocols enabled (%d). Cannot determine active protocol.", 3 + ) + assert realistic_model.get_component_value(("RC Receiver", "FC Connection", "Type")) == "SERIAL2" + assert realistic_model.get_component_value(("RC Receiver", "FC Connection", "Protocol")) == "CRSF" + + def test_set_rc_protocols_identifies_single_enabled_protocol(self, realistic_model) -> None: + """One known RC protocol bit selects its protocol and supplies the default type.""" + realistic_model.set_component_value(("RC Receiver", "FC Connection", "Type"), None) + realistic_model.set_component_value(("RC Receiver", "FC Connection", "Protocol"), None) + + realistic_model._process_rc_protocols({"RC_PROTOCOLS": 512}) + + assert realistic_model.get_component_value(("RC Receiver", "FC Connection", "Type")) == "RCin/SBUS" + assert realistic_model.get_component_value(("RC Receiver", "FC Connection", "Protocol")) == "CRSF" def test_set_serial_type_handles_invalid_serial_protocol_value(self, realistic_model) -> None: """ @@ -317,9 +396,123 @@ def test_set_serial_type_handles_invalid_serial_protocol_value(self, realistic_m """ with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PORTS", ["SERIAL1"]): fc_parameters = {"SERIAL1_PROTOCOL": "invalid"} - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: result = realistic_model._set_serial_type_from_fc_parameters(fc_parameters) assert result is False + mock_log.assert_called_once_with("Invalid non-integer value for SERIAL1_PROTOCOL invalid") + + @pytest.mark.parametrize("first_protocol", ["invalid", 0, 99, 77]) + def test_invalid_or_unsupported_serial_protocol_does_not_skip_later_ports( + self, realistic_model, first_protocol: str | int + ) -> None: + """A bad or unsupported serial protocol does not prevent later valid ports from importing.""" + with ( + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PORTS", + ["SERIAL1", "SERIAL2"], + ), + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PROTOCOLS_DICT", + { + "2": {"component": "Telemetry", "protocol": "MAVLink2"}, + "77": {"protocol": "Unused component"}, + }, + ), + ): + realistic_model._set_serial_type_from_fc_parameters({"SERIAL1_PROTOCOL": first_protocol, "SERIAL2_PROTOCOL": 2}) + + assert realistic_model.get_component_value(("Telemetry", "FC Connection", "Type")) == "SERIAL2" + assert realistic_model.get_component_value(("Telemetry", "FC Connection", "Protocol")) == "MAVLink2" + + def test_first_serial_telemetry_port_keeps_precedence(self, realistic_model) -> None: + """When multiple serial ports provide telemetry, the first configured port remains selected.""" + with ( + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PORTS", + ["SERIAL1", "SERIAL2"], + ), + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PROTOCOLS_DICT", + {"2": {"component": "Telemetry", "protocol": "MAVLink2"}}, + ), + ): + realistic_model._set_serial_type_from_fc_parameters({"SERIAL1_PROTOCOL": 2, "SERIAL2_PROTOCOL": 2}) + + assert realistic_model.get_component_value(("Telemetry", "FC Connection", "Type")) == "SERIAL1" + assert realistic_model.get_component_value(("Telemetry", "FC Connection", "Protocol")) == "MAVLink2" + + def test_missing_earlier_serial_parameter_does_not_skip_a_later_valid_port(self, realistic_model) -> None: + """Import scans later serial ports when earlier port parameters are absent.""" + with ( + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PORTS", + ["SERIAL1", "SERIAL2"], + ), + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PROTOCOLS_DICT", + {"2": {"component": "Telemetry", "protocol": "MAVLink2"}}, + ), + ): + realistic_model._set_serial_type_from_fc_parameters({"SERIAL2_PROTOCOL": 2}) + + assert realistic_model.get_component_value(("Telemetry", "FC Connection", "Type")) == "SERIAL2" + assert realistic_model.get_component_value(("Telemetry", "FC Connection", "Protocol")) == "MAVLink2" + + def test_missing_serial_protocol_component_does_not_skip_later_ports(self, realistic_model) -> None: + """A protocol entry without a component is skipped while later ports are still inspected.""" + with ( + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PORTS", + ["SERIAL1", "SERIAL2"], + ), + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PROTOCOLS_DICT", + { + "77": {"protocol": "Unused component"}, + "2": {"component": "Telemetry", "protocol": "MAVLink2"}, + }, + ), + ): + realistic_model._set_serial_type_from_fc_parameters({"SERIAL1_PROTOCOL": 77, "SERIAL2_PROTOCOL": 2}) + + assert realistic_model.get_component_value(("Telemetry", "FC Connection", "Type")) == "SERIAL2" + + def test_serial_gnss_import_keeps_the_first_receiver_port(self, realistic_model) -> None: + """The first serial GNSS port remains selected when firmware reports multiple receivers.""" + with ( + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PORTS", + ["SERIAL1", "SERIAL2"], + ), + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PROTOCOLS_DICT", + {"5": {"component": "GNSS Receiver", "protocol": "uBlox"}}, + ), + ): + realistic_model._set_serial_type_from_fc_parameters({"SERIAL1_PROTOCOL": 5, "SERIAL2_PROTOCOL": 5}) + + assert realistic_model.get_component_value(("GNSS Receiver", "FC Connection", "Type")) == "SERIAL1" + assert realistic_model.get_component_value(("GNSS Receiver", "FC Connection", "Protocol")) == "uBlox" + + def test_serial_esc_control_connection_populates_both_directions(self, realistic_model) -> None: + """A serial ESC control protocol configures the shared FC-to-ESC and ESC-to-FC connection.""" + with ( + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PORTS", + ["SERIAL1"], + ), + patch( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.SERIAL_PROTOCOLS_DICT", + {"23": {"component": "ESC", "protocol": "FETtecOneWire"}}, + ), + ): + is_serial_esc = realistic_model._set_serial_type_from_fc_parameters({"SERIAL1_PROTOCOL": 23}) + + assert is_serial_esc is True + assert realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Type")) == "SERIAL1" + assert realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Protocol")) == "FETtecOneWire" + assert realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Type")) == "SERIAL1" + assert realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Protocol")) == "FETtecOneWire" def test_set_esc_type_handles_invalid_mot_pwm_type(self, realistic_model) -> None: """ @@ -332,8 +525,61 @@ def test_set_esc_type_handles_invalid_mot_pwm_type(self, realistic_model) -> Non """ fc_parameters = {"MOT_PWM_TYPE": "invalid"} doc: dict = {} - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: realistic_model._set_esc_type_from_fc_parameters(fc_parameters, doc) + mock_log.assert_called_once_with("Invalid non-integer value for MOT_PWM_TYPE %s", "invalid") + assert realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Type")) == "Main Out" + + def test_missing_motor_pwm_type_uses_the_zero_default(self, realistic_model) -> None: + """A missing MOT_PWM_TYPE uses firmware's default value zero when metadata is available.""" + realistic_model._set_esc_type_from_fc_parameters({}, {"MOT_PWM_TYPE": {"values": {"0": "Normal", "1": "OneShot"}}}) + + assert realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Protocol")) == "Normal" + + @pytest.mark.parametrize( + ("telemetry_type", "telemetry_protocol"), + [("SERIAL3", "Scripting"), ("CAN1", "DroneCAN")], + ) + def test_dshot_import_preserves_a_dedicated_telemetry_connection( + self, realistic_model, telemetry_type: str, telemetry_protocol: str + ) -> None: + """DShot control import does not replace an independently detected serial or CAN back-channel.""" + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Type"), telemetry_type) + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Protocol"), telemetry_protocol) + + realistic_model._set_esc_type_from_fc_parameters({"MOT_PWM_TYPE": 6}, {"MOT_PWM_TYPE": {"values": {"6": "DShot600"}}}) + + assert realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Type")) == telemetry_type + assert realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Protocol")) == telemetry_protocol + + def test_non_dshot_import_preserves_a_dedicated_serial_telemetry_connection(self, realistic_model) -> None: + """A non-DShot control protocol leaves an already imported serial telemetry link intact.""" + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Type"), "SERIAL4") + realistic_model.set_component_value(("ESC", "ESC->FC Telemetry", "Protocol"), "ESC Telemetry") + + realistic_model._set_esc_type_from_fc_parameters({"MOT_PWM_TYPE": 0}, {"MOT_PWM_TYPE": {"values": {"0": "Normal"}}}) + + assert realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Type")) == "SERIAL4" + assert realistic_model.get_component_value(("ESC", "ESC->FC Telemetry", "Protocol")) == "ESC Telemetry" + + def test_esc_dictionary_fallback_uses_the_selected_firmware(self, realistic_model, monkeypatch) -> None: + """When parameter metadata is absent, ESC protocol lookup uses the active firmware dictionary.""" + realistic_model.set_component_value(("Flight Controller", "Firmware", "Type"), "ArduPlane") + requested_firmware_types: list[str] = [] + + def connection_options(firmware_type: str) -> dict: + requested_firmware_types.append(firmware_type) + return {"6": {"protocol": "PlaneDShot", "type": ("Main Out",)}} + + monkeypatch.setattr( + "ardupilot_methodic_configurator.data_model_vehicle_components_import.get_esc_connection_sub_dict", + connection_options, + ) + + realistic_model._set_esc_type_from_fc_parameters({"MOT_PWM_TYPE": 6}, {}) + + assert realistic_model.get_component_value(("ESC", "FC->ESC Connection", "Protocol")) == "PlaneDShot" + assert requested_firmware_types == ["ArduPlane"] def test_set_battery_type_handles_invalid_value(self, realistic_model) -> None: """ @@ -345,8 +591,17 @@ def test_set_battery_type_handles_invalid_value(self, realistic_model) -> None: AND: System should not crash """ fc_parameters = {"BATT_MONITOR": "invalid"} - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + realistic_model.set_component_value(("Battery Monitor", "FC Connection", "Type"), "Analog") + realistic_model.set_component_value(("Battery Monitor", "FC Connection", "Protocol"), "Analog Voltage and Current") + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: realistic_model._set_battery_type_from_fc_parameters(fc_parameters) + assert mock_log.call_args.args[0] == "Error processing BATT_MONITOR parameter: %s" + assert "invalid" in mock_log.call_args.args[1] + assert realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Type")) == "Analog" + assert ( + realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Protocol")) + == "Analog Voltage and Current" + ) def test_set_battery_type_handles_key_error(self, realistic_model) -> None: """ @@ -358,8 +613,16 @@ def test_set_battery_type_handles_key_error(self, realistic_model) -> None: AND: Error should be logged """ # pylint: disable=duplicate-code # Common error handling test pattern fc_parameters = {"BATT_MONITOR": 999} - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + realistic_model.set_component_value(("Battery Monitor", "FC Connection", "Type"), "Analog") + realistic_model.set_component_value(("Battery Monitor", "FC Connection", "Protocol"), "Analog Voltage and Current") + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: realistic_model._set_battery_type_from_fc_parameters(fc_parameters) + mock_log.assert_called_once_with("BATT_MONITOR value %s not found in BATT_MONITOR_CONNECTION", 999) + assert realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Type")) == "Analog" + assert ( + realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Protocol")) + == "Analog Voltage and Current" + ) # pylint: enable=duplicate-code def test_set_battery_type_handles_type_error(self, realistic_model) -> None: @@ -372,8 +635,17 @@ def test_set_battery_type_handles_type_error(self, realistic_model) -> None: AND: Error should be logged """ # pylint: disable=duplicate-code # Common error handling test pattern fc_parameters = {"BATT_MONITOR": None} - with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): + realistic_model.set_component_value(("Battery Monitor", "FC Connection", "Type"), "Analog") + realistic_model.set_component_value(("Battery Monitor", "FC Connection", "Protocol"), "Analog Voltage and Current") + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as mock_log: realistic_model._set_battery_type_from_fc_parameters(fc_parameters) + assert mock_log.call_args.args[0] == "Error processing BATT_MONITOR parameter: %s" + assert "NoneType" in mock_log.call_args.args[1] + assert realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Type")) == "Analog" + assert ( + realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Protocol")) + == "Analog Voltage and Current" + ) # pylint: enable=duplicate-code def test_set_battery_type_handles_tuple_type_values(self, realistic_model) -> None: @@ -395,6 +667,51 @@ def test_set_battery_type_handles_tuple_type_values(self, realistic_model) -> No assert batt_type == "Analog" assert batt_protocol == "Voltage" + @pytest.mark.parametrize(("bus", "expected"), [(1, "I2C2"), (99, "I2C1"), ("invalid", "I2C1")]) + def test_set_battery_type_selects_and_bounds_i2c_bus(self, realistic_model, bus: int | str, expected: str) -> None: + """The BATT_I2C_BUS index selects the matching I2C port and invalid indices fall back to I2C1.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as log_warning: + realistic_model._set_battery_type_from_fc_parameters({"BATT_MONITOR": 5, "BATT_I2C_BUS": bus}) + + assert realistic_model.get_component_value(("Battery Monitor", "FC Connection", "Type")) == expected + if bus == 99: + log_warning.assert_called_once_with("BATT_I2C_BUS value %d out of range (0-%d), defaulting to first bus", 99, 3) + elif bus == "invalid": + log_warning.assert_called_once_with("Invalid BATT_I2C_BUS value, defaulting to first bus") + else: + log_warning.assert_not_called() + + def test_motor_pole_import_uses_selected_firmware_esc_dictionary(self, realistic_model) -> None: + """DShot pole detection looks up the connection mapping for the selected firmware.""" + realistic_model.set_component_value(("Flight Controller", "Firmware", "Type"), "ArduCopter") + realistic_model.set_component_value(("Motors", "Specifications", "Poles"), 99) + + with patch.object( + _import_module, + "get_esc_connection_sub_dict", + wraps=_import_module.get_esc_connection_sub_dict, + ) as get_esc_dict: + realistic_model._set_motor_poles_from_fc_parameters({"MOT_PWM_TYPE": 6, "SERVO_BLH_POLES": 14}) + + get_esc_dict.assert_called_once_with("ArduCopter") + assert realistic_model.get_component_value(("Motors", "Specifications", "Poles")) == 14 + + def test_unknown_motor_pwm_type_does_not_break_motor_pole_import(self, realistic_model) -> None: + """An unknown PWM type with no matching metadata leaves the current pole count untouched.""" + realistic_model.set_component_value(("Motors", "Specifications", "Poles"), 99) + + realistic_model._set_motor_poles_from_fc_parameters({"MOT_PWM_TYPE": 999, "SERVO_BLH_POLES": 14}) + + assert realistic_model.get_component_value(("Motors", "Specifications", "Poles")) == 99 + + def test_fettec_pole_count_requires_mask_and_pole_value(self, realistic_model) -> None: + """A FETtec pole count is ignored unless both the mask and pole count are present.""" + realistic_model.set_component_value(("Motors", "Specifications", "Poles"), 99) + + realistic_model._set_motor_poles_from_fc_parameters({"MOT_PWM_TYPE": 0, "SERVO_FTW_POLES": 12}) + + assert realistic_model.get_component_value(("Motors", "Specifications", "Poles")) == 99 + def test_set_battery_capacity_from_fc_parameters(self, realistic_model) -> None: """ Battery capacity is correctly imported from FC parameters. @@ -434,6 +751,25 @@ def test_set_battery_capacity_handles_invalid_type(self, realistic_model) -> Non with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error"): realistic_model._set_battery_type_from_fc_parameters(fc_parameters) + @pytest.mark.parametrize("capacity", [0, -100]) + def test_battery_capacity_rejection_logs_exact_value(self, realistic_model, capacity: int) -> None: + """Zero and negative capacities are rejected with the exact FC value in the warning.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as log_warning: + realistic_model._import_bat_values_from_fc(BatteryVoltageSpecs(0, 3.0, 4.2, "Lipo", {"BATT_CAPACITY": capacity})) + + log_warning.assert_called_once_with("BATT_CAPACITY is zero or negative: %s", capacity) + + @pytest.mark.parametrize("capacity", [None, "unknown"]) + def test_battery_capacity_conversion_error_logs_exact_parameter_and_error(self, realistic_model, capacity) -> None: + """Invalid capacity values report their conversion failure with the parameter name.""" + with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_error") as log_error: + realistic_model._import_bat_values_from_fc(BatteryVoltageSpecs(0, 3.0, 4.2, "Lipo", {"BATT_CAPACITY": capacity})) + + log_error.assert_called_once() + args = log_error.call_args.args + assert args[0] == "Error processing BATT_CAPACITY parameter: %s" + assert args[1].startswith(("int() argument must be a string", "invalid literal for int()")) + def test_plane_battery_import_preserves_template_values_when_import_file_is_sparse(self, realistic_model) -> None: """ Sparse Plane imports preserve battery values already supplied by the template. @@ -581,7 +917,7 @@ def test_set_battery_type_warns_when_batt_monitor_not_in_fc_parameters(self, rea """ with patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning") as mock_warn: realistic_model._set_battery_type_from_fc_parameters({}) - mock_warn.assert_called() + mock_warn.assert_called_once_with("BATT_MONITOR parameter not found in fc_parameters") def test_set_battery_type_uses_default_chemistry_when_detection_returns_invalid_name(self, realistic_model) -> None: """ @@ -597,10 +933,36 @@ def test_set_battery_type_uses_default_chemistry_when_detection_returns_invalid_ with ( patch.object(realistic_model, "_detect_battery_chemistry_from_voltages", return_value="InvalidChemistry"), patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning"), + patch.object(realistic_model, "_estimate_battery_cell_count", return_value=4) as estimate, + patch.object(realistic_model, "_import_bat_values_from_fc") as import_values, ): - # Should not raise — invalid chemistry triggers fallback to default realistic_model._set_battery_type_from_fc_parameters({"BATT_MONITOR": 4}) + estimate.assert_called_once_with({"BATT_MONITOR": 4}, BATTERY_DEFAULT_CHEMISTRY) + specs = import_values.call_args.args[0] + assert specs.detected_chemistry == BATTERY_DEFAULT_CHEMISTRY + assert specs.limit_min == BatteryCell.limit_min_voltage(BATTERY_DEFAULT_CHEMISTRY) + assert specs.limit_max == BatteryCell.limit_max_voltage(BATTERY_DEFAULT_CHEMISTRY) + + def test_set_battery_type_preserves_valid_current_chemistry_when_detection_is_unavailable(self, realistic_model) -> None: + """Unavailable voltage evidence preserves a valid chemistry already selected in the model.""" + current_chemistry = "LiIon" + realistic_model.set_component_value(("Battery", "Specifications", "Chemistry"), current_chemistry) + + with ( + patch.object(realistic_model, "_detect_battery_chemistry_from_voltages", return_value=None), + patch.object(realistic_model, "_estimate_battery_cell_count", return_value=4) as estimate, + patch.object(realistic_model, "_import_bat_values_from_fc") as import_values, + patch("ardupilot_methodic_configurator.data_model_vehicle_components_import.logging_warning"), + ): + realistic_model._set_battery_type_from_fc_parameters({"BATT_MONITOR": 4, "BATT_ARM_VOLT": 20.0}) + + estimate.assert_called_once_with({"BATT_MONITOR": 4, "BATT_ARM_VOLT": 20.0}, current_chemistry) + specs = import_values.call_args.args[0] + assert specs.detected_chemistry == current_chemistry + assert specs.limit_min == BatteryCell.limit_min_voltage(current_chemistry) + assert specs.limit_max == BatteryCell.limit_max_voltage(current_chemistry) + def test_estimate_battery_cell_count_returns_zero_when_cell_path_not_in_validation_rules(self, realistic_model) -> None: """ Battery cell count estimation returns 0 when the cell path is absent from VALIDATION_RULES. diff --git a/tests/unit_data_model_vehicle_components_json_schema.py b/tests/unit_data_model_vehicle_components_json_schema.py index a4f52ba19..c585fa51b 100755 --- a/tests/unit_data_model_vehicle_components_json_schema.py +++ b/tests/unit_data_model_vehicle_components_json_schema.py @@ -385,10 +385,18 @@ def test_modify_schema_logs_debug_info(self) -> None: # Test successful modification json_schema.modify_schema_for_mcu_series(is_optional=True) - # Verify debug logging occurred - mock_debug.assert_called() - call_args = str(mock_debug.call_args) - assert "Modified schema: MCU Series" in call_args + assert mock_debug.call_count == 1 + assert mock_debug.call_args.args == ("Modified schema: MCU Series x-is-optional=%s to value=%u", True, True) + mock_debug.reset_mock() + json_schema.modify_schema_for_mcu_series(is_optional=False) + assert mock_debug.call_count == 1 + assert mock_debug.call_args.args == ("Modified schema: MCU Series x-is-optional=%s to value=%u", False, False) + assert ( + json_schema.schema["definitions"]["flightController"]["allOf"][0]["properties"]["Specifications"]["properties"][ + "MCU Series" + ].get("x-is-optional") + is None + ) def test_error_handling_in_schema_modification(self) -> None: """