From 2e420d2a43cc5ff7eaf0577ee52a7fa0caef7445 Mon Sep 17 00:00:00 2001 From: firestar5683 <168790843+firestar5683@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:17:37 -0600 Subject: [PATCH] Adopt Ty 0.0.112 --- .../safety/tests/libsafety/libsafety_py.py | 4 +- .../tests/test_hyundai_classic_scc_aol.py | 9 +-- .../safety/tests/test_hyundai_forte_aol.py | 5 +- .../tests/test_hyundai_ioniq6_stock_aol.py | 4 +- .../safety/tests/test_hyundai_kona_lda_aol.py | 25 ++++---- .../tests/test_hyundai_optional_release.py | 7 +-- .../tests/test_modem_cellular_disabled.py | 6 +- openpilot/selfdrive/car/car_events.py | 2 +- .../car/tests/test_lkas_long_only.py | 3 +- .../car/tests/test_radar_deferral.py | 1 + openpilot/selfdrive/controls/controlsd.py | 15 ++--- .../controls/lib/longitudinal_planner.py | 2 +- openpilot/selfdrive/controls/plannerd.py | 2 +- openpilot/selfdrive/controls/radard.py | 5 +- .../tests/test_cem_input_acquisition_order.py | 7 ++- .../tests/test_conditional_runtime_loop.py | 27 ++++++--- .../tests/test_longitudinal_plan_validity.py | 7 +++ .../selfdrive/controls/tests/test_voacc.py | 10 +++- .../selfdrive/locationd/models/car_kf.py | 15 +++-- openpilot/selfdrive/locationd/paramsd.py | 7 ++- openpilot/selfdrive/selfdrived/helpers.py | 4 +- openpilot/selfdrive/test/helpers.py | 7 ++- .../test/process_replay/process_replay.py | 7 ++- openpilot/selfdrive/test/test_onroad.py | 6 +- .../arabesque/tools/browser_session.py | 9 ++- openpilot/selfdrive/ui/layouts/onboarding.py | 8 +-- .../selfdrive/ui/layouts/settings/common.py | 4 +- .../selfdrive/ui/layouts/settings/firehose.py | 3 +- .../layouts/settings/initial_cruise_speed.py | 4 +- .../selfdrive/ui/layouts/settings/software.py | 12 ++-- .../selfdrive/ui/layouts/settings/toggles.py | 15 +++-- .../selfdrive/ui/layouts/training_guide.py | 4 +- openpilot/selfdrive/ui/mici/layouts/home.py | 4 +- .../selfdrive/ui/mici/layouts/onboarding.py | 20 +++---- .../ui/mici/layouts/settings/developer.py | 12 ++-- .../layouts/settings/device/device_layout.py | 30 +++++----- .../ui/mici/layouts/settings/device/prime.py | 34 +++++++---- .../mici/layouts/settings/network/esim_ui.py | 10 ++-- .../settings/network/network_layout.py | 15 +++-- .../ui/mici/layouts/settings/software.py | 8 +-- .../ui/mici/layouts/settings/toggles.py | 12 ++-- .../ui/mici/onroad/cabin_camera_dialog.py | 10 ++-- openpilot/selfdrive/ui/mici/widgets/dialog.py | 2 +- .../ui/onroad/cabin_camera_dialog.py | 6 +- .../selfdrive/ui/tests/diff/replay_script.py | 6 +- .../selfdrive/ui/tests/profile_onroad.py | 2 +- .../ui/tests/test_arabesque_browser.py | 7 +++ .../ui/tests/test_mici_projection_batch.py | 11 +++- openpilot/selfdrive/ui/ui.py | 10 ++-- openpilot/selfdrive/ui/ui_state.py | 18 ++++-- openpilot/selfdrive/ui/widgets/prime.py | 7 ++- .../starpilot/analytics/tests/test_runtime.py | 1 + .../starpilot/aol/tests/honda_pandad_order.py | 5 ++ .../starpilot/aol/tests/hyundai_cpp_order.py | 5 ++ .../aol/tests/stock_lateral_test_helpers.py | 16 ++++++ .../test_canfd_location_native_recovery.py | 1 + .../aol/tests/test_ccnc_full_stop_intent.py | 2 + .../aol/tests/test_distracted_lateral.py | 3 +- .../aol/tests/test_ev6_stock_parity.py | 10 +++- .../aol/tests/test_forte_integration.py | 3 + .../aol/tests/test_forte_physical_arm_join.py | 8 ++- openpilot/starpilot/aol/tests/test_gm.py | 5 +- .../aol/tests/test_gm_ascm_receive_order.py | 7 ++- .../aol/tests/test_gm_held_brake_successor.py | 7 ++- .../aol/tests/test_gm_receipt_clock_ipc.py | 2 + .../tests/test_gm_route1c_receive_order.py | 6 +- .../tests/test_gm_steering_receive_order.py | 6 +- .../aol/tests/test_hkg_cancel_joined.py | 11 +++- .../tests/test_honda_recovery_lifecycle.py | 6 +- .../aol/tests/test_honda_route_regressions.py | 7 ++- .../aol/tests/test_meb_actual_callers.py | 2 + .../aol/tests/test_mqb_actual_callers.py | 36 +++++++++--- .../aol/tests/test_panda_inventory.py | 29 ++++++++-- .../aol/tests/test_seatbelt_cold_start.py | 9 ++- .../aol/tests/test_seatbelt_lateral.py | 5 ++ .../test_sonata_cruise_only_withdrawal.py | 3 +- .../test_sonata_mapped_button_callers.py | 3 +- .../test_sonata_temporary_withdrawals.py | 3 +- openpilot/starpilot/aol/tests/test_toyota.py | 2 + .../aol/tests/test_transition_diagnostic.py | 4 ++ .../aol/tests/test_vehicle_policy_cache.py | 2 +- .../starpilot/aol/transport_pause_session.py | 2 +- .../audio/tests/test_complete_alert_assets.py | 2 +- .../bluetooth/tests/test_accept_pair.py | 4 ++ .../starpilot/bluetooth/tests/test_owner.py | 25 +++++++- openpilot/starpilot/car/ford/bluepilot.py | 4 +- .../honda/tests/test_bosch_a_integration.py | 7 ++- .../car/honda/tests/test_radar_pipeline.py | 5 +- openpilot/starpilot/car/mazda/stock_intent.py | 2 +- .../car/rivian/tests/test_aol_lifecycle.py | 2 + .../car/subaru/tests/pandad_order.py | 5 ++ .../subaru/tests/test_smoothing_model_join.py | 2 + .../car/tesla/tests/test_radar_pipeline.py | 4 +- .../tesla/tests/test_speed_sync_context.py | 1 + .../tests/test_legacy_radar_pre_warning.py | 4 +- .../toyota/tests/test_rav4h_caller_native.py | 1 + openpilot/starpilot/conditional_mode/host.py | 3 +- .../starpilot/conditional_mode/projection.py | 7 ++- .../starpilot/conditional_mode/status.py | 5 +- .../conditional_mode/tests/test_adjacent.py | 7 +++ .../tests/test_controller_mode_status.py | 3 +- .../tests/test_effective_status.py | 11 ++-- .../conditional_mode/tests/test_manual.py | 11 ++++ .../tests/test_manual_saved.py | 7 ++- .../tests/test_paired_clock.py | 3 +- .../tests/test_runtime_settings.py | 12 ++-- .../tests/test_scene_cadence.py | 2 +- .../tests/test_status_consumer.py | 2 + .../conditional_mode/tests/test_traffic.py | 13 +++-- .../conditional_mode/tests/test_ui_action.py | 8 +++ .../controllers/tests/test_coast_idle.py | 10 +++- .../controllers/tests/test_mode_actions.py | 3 +- .../controllers/tests/test_selfie.py | 3 + .../controllers/tests/test_wheel_ipc.py | 1 + .../curve_speed/tests/test_status.py | 2 + .../curve_speed/tests/test_target.py | 1 + openpilot/starpilot/flm/event_collection.py | 3 +- openpilot/starpilot/flm/event_collector.py | 2 + .../starpilot/flm/event_controller_replay.py | 6 +- .../starpilot/flm/feedback_observation.py | 7 ++- openpilot/starpilot/flm/fit_process.py | 20 +++++-- openpilot/starpilot/flm/global_runtime.py | 42 ++++++++++---- openpilot/starpilot/flm/learning_wire.py | 2 +- openpilot/starpilot/flm/live.py | 2 +- .../starpilot/flm/live_tracking_actor.py | 57 +++++++++++-------- openpilot/starpilot/flm/manual_coordinates.py | 2 +- openpilot/starpilot/flm/offroad_observed.py | 7 ++- openpilot/starpilot/flm/offroad_runtime.py | 6 +- openpilot/starpilot/flm/offroad_worker.py | 3 +- openpilot/starpilot/flm/selected_effects.py | 11 ++-- openpilot/starpilot/flm/steerlearnerd.py | 31 +++++----- .../flm/tests/test_actual_raw_worker.py | 9 ++- .../flm/tests/test_event_admission_clock.py | 9 +-- .../tests/test_event_application_success.py | 4 +- .../flm/tests/test_event_replay_cost.py | 1 + .../test_event_support_qualified_subset.py | 3 +- .../flm/tests/test_event_target_renewal.py | 2 +- .../flm/tests/test_full_effect_trace.py | 1 + .../flm/tests/test_full_surface_reporting.py | 3 + .../tests/test_global_event_capture_floor.py | 2 +- .../tests/test_healthy_maneuver_completion.py | 6 +- .../flm/tests/test_history_restore.py | 3 +- .../tests/test_live_tracking_probe_process.py | 1 + .../test_live_trial_actual_controller.py | 5 +- .../tests/test_live_trial_global_runtime.py | 1 + .../flm/tests/test_live_trial_owner.py | 1 + .../tests/test_offroad_process_lifecycle.py | 4 +- .../flm/tests/test_selected_effect_owner.py | 1 + .../flm/tests/test_source_baseline_recheck.py | 13 ++++- openpilot/starpilot/flm/torque_adapter.py | 2 + .../galaxy/companion_uplink_daemon.py | 7 ++- .../galaxy/companion_uplink_worker.py | 2 +- .../starpilot/galaxy/defaults_recovery.py | 5 +- openpilot/starpilot/galaxy/flm_diagnostics.py | 2 +- .../starpilot/galaxy/flm_saved_settings.py | 2 +- .../starpilot/galaxy/flm_training_results.py | 2 +- .../starpilot/galaxy/recording_library.py | 2 + openpilot/starpilot/galaxy/settings.py | 16 ++++-- .../test_projection_phone_window_http.py | 2 +- .../starpilot/galaxy/test_starport_http.py | 2 +- .../galaxy/tests/test_auth_runtime.py | 17 ++++-- .../galaxy/tests/test_companion_http.py | 3 +- .../galaxy/tests/test_device_state.py | 3 + .../tests/test_drive_stats_background.py | 6 +- .../galaxy/tests/test_drive_stats_http.py | 3 +- .../starpilot/galaxy/tests/test_flm_backup.py | 4 +- .../tests/test_local_hostname_runtime.py | 5 +- .../galaxy/tests/test_local_hostnames.py | 5 +- .../starpilot/galaxy/tests/test_managed.py | 2 +- .../galaxy/tests/test_model_recording.py | 2 +- .../starpilot/galaxy/tests/test_models.py | 5 +- .../galaxy/tests/test_recording_library.py | 5 +- .../galaxy/tests/test_reverse_proxy.py | 5 +- .../tests/test_sentry_notifications_http.py | 1 + .../tests/test_settings_live_context.py | 2 + .../galaxy/tests/test_sound_downloads.py | 3 +- .../galaxy/tests/test_spotify_setup.py | 3 +- .../galaxy/tests/test_starport_send.py | 1 + .../galaxy/tests/test_vasm_settings.py | 4 +- .../starpilot/galaxy_bluetooth/phone_ui.py | 6 +- .../galaxy_bluetooth/tests/test_bridge.py | 6 +- .../starpilot/lateral/gm_geometry_runtime.py | 5 +- openpilot/starpilot/lateral/ioniq6_policy.py | 25 ++++---- openpilot/starpilot/lateral/lane_centering.py | 2 +- .../tests/test_automatic_learning_source.py | 7 ++- .../lateral/tests/test_bolt_lane_runtime.py | 5 +- .../tests/test_bolt_manual_friction.py | 4 ++ .../lateral/tests/test_bolt_manual_gain.py | 3 + .../tests/test_controller_selection.py | 4 +- .../lateral/tests/test_global_lane_runtime.py | 2 + .../lateral/tests/test_gm_geometry_runtime.py | 8 ++- .../lateral/tests/test_gm_manual_torque.py | 8 +-- .../tests/test_ioniq6_torque_source.py | 2 +- .../lateral/tests/test_lane_change_cruise.py | 3 +- .../lateral/tests/test_lane_runtime.py | 48 +++++++++++----- .../lateral/tests/test_torque_learning.py | 9 +++ .../lateral/tests/test_torque_runtime.py | 10 +++- .../lateral/tests/test_volt_lane_runtime.py | 1 + openpilot/starpilot/longitudinal/extension.py | 6 +- .../longitudinal/tests/test_cruise_delay.py | 2 +- .../tests/test_experimental_release.py | 10 ++-- .../longitudinal/tests/test_follow_jerk.py | 1 + .../tests/test_force_stop_runtime.py | 7 ++- .../longitudinal/tests/test_gm_volt_stop.py | 1 + .../tests/test_lane_change_gap.py | 2 +- .../longitudinal/tests/test_lead_approach.py | 3 +- .../tests/test_lead_approach_planner.py | 2 +- .../tests/test_lead_approach_runtime.py | 8 +-- .../longitudinal/tests/test_mpc_cost_cache.py | 1 + .../tests/test_mpc_terminal_constraints.py | 7 ++- .../tests/test_profile_runtime.py | 15 ++++- .../longitudinal/tests/test_takeoffs.py | 1 + .../tests/test_traffic_acceleration.py | 15 ++++- .../longitudinal/tests/test_vision_stop.py | 8 +-- .../maps/tests/test_shadow_lifecycle.py | 6 +- openpilot/starpilot/models/runner.py | 1 + openpilot/starpilot/models/runtime.py | 14 ++++- .../models/runtime_bridge/guard-policy.json | 2 +- .../models/runtime_bridge/runtime.py | 2 +- .../starpilot/models/runtime_bridge/usb.py | 11 ++-- .../starpilot/models/tests/test_laboratory.py | 5 +- .../models/tests/test_laboratory_coherent.py | 4 +- .../models/tests/test_laboratory_layout.py | 10 +++- .../models/tests/test_laboratory_runner.py | 4 +- .../starpilot/models/tests/test_manager.py | 28 ++++++++- .../starpilot/models/tests/test_receipt.py | 7 ++- .../models/tests/test_shipped_default.py | 3 +- .../models/tests/test_usb_source_modes.py | 1 + .../starpilot/navigation/offline_owner.py | 3 +- .../tests/test_signal_stop_release.py | 1 + openpilot/starpilot/replay/export.py | 2 +- openpilot/starpilot/replay/owner.py | 8 ++- openpilot/starpilot/replay/render.py | 38 +++++++++---- .../starpilot/replay/tests/test_frames.py | 8 ++- .../sentry_mode/tests/test_actions.py | 5 +- openpilot/starpilot/software/fast_update.py | 2 +- openpilot/starpilot/soloist/phone_audio.py | 7 ++- openpilot/starpilot/soloist/supervisor.py | 7 ++- .../starpilot/soloist/tests/test_package.py | 1 + .../starpilot/speed_limits/offset_document.py | 2 +- openpilot/starpilot/speed_limits/selection.py | 15 ++--- .../tests/test_action_arbitration.py | 6 ++ .../speed_limits/tests/test_advance.py | 16 ++++++ .../tests/test_confirmation_engagement.py | 1 + .../speed_limits/tests/test_overrides.py | 4 ++ .../speed_limits/tests/test_runtime_replay.py | 14 +++++ .../speed_limits/tests/test_selection.py | 14 ++++- .../speed_limits/tests/test_set_speed.py | 1 + .../tests/test_tesla_set_speed.py | 9 ++- .../starpilot/speed_limits/vision/producer.py | 2 + .../speed_limits/vision/stop_signs.py | 2 +- .../tests/test_identity_native_lifecycle.py | 7 +++ .../vision/tests/test_material_validation.py | 2 + .../tests/test_speed_warning_context.py | 9 +++ .../vision/tests/test_stop_projection.py | 4 +- .../vision/tests/test_stop_signs.py | 5 +- .../speed_limits/vision/tests/test_vision.py | 12 ++++ .../spot_monitor/tests/test_inference.py | 3 + .../starpilot/system/starport/apk_identity.py | 10 +++- .../system/starport/bluetooth_bridge.py | 5 +- .../system/starport/bugsink_report.py | 6 +- .../system/starport/car_interface.py | 12 +++- .../system/starport/projection_onroad.py | 8 ++- .../starpilot/system/starport/supervisor.py | 15 +++-- .../system/starport/system_snapshot.py | 3 +- .../starport/test_configuration_authority.py | 1 + .../system/starport/tests/fake_head_unit.py | 2 + .../starport/tests/test_apk_identity.py | 9 ++- .../starport/tests/test_bugsink_report.py | 4 +- .../starport/tests/test_car_interface.py | 1 + .../tests/test_diagnostics_logging.py | 2 + .../starport/tests/test_media_controls.py | 2 +- .../system/starport/tests/test_nav_status.py | 4 +- .../starport/tests/test_phone_window.py | 4 ++ .../tests/test_projection_layout_runtime.py | 1 + .../starport/tests/test_projection_map.py | 8 +++ .../system/starport/tests/test_starport.py | 4 +- .../starport/tests/test_unacked_video.py | 1 + openpilot/starpilot/system/starport/view.py | 2 +- .../tests/test_dom_handoff_migration.py | 1 + openpilot/starpilot/tests/test_ev6_startup.py | 1 + .../starpilot/tests/test_ev9_lead_inputs.py | 2 +- .../tests/test_first_start_migration.py | 1 + .../tests/test_ford_native_pinion_guard.py | 11 +++- .../tests/test_ford_starpilot_angle.py | 4 +- .../starpilot/tests/test_gm_vision_source.py | 2 + openpilot/starpilot/ui/bluetooth_compact.py | 8 ++- openpilot/starpilot/ui/bluetooth_large.py | 10 ++-- openpilot/starpilot/ui/clip.py | 6 +- .../starpilot/ui/feature_settings_owner.py | 2 + .../starpilot/ui/layout_preview_renderer.py | 7 ++- .../starpilot/ui/longitudinal_developer.py | 4 +- .../starpilot/ui/native/_raylib_extra.pyi | 3 + openpilot/starpilot/ui/onroad_lane_alerts.py | 4 +- openpilot/starpilot/ui/onroad_map.py | 12 ++-- openpilot/starpilot/ui/onroad_map_layer.py | 2 + openpilot/starpilot/ui/onroad_uniden.py | 6 +- openpilot/starpilot/ui/path_markers.py | 3 +- openpilot/starpilot/ui/replay_settings.py | 13 +++-- openpilot/starpilot/ui/runtime_app.py | 34 ++++++----- openpilot/starpilot/ui/runtime_compact.py | 9 ++- openpilot/starpilot/ui/shell.py | 16 +++--- openpilot/starpilot/ui/spacepilot/session.py | 3 +- .../ui/tests/test_bluetooth_compact.py | 6 ++ .../ui/tests/test_cem_passive_scene.py | 3 + .../ui/tests/test_conditional_feature.py | 7 ++- .../ui/tests/test_controller_feature.py | 7 ++- .../starpilot/ui/tests/test_covered_camera.py | 3 +- .../ui/tests/test_curve_glow_flicker.py | 12 ++-- .../ui/tests/test_developer_preview.py | 4 ++ .../starpilot/ui/tests/test_dinish_speed.py | 1 + .../ui/tests/test_display_settings.py | 1 + .../test_experimental_mode_persistence.py | 6 +- .../ui/tests/test_feature_settings_lateral.py | 11 ++-- .../tests/test_feature_settings_navigation.py | 11 ++-- .../ui/tests/test_feature_settings_visuals.py | 34 +++++++---- .../tests/test_global_feature_presentation.py | 7 ++- .../starpilot/ui/tests/test_home_actions.py | 2 + .../ui/tests/test_home_stats_source.py | 11 ++++ .../ui/tests/test_lane_change_feature.py | 7 ++- .../ui/tests/test_lane_strength_native.py | 7 ++- .../ui/tests/test_layout_preview_renderer.py | 9 +++ .../ui/tests/test_long_profile_feature.py | 9 +-- openpilot/starpilot/ui/tests/test_maps.py | 5 +- openpilot/starpilot/ui/tests/test_models.py | 6 +- .../starpilot/ui/tests/test_onroad_axes.py | 4 +- .../ui/tests/test_onroad_customization.py | 1 + .../starpilot/ui/tests/test_onroad_dm.py | 5 ++ .../ui/tests/test_onroad_favorites.py | 3 + .../ui/tests/test_onroad_lane_alerts.py | 3 +- .../starpilot/ui/tests/test_onroad_map.py | 7 ++- .../ui/tests/test_onroad_navigation.py | 9 +-- .../starpilot/ui/tests/test_pip_settings.py | 4 +- .../starpilot/ui/tests/test_pip_sidecam.py | 4 +- .../ui/tests/test_replay_settings.py | 3 +- .../ui/tests/test_runtime_navigation.py | 6 +- .../ui/tests/test_runtime_onroad_leaf.py | 7 ++- .../ui/tests/test_settings_actions.py | 3 +- .../starpilot/ui/tests/test_slc_ui_runtime.py | 5 +- .../ui/tests/test_sounds_settings.py | 1 + .../starpilot/ui/tests/test_traffic_status.py | 4 +- .../ui/tests/test_ui_started_authority.py | 11 ++-- .../starpilot/ui/tests/test_value_editors.py | 4 +- .../ui/tests/test_vision_speed_units.py | 1 + openpilot/starpilot/ui/tests/test_weather.py | 3 +- openpilot/starpilot/ui/toggles_state.py | 4 +- openpilot/system/athena/athenad.py | 1 + .../athena/tests/test_upload_preferences.py | 3 +- .../loggerd/tests/test_legacy_recordings.py | 1 + .../system/loggerd/tests/test_loggerd.py | 2 + openpilot/system/manager/process.py | 2 +- .../manager/test/test_process_recovery.py | 8 ++- .../sensord/tests/test_worker_lifecycle.py | 2 + openpilot/system/ui/lib/application.py | 31 ++++++---- openpilot/system/ui/widgets/list_view.py | 19 +++---- openpilot/system/ui/widgets/network.py | 7 ++- .../system/updated/tests/test_fast_request.py | 6 +- openpilot/system/webrtc/device/video.py | 1 + openpilot/system/webrtc/webrtcd.py | 1 + .../lateral_maneuvers/lateral_maneuversd.py | 2 + .../tools/plotjuggler/test_plotjuggler.py | 4 +- openpilot/tools/replay/tests/test_machine.py | 25 +++++++- .../tools/replay/tests/test_onroad_host.py | 18 ++++++ prebuilt.json | 2 +- pyproject.toml | 4 +- uv.lock | 50 ++++++++-------- 366 files changed, 1777 insertions(+), 752 deletions(-) create mode 100644 openpilot/starpilot/ui/native/_raylib_extra.pyi diff --git a/opendbc_repo/opendbc/safety/tests/libsafety/libsafety_py.py b/opendbc_repo/opendbc/safety/tests/libsafety/libsafety_py.py index 61e6997c99..b785838daf 100644 --- a/opendbc_repo/opendbc/safety/tests/libsafety/libsafety_py.py +++ b/opendbc_repo/opendbc/safety/tests/libsafety/libsafety_py.py @@ -100,7 +100,9 @@ class CANPacket: ffi.cdef("void mutation_set_active_mutant(int id); int mutation_get_active_mutant(void);") class LibSafety: - pass + def safety_rx_hook(self, packet: CANPacket, /) -> bool: ... + def aol_get_request_mask(self, /) -> int: ... + def aol_get_permission_mask(self, /) -> int: ... libsafety: LibSafety libpath: str diff --git a/opendbc_repo/opendbc/safety/tests/test_hyundai_classic_scc_aol.py b/opendbc_repo/opendbc/safety/tests/test_hyundai_classic_scc_aol.py index 3691c0325e..c4ecb73524 100644 --- a/opendbc_repo/opendbc/safety/tests/test_hyundai_classic_scc_aol.py +++ b/opendbc_repo/opendbc/safety/tests/test_hyundai_classic_scc_aol.py @@ -1,18 +1,11 @@ """Classic SCC physical ownership remains separate from stock longitudinal control.""" -import unittest from opendbc.car.structs import CarParams from opendbc.safety.tests import test_hyundai_grouped_non_scc_aol as grouped from opendbc.safety.tests import test_hyundai_kona_lda_aol as fixture -class TestHyundaiClassicSccAol(unittest.TestCase): - setUp = fixture.TestHyundaiKonaLdaAol.setUp - tearDown = fixture.TestHyundaiKonaLdaAol.tearDown - reset = fixture.TestHyundaiKonaLdaAol.reset - rx = fixture.TestHyundaiKonaLdaAol.rx - request = fixture.TestHyundaiKonaLdaAol.request - +class TestHyundaiClassicSccAol(fixture.KonaAolFixture): def feed(self, word, main=False, source=None, pressed=False, scc11=True, main_bus=None): self.safety.set_timer(self.now) count = self.counter diff --git a/opendbc_repo/opendbc/safety/tests/test_hyundai_forte_aol.py b/opendbc_repo/opendbc/safety/tests/test_hyundai_forte_aol.py index df35e9cb94..6b68eb9370 100644 --- a/opendbc_repo/opendbc/safety/tests/test_hyundai_forte_aol.py +++ b/opendbc_repo/opendbc/safety/tests/test_hyundai_forte_aol.py @@ -7,7 +7,7 @@ from opendbc.safety.tests.libsafety import libsafety_py from opendbc.safety.tests.test_hyundai import checksum -class TestHyundaiForteAol(unittest.TestCase): +class ForteAolFixture(unittest.TestCase): def setUp(self): self.safety = libsafety_py.libsafety self.packer = CANPackerSafety('hyundai_can_generated') @@ -48,6 +48,8 @@ class TestHyundaiForteAol(unittest.TestCase): self.safety.aol_set_host_request(mask) return self.safety.aol_get_permission_mask() + +class TestHyundaiForteAol(ForteAolFixture): def test_main_before_cruise_and_exact_mode_word_experience(self): for word, source in ((0x1400, None), (0x1c00, 'BCM_PO_11'), (0x1c00, 'CLU13')): self.reset(word) @@ -132,6 +134,7 @@ class TestHyundaiForteAol(unittest.TestCase): self.reset(0x1400) for _ in range(3): self.feed(main=True, source=None) + def steer(torque, request): return self.packer.make_can_msg_safety('LKAS11', 0, { 'CR_Lkas_StrToqReq': torque, 'CF_Lkas_ActToi': request}) diff --git a/opendbc_repo/opendbc/safety/tests/test_hyundai_ioniq6_stock_aol.py b/opendbc_repo/opendbc/safety/tests/test_hyundai_ioniq6_stock_aol.py index d2eda8fda0..a8841ca253 100644 --- a/opendbc_repo/opendbc/safety/tests/test_hyundai_ioniq6_stock_aol.py +++ b/opendbc_repo/opendbc/safety/tests/test_hyundai_ioniq6_stock_aol.py @@ -7,7 +7,7 @@ from opendbc.safety.tests.libsafety import libsafety_py from opendbc.safety.tests.test_hyundai_ioniq6_long import params -class TestHyundaiIoniq6StockAol(unittest.TestCase): +class Ioniq6StockAolFixture(unittest.TestCase): def mode(self, raw): self.safety = libsafety_py.libsafety self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, raw), 0) @@ -44,6 +44,8 @@ class TestHyundaiIoniq6StockAol(unittest.TestCase): self.safety.set_aol_test_heartbeat(True) self.safety.aol_set_host_request(3) + +class TestHyundaiIoniq6StockAol(Ioniq6StockAolFixture): def test_stock_scc_and_physical_gesture_share_request_gate(self): for raw in (0x811, 0x891): with self.subTest(raw=raw): diff --git a/opendbc_repo/opendbc/safety/tests/test_hyundai_kona_lda_aol.py b/opendbc_repo/opendbc/safety/tests/test_hyundai_kona_lda_aol.py index d9387b3e57..b33e536a89 100644 --- a/opendbc_repo/opendbc/safety/tests/test_hyundai_kona_lda_aol.py +++ b/opendbc_repo/opendbc/safety/tests/test_hyundai_kona_lda_aol.py @@ -1,27 +1,24 @@ """Exact Kona LDA uses the already-qualified classic physical token owner.""" -import unittest from opendbc.car.structs import CarParams from opendbc.safety.tests import test_hyundai_forte_aol as fixture -class TestHyundaiKonaLdaAol(unittest.TestCase): - setUp = fixture.TestHyundaiForteAol.setUp - tearDown = fixture.TestHyundaiForteAol.tearDown - rx = fixture.TestHyundaiForteAol.rx - feed = fixture.TestHyundaiForteAol.feed - request = fixture.TestHyundaiForteAol.request - +class KonaAolFixture(fixture.ForteAolFixture): def reset(self, word=0x1c40, experience=32, mode=CarParams.SafetyModel.hyundai): - return fixture.TestHyundaiForteAol.reset(self, word, experience, mode) + return super().reset(word, experience, mode) - test_combined_sources_do_not_double_toggle_and_neutral_retains_token = fixture.TestHyundaiForteAol.test_combined_sources_do_not_double_toggle_and_neutral_retains_token + +class TestHyundaiKonaLdaAol(KonaAolFixture): + test_combined_sources_do_not_double_toggle_and_neutral_retains_token = ( + fixture.TestHyundaiForteAol.test_combined_sources_do_not_double_toggle_and_neutral_retains_token) test_unclaimed_token_and_missing_required_sources_expire = fixture.TestHyundaiForteAol.test_unclaimed_token_and_missing_required_sources_expire test_new_or_expired_held_source_requires_its_own_neutral = fixture.TestHyundaiForteAol.test_new_or_expired_held_source_requires_its_own_neutral def test_exact_kona_lda_namespace_and_no_independent_longitudinal(self): for source in ('BCM_PO_11','CLU13'): self.reset() - for _ in range(6): self.feed(main=False, source=source) + for _ in range(6): + self.feed(main=False, source=source) self.feed(main=False,source=source,pressed=True) self.assertFalse(self.safety.get_controls_allowed()) self.assertEqual(self.request(1),1) @@ -29,9 +26,11 @@ class TestHyundaiKonaLdaAol(unittest.TestCase): self.assertEqual(self.request(2),0) for word in (0x1840,0x1c43,0x1c42,0x1c44,0x9c40,0x3c40): self.reset(word) - for _ in range(6): self.feed(main=True) + for _ in range(6): + self.feed(main=True) self.assertEqual(self.request(1),0) for experience in (0,1,33): self.reset(experience=experience) - for _ in range(6): self.feed(main=True) + for _ in range(6): + self.feed(main=True) self.assertEqual(self.request(1),0) diff --git a/opendbc_repo/opendbc/safety/tests/test_hyundai_optional_release.py b/opendbc_repo/opendbc/safety/tests/test_hyundai_optional_release.py index 9e2e7d1d67..c830457167 100644 --- a/opendbc_repo/opendbc/safety/tests/test_hyundai_optional_release.py +++ b/opendbc_repo/opendbc/safety/tests/test_hyundai_optional_release.py @@ -1,5 +1,4 @@ """Optional torque-AOL release owns a separate, negotiated physical lease.""" -import unittest from opendbc.car import structs from opendbc.safety.tests.libsafety import libsafety_py @@ -7,9 +6,7 @@ import opendbc.safety.tests.test_hyundai_ioniq6_stock_aol as stock_helpers import opendbc.safety.tests.test_hyundai_hda2_long_aol as long_helpers -class TestHyundaiOptionalRelease(unittest.TestCase): - packet = stock_helpers.TestHyundaiIoniq6StockAol.packet - rx = stock_helpers.TestHyundaiIoniq6StockAol.rx +class TestHyundaiOptionalRelease(stock_helpers.Ioniq6StockAolFixture): def assert_rx_profile(self): self.assertFalse(self.safety.get_relay_malfunction(), self.context) @@ -29,7 +26,7 @@ class TestHyundaiOptionalRelease(unittest.TestCase): ("MDPS", {"MDPS_StrTqSnsrVal": 0}), ("CRUISE_BUTTONS", {})): self.rx(name, values) else: - stock_helpers.TestHyundaiIoniq6StockAol.healthy(self, acc) + super().healthy(acc) self.assert_rx_profile() def tx(self, torque, request): diff --git a/openpilot/common/hardware/comma/tests/test_modem_cellular_disabled.py b/openpilot/common/hardware/comma/tests/test_modem_cellular_disabled.py index d0584fe5ca..9ede2edce4 100644 --- a/openpilot/common/hardware/comma/tests/test_modem_cellular_disabled.py +++ b/openpilot/common/hardware/comma/tests/test_modem_cellular_disabled.py @@ -5,9 +5,9 @@ from openpilot.common.hardware.comma.modem import Modem, State def _modem(params): m = Modem() - m._read_param = lambda key: params.get(key, "") # ty: ignore[invalid-assignment] # test double - m._publish_state = lambda **kw: m.S.update(kw) # ty: ignore[invalid-assignment] # test double - m._atv = lambda cmd, pfx: '2,1' if cmd in ("AT+CREG?", "AT+CGREG?") else None # ty: ignore[invalid-assignment] # test double + m._read_param = lambda key: params.get(key, "") + m._publish_state = lambda **kw: m.S.update(kw) + m._atv = lambda cmd, pfx: '2,1' if cmd in ("AT+CREG?", "AT+CGREG?") else None return m diff --git a/openpilot/selfdrive/car/car_events.py b/openpilot/selfdrive/car/car_events.py index e5fc2e7a7d..d136a5e573 100644 --- a/openpilot/selfdrive/car/car_events.py +++ b/openpilot/selfdrive/car/car_events.py @@ -109,7 +109,7 @@ class CarEvents: # events.add(EventName.steerTimeLimit) elif self.CP.brand == 'leapmotor': - if self.leapmotor_cancel.update(CS, CS_prev): + if self.leapmotor_cancel is not None and self.leapmotor_cancel.update(CS, CS_prev): from openpilot.starpilot.car.leapmotor.events import announce announce(events) diff --git a/openpilot/selfdrive/car/tests/test_lkas_long_only.py b/openpilot/selfdrive/car/tests/test_lkas_long_only.py index 6d9f54e012..1cca1d3e87 100644 --- a/openpilot/selfdrive/car/tests/test_lkas_long_only.py +++ b/openpilot/selfdrive/car/tests/test_lkas_long_only.py @@ -11,6 +11,7 @@ from opendbc.car.hyundai.tests.test_ioniq6_longitudinal import controller_fixtur from opendbc.car.hyundai.values import DBC from opendbc.car.interfaces import RadarInterfaceBase from opendbc.car.structs import car +from openpilot.common.test import require_value from openpilot.cereal import log, messaging from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix @@ -47,7 +48,7 @@ def test_full_lkas_long_only_actual_owners_output_and_presentation(alt, prearmed card = Car(Interface(), Radar(cp)) sd, controls = SelfdriveD(), Controls() - assert card.aol_card_intent.explicit_latch and sd.aol_replay and controls.aol_replay + assert require_value(card.aol_card_intent).explicit_latch and sd.aol_replay and controls.aol_replay sd.initialized = True sd.state_machine.state = log.SelfdriveState.OpenpilotState.enabled audio = AxisAlerts() diff --git a/openpilot/selfdrive/car/tests/test_radar_deferral.py b/openpilot/selfdrive/car/tests/test_radar_deferral.py index fc31210dcc..1cbe55b025 100644 --- a/openpilot/selfdrive/car/tests/test_radar_deferral.py +++ b/openpilot/selfdrive/car/tests/test_radar_deferral.py @@ -51,6 +51,7 @@ def healthy_stock_card_step(mode="normal"): return frames def radar_bank(): + assert radar.rcp is not None return [radar_packer.make_can_msg(f'RADAR_TRACK_{addr:x}', radar.rcp.bus, {'STATE': 3, 'LONG_DIST': float(addr - radar.start_addr + 10), 'LAT_DIST': 0., 'REL_SPEED': -1.}) for addr in range(radar.start_addr, radar.start_addr + radar.msg_count)] diff --git a/openpilot/selfdrive/controls/controlsd.py b/openpilot/selfdrive/controls/controlsd.py index d83a8ed7f1..b48358c622 100755 --- a/openpilot/selfdrive/controls/controlsd.py +++ b/openpilot/selfdrive/controls/controlsd.py @@ -439,7 +439,7 @@ class Controls: and not any(e.overrideLongitudinal for e in self.sm['onroadEvents']) ) - if diagnostic_entry is not None: + if diagnostic_entry is not None and diagnostic_observer is not None: diagnostic_gate = diagnostic_observer.capture(self.sm, now_ns) diagnostic_native = native diagnostic_initial_lateral = bool(CC.latActive) @@ -501,23 +501,24 @@ class Controls: CC.latActive = bool(CC.latActive and pause_allowed) - if self.torque_host is not None: + torque_host = self.torque_host + if torque_host is not None: # The optional source must not keep an active torque request through lost car state. CC.latActive = bool(CC.latActive and CS.canValid and not CS.canTimeout) now_ns = int(self.sm.logMonoTime['carState']) if os.getenv('REPLAY') == '1' else time.monotonic_ns() - tune = self.torque_host.sample(self.sm, now_ns=now_ns, lat_active=bool(CC.latActive)) + tune = torque_host.sample(self.sm, now_ns=now_ns, lat_active=bool(CC.latActive)) from openpilot.starpilot.flm.native_baseline import apply_native_refinement from openpilot.starpilot.lateral.torque_tuning import TorqueSource native_applied = bool( self.torque_learning_allowed and tune.source == TorqueSource.LEARNED - and self.torque_host.settings.user_factor is None - and self.torque_host.settings.user_friction is None - and apply_native_refinement(self.LaC, self.CP, self.sm, now_ns=now_ns, host=True, apply=lambda: self.torque_host.apply(self.LaC, tune)) + and torque_host.settings.user_factor is None + and torque_host.settings.user_friction is None + and apply_native_refinement(self.LaC, self.CP, self.sm, now_ns=now_ns, host=True, apply=lambda: torque_host.apply(self.LaC, tune)) ) if not native_applied: - self.torque_host.apply(self.LaC, tune) + torque_host.apply(self.LaC, tune) if not CC.latActive: self.LaC.pid.reset() diff --git a/openpilot/selfdrive/controls/lib/longitudinal_planner.py b/openpilot/selfdrive/controls/lib/longitudinal_planner.py index 19f3e03d3b..91314978e9 100755 --- a/openpilot/selfdrive/controls/lib/longitudinal_planner.py +++ b/openpilot/selfdrive/controls/lib/longitudinal_planner.py @@ -414,7 +414,7 @@ class LongitudinalPlanner: if type(global_braking_response) is str else None) selected_braking = (selected_profiles.cruise_brake_magnitude if profile_eligible and selected_profiles is not None else None) - if selected_braking is not None: + if selected_braking is not None and selected_profiles is not None: global_magnitude = selected_braking # One resolved response, never multiplied or stacked. global_braking_response = selected_profiles.braking_style global_selected = (global_magnitude is not None and profile_eligible and (traffic_mode is False or selected_braking is not None) and diff --git a/openpilot/selfdrive/controls/plannerd.py b/openpilot/selfdrive/controls/plannerd.py index abc31ddfe2..398bb1cbd9 100755 --- a/openpilot/selfdrive/controls/plannerd.py +++ b/openpilot/selfdrive/controls/plannerd.py @@ -433,7 +433,7 @@ def starpilot_main(): current_start_ns = (int(sm['deviceState'].startedMonoTime) if 'deviceState' in subscribed_services and sm.valid['deviceState'] and sm.alive['deviceState'] and 0 < sm.logMonoTime['deviceState'] <= now_ns else 0) - if stop_resume_sock is not None: + if stop_resume_sock is not None and force_stop_owner is not None: collect_resume(force_stop_owner.resume, stop_resume_sock, messaging.recv_one_or_none, now_ns=now_ns, drive_id=current_start_ns, receive_clock=time.monotonic_ns if 'REPLAY' not in os.environ else None) diff --git a/openpilot/selfdrive/controls/radard.py b/openpilot/selfdrive/controls/radard.py index 016d0cc744..c5d7e3d2f4 100755 --- a/openpilot/selfdrive/controls/radard.py +++ b/openpilot/selfdrive/controls/radard.py @@ -260,8 +260,11 @@ class RadarD: car_stamp = int(sm.logMonoTime['carState']) camera_eof = int(sm['modelV2'].timestampEof) self.adjacent_sources = (radar_stamp, model_stamp, car_stamp, camera_eof) + state = self.radar_state + if state is None: + return primary_ids = frozenset( - int(getattr(lead, 'radarTrackId', -1)) for lead in (self.radar_state.leadOne, self.radar_state.leadTwo) + int(getattr(lead, 'radarTrackId', -1)) for lead in (state.leadOne, state.leadTwo) if bool(getattr(lead, 'present', False)) and bool(getattr(lead, 'radar', False)) and int(getattr(lead, 'radarTrackId', -1)) >= 0 ) frame = AdjacentFrame( diff --git a/openpilot/selfdrive/controls/tests/test_cem_input_acquisition_order.py b/openpilot/selfdrive/controls/tests/test_cem_input_acquisition_order.py index 5534534a25..b748502517 100644 --- a/openpilot/selfdrive/controls/tests/test_cem_input_acquisition_order.py +++ b/openpilot/selfdrive/controls/tests/test_cem_input_acquisition_order.py @@ -103,7 +103,7 @@ class TestCemInputAcquisitionOrder(unittest.TestCase): patch.object(feature_runtime, 'read_slc_settings', side_effect=read): runtime, changed = owner.refresh(MONO) self.assertTrue(changed) - self.assertIsNotNone(runtime) + assert runtime is not None self.assertEqual(owner.configuration, expected) self.assertEqual(len(reads), 1) self.assertEqual(owner.refresh(MONO+50_000_000), (runtime, False)) @@ -167,6 +167,7 @@ class TestCemDelayedBatchTransport(unittest.TestCase): manual=manual_for_drive(ManualIntent.NONE, self.fixture.drive_id, self.fixture.drive_id+1), owner_context=owner_context(source), selected_t_follow_s=1.45, selected_t_follow_observed_mono_ns=source) + assert result.projected is not None self.assertIsNone(result.projected.authority) self.assertIsNone(result.override_experimental) self.assertEqual(result.status, 'authority_unavailable') @@ -191,7 +192,7 @@ class TestCemDelayedBatchTransport(unittest.TestCase): self.assertEqual(sm['modelV2'].as_builder().to_bytes(), model) self.assertEqual(sm.logMonoTime['modelV2'], model_stamp) wire = observation(event.slcState, now) - self.assertIsNotNone(wire) + assert wire is not None assert wire is not None self.assertEqual(wire.model_ns, model_stamp) ack = publish_ack(session='a'*32, sequence=1, observed_ns=now, @@ -200,7 +201,7 @@ class TestCemDelayedBatchTransport(unittest.TestCase): displayed = ConditionalDisplayProjector().project(ack.starpilotSelfdriveState, now_ns=now, event_ns=now, selfdrive_ns=now-1_000_000, drive_id=self.fixture.drive_id, selfdrive_experimental=True, selfdrive_enabled=True, long_active=True, car_valid=True, system_long=True) - self.assertIsNotNone(displayed) + assert displayed is not None self.assertEqual(displayed.reason, 'cem_stop') self.assertTrue(displayed.effective_experimental) diff --git a/openpilot/selfdrive/controls/tests/test_conditional_runtime_loop.py b/openpilot/selfdrive/controls/tests/test_conditional_runtime_loop.py index 1e5459982c..0d0035619d 100644 --- a/openpilot/selfdrive/controls/tests/test_conditional_runtime_loop.py +++ b/openpilot/selfdrive/controls/tests/test_conditional_runtime_loop.py @@ -10,6 +10,7 @@ from unittest.mock import Mock, call, patch from opendbc.car.honda.interface import CarInterface from opendbc.car.honda.values import CAR +from openpilot.common.test import require_value from openpilot.starpilot.audio.departure_alert import DepartureNotifications from openpilot.cereal import messaging from openpilot.common.params import Params @@ -187,7 +188,7 @@ class TestConditionalRuntimeLoop(unittest.TestCase): params.put_bool('ShowSpeedLimits', True, block=True) display, changed = owner.refresh(2_000_000_000) self.assertTrue(changed) - self.assertIsNotNone(display) + assert display is not None self.assertFalse(display.settings.enabled) self.assertFalse(display.vision_enabled) params.put('SLCPriority1', 'Vision', block=True) @@ -341,22 +342,28 @@ class TestConditionalRuntimeLoop(unittest.TestCase): now_boot_ns=BOOT + stamp - MONO + 2_000_000, sample_skew_ns=1000, drive_id=MONO - 1_000_000_000, native_plan_valid=True) self.assertIs(current.choice, ModeChoice.CEM) - if current.projected.authority is None: + projected = require_value(current.projected) + authority = projected.authority + if authority is None: ccm_policy.reset() # The initial subscription barrier has no fresh authority yet. ccm_decision = None else: - ccm_decision = ccm_policy.step((stamp + 2_000_000) / 1e9, ModeChoice.CCM, ManualIntent.NONE, - current.projected.authority, current.projected.scene) + ccm_decision = ccm_policy.step((stamp + 2_000_000) / 1e9, ModeChoice.CCM, ManualIntent.NONE, authority, projected.scene) self.assertEqual(legacy.read_bytes(), saved_modes[index % len(saved_modes)]) if 20 <= index < 30: + assert current.projected is not None self.assertIs(current.projected.scene.adjacent_lead_ambiguous, False) + assert current.decision is not None self.assertEqual(current.decision.reason.value, 'no_trigger') - self.assertIsNotNone(ccm_decision) + assert ccm_decision is not None self.assertEqual(ccm_decision.reason.value, 'ccm_speed') self.assertIs(ccm_decision.requested_experimental, False) self.assertIs(current.override_experimental, False) + assert current.projected is not None self.assertIs(current.projected.scene.adjacent_lead_ambiguous, True) + assert ccm_decision is not None self.assertEqual(ccm_decision.reason.value, 'ccm_veto') + assert ccm_decision is not None self.assertIs(ccm_decision.requested_experimental, True) # Real adjacent radar veto exits Chill immediately. def test_current_build_disabled_scenes_make_chill_launch_known(self): @@ -412,8 +419,8 @@ class TestConditionalRuntimeLoop(unittest.TestCase): assert proposal.projected is not None self.assertFalse(proposal.projected.scene.traffic_mode) self.assertFalse(proposal.projected.scene.stop_sign_confirmed) - self.assertIsNotNone(proposal.projected.stop_source_observed_mono_s) - self.assertIsNotNone(proposal.projected.slower_source_observed_mono_s) + assert proposal.projected.stop_source_observed_mono_s is not None + assert proposal.projected.slower_source_observed_mono_s is not None # A future enabled traffic owner with no fresh frame stays unknown. Its # absence cannot be silently converted into a clear traffic scene. @@ -482,6 +489,7 @@ class TestConditionalRuntimeLoop(unittest.TestCase): proposal, _ = owner.sample(sm, cp, planner, now_mono_ns=stamp + 1_000_000, now_boot_ns=BOOT + 51_000_000, sample_skew_ns=1000, drive_id=MONO, manual_event=current_manual_event(manual, stamp + 1_000_000, stamp)) + assert owner.manual_state is not None self.assertEqual(owner.manual_state.intent.value, 'force_experimental') self.assertTrue(proposal.override_experimental) params.put('LKASButtonControl', 0, block=True) @@ -491,10 +499,12 @@ class TestConditionalRuntimeLoop(unittest.TestCase): planner.update(sm) owner.sample(sm, cp, planner, now_mono_ns=later + 1_000_000, now_boot_ns=BOOT + 101_000_000, sample_skew_ns=1000, drive_id=MONO, manual_event=receipt(2, later, fingerprint)) + assert owner.manual_state is not None self.assertEqual(owner.manual_state.intent.value, 'force_experimental') params.put('LKASButtonControl', 5, block=True) owner.sample(sm, cp, planner, now_mono_ns=later + 2_000_000, now_boot_ns=BOOT + 102_000_000, sample_skew_ns=1000, drive_id=MONO, manual_event=receipt(2, later, fingerprint)) + assert owner.manual_state is not None self.assertEqual(owner.manual_state.intent.value, 'force_experimental') # Denied receipt cannot rearm. def test_actual_mpc_headway_settings_and_model_lane_join_without_manual_owner(self): @@ -525,12 +535,15 @@ class TestConditionalRuntimeLoop(unittest.TestCase): proposal, snapshot = owner.sample(sm, cp, planner, now_mono_ns=event + 1_000_000, now_boot_ns=BOOT + index * 50_000_000 + 1_000_000, sample_skew_ns=1000, drive_id=MONO) + assert snapshot is not None self.assertEqual(proposal.settings_revision, snapshot.revision) + assert proposal.projected is not None self.assertEqual(proposal.projected.scene.lane_available, False if index == 4 else None) self.assertTrue(proposal.override_experimental) # Explicit nonpersistent saved choice starts at NONE. status = owner.status.attach(None, proposal, snapshot, now_ns=event + 1_000_000, drive_id=MONO, model_ns=event, car_state_ns=event) observed = messaging.log_from_bytes(status.to_bytes()).slcState.conditionalMode + assert snapshot is not None self.assertEqual(observed.settingsRevision, snapshot.revision) self.assertTrue(observed.hasOverride) self.assertEqual(str(observed.status), 'proposed') diff --git a/openpilot/selfdrive/controls/tests/test_longitudinal_plan_validity.py b/openpilot/selfdrive/controls/tests/test_longitudinal_plan_validity.py index 479e3d89eb..22dd0d1d68 100644 --- a/openpilot/selfdrive/controls/tests/test_longitudinal_plan_validity.py +++ b/openpilot/selfdrive/controls/tests/test_longitudinal_plan_validity.py @@ -56,9 +56,13 @@ class LongitudinalPlanValidityTest(unittest.TestCase): side_effect=lambda service, plan=plan, new_message=new_message: ( plan if service == 'longitudinalPlan' else new_message(service))): planner.publish(sources, published) + assert published.message is not None self.assertEqual(published.message.longitudinalPlan.modelMonoTime, sources.logMonoTime['modelV2']) + assert published.message is not None self.assertAlmostEqual(published.message.longitudinalPlan.processingDelay, delay_ns / 1e9, places=8) + assert published.companion is not None self.assertEqual(published.companion.logMonoTime, plan.logMonoTime) + assert published.companion is not None self.assertEqual(published.companion.starpilotLongitudinalPlan.sourcePlanMonoTime, plan.logMonoTime) def test_optional_vision_frequency_and_dashboard_absence_do_not_invalidate_native_plan(self): @@ -73,13 +77,16 @@ class LongitudinalPlanValidityTest(unittest.TestCase): published = Capture() planner.publish(sources, published) + assert published.message is not None self.assertTrue(published.message.valid) + assert published.message is not None self.assertEqual(published.message.which(), 'longitudinalPlan') for required in NATIVE_PLAN_INPUTS: with self.subTest(required=required): sources.valid[required] = False planner.publish(sources, published) + assert published.message is not None self.assertFalse(published.message.valid) sources.valid[required] = True diff --git a/openpilot/selfdrive/controls/tests/test_voacc.py b/openpilot/selfdrive/controls/tests/test_voacc.py index 1902112535..3b86b5c699 100644 --- a/openpilot/selfdrive/controls/tests/test_voacc.py +++ b/openpilot/selfdrive/controls/tests/test_voacc.py @@ -7,6 +7,7 @@ import tempfile import unittest from unittest.mock import Mock, patch +from openpilot.common.test import require_value from openpilot.selfdrive.controls import radard from openpilot.selfdrive.controls.radard import RadarD from openpilot.selfdrive.controls.tests.test_adjacent_radar_transport import Captured, MONO, Sources @@ -31,9 +32,11 @@ class VoaccTest(unittest.TestCase): normal, vision = RadarD(), RadarD(use_voacc=True) normal.update(source, source['radarTracks']) vision.update(source, source['radarTracks']) + assert normal.radar_state is not None self.assertTrue(normal.radar_state.leadOne.radar) + assert normal.radar_state is not None self.assertEqual(normal.radar_state.leadOne.dRel, 5.) - for lead in (vision.radar_state.leadOne, vision.radar_state.leadTwo): + for lead in (require_value(vision.radar_state).leadOne, require_value(vision.radar_state).leadTwo): self.assertTrue(lead.present) self.assertFalse(lead.radar) self.assertEqual(lead.radarTrackId, -1) @@ -45,7 +48,9 @@ class VoaccTest(unittest.TestCase): source = self.source(vision=False) radar = RadarD(use_voacc=True) radar.update(source, source['radarTracks']) + assert radar.radar_state is not None self.assertFalse(radar.radar_state.leadOne.present) + assert radar.radar_state is not None self.assertFalse(radar.radar_state.leadTwo.present) def test_radar_errors_and_message_validity_are_preserved(self): @@ -70,6 +75,7 @@ class VoaccTest(unittest.TestCase): radar.update(source, source['radarTracks']) policy.update_tracks.assert_called_once_with(source, source['radarTracks'], radar) policy.leads.assert_not_called() + assert radar.radar_state is not None self.assertFalse(radar.radar_state.leadOne.radar) def test_default_off_keeps_normal_output(self): @@ -77,6 +83,8 @@ class VoaccTest(unittest.TestCase): default, disabled = RadarD(), RadarD(use_voacc=False) default.update(source, source['radarTracks']) disabled.update(source, source['radarTracks']) + assert default.radar_state is not None + assert disabled.radar_state is not None self.assertEqual(default.radar_state.to_dict(), disabled.radar_state.to_dict()) def test_main_latches_setting_until_next_drive(self): diff --git a/openpilot/selfdrive/locationd/models/car_kf.py b/openpilot/selfdrive/locationd/models/car_kf.py index 27cc4ef9c9..bb4d16f288 100755 --- a/openpilot/selfdrive/locationd/models/car_kf.py +++ b/openpilot/selfdrive/locationd/models/car_kf.py @@ -167,12 +167,15 @@ class CarKalman(KalmanFilter): dim_state, dim_state_err, global_vars=CarKalman.global_vars, logger=cloudlog) def set_globals(self, mass, rotational_inertia, center_to_front, center_to_rear, stiffness_front, stiffness_rear): - self.filter.set_global("mass", mass) - self.filter.set_global("rotational_inertia", rotational_inertia) - self.filter.set_global("center_to_front", center_to_front) - self.filter.set_global("center_to_rear", center_to_rear) - self.filter.set_global("stiffness_front", stiffness_front) - self.filter.set_global("stiffness_rear", stiffness_rear) + filter_ = self.filter + if filter_ is None: + raise RuntimeError("Car Kalman filter unavailable") + filter_.set_global("mass", mass) + filter_.set_global("rotational_inertia", rotational_inertia) + filter_.set_global("center_to_front", center_to_front) + filter_.set_global("center_to_rear", center_to_rear) + filter_.set_global("stiffness_front", stiffness_front) + filter_.set_global("stiffness_rear", stiffness_rear) if __name__ == "__main__": diff --git a/openpilot/selfdrive/locationd/paramsd.py b/openpilot/selfdrive/locationd/paramsd.py index 81fa68996c..2315451191 100755 --- a/openpilot/selfdrive/locationd/paramsd.py +++ b/openpilot/selfdrive/locationd/paramsd.py @@ -128,10 +128,11 @@ class VehicleParamsLearner: self.kf.predict_and_observe(t, ObservationKind.STEER_ANGLE, np.array([[np.radians(steering_angle)]])) self.kf.predict_and_observe(t, ObservationKind.ROAD_FRAME_X_SPEED, np.array([[self.observed_speed]])) - if not self.active: + filter_ = self.kf.filter + if not self.active and filter_ is not None: # Reset time when stopped so uncertainty doesn't grow - self.kf.filter.set_filter_time(t) - self.kf.filter.reset_rewind() + filter_.set_filter_time(t) + filter_.reset_rewind() def get_msg(self, valid: bool, debug: bool = False) -> capnp._DynamicStructBuilder: x = self.kf.x diff --git a/openpilot/selfdrive/selfdrived/helpers.py b/openpilot/selfdrive/selfdrived/helpers.py index 195ef3b171..730ccb13d2 100644 --- a/openpilot/selfdrive/selfdrived/helpers.py +++ b/openpilot/selfdrive/selfdrived/helpers.py @@ -148,8 +148,8 @@ def update_jetlink_swaps(owner, in_control, state=None): owner._jetlink_runtime_ticks = (ticks + 1) % max(round(.2 / DT_CTRL), 1) runtime = getattr(owner, '_jetlink_runtime', None) runtime_valid = getattr(owner, '_jetlink_runtime_valid', False) - state = runtime.state if runtime_valid else 'none' - if model_ok and big and runtime_valid and runtime.state == 'running' and runtime.active: + state = runtime.state if runtime_valid and runtime is not None else 'none' + if model_ok and big and runtime_valid and runtime is not None and state == 'running' and runtime.active: owner._jetlink_model_provenance = True model_ok = model_ok and runtime_valid swap = owner.jetlink_swaps.update(model_ok, big, in_control, state=state) diff --git a/openpilot/selfdrive/test/helpers.py b/openpilot/selfdrive/test/helpers.py index 70b96cf35f..b9926468f7 100644 --- a/openpilot/selfdrive/test/helpers.py +++ b/openpilot/selfdrive/test/helpers.py @@ -84,12 +84,13 @@ def processes_context(processes, init_time=0, ignore_stopped=None): if n < len(processes) - 1: time.sleep(init_time) - assert all(managed_processes[name].proc.exitcode is None for name in processes) + procs = [managed_processes[name] for name in processes] + assert all(p.proc is not None and p.proc.exitcode is None for p in procs) try: - yield [managed_processes[name] for name in processes] + yield procs # assert processes are still started - assert all(managed_processes[name].proc.exitcode is None for name in processes if name not in ignore_stopped) + assert all(p.proc is not None and p.proc.exitcode is None for p in procs if p.name not in ignore_stopped) finally: for p in processes: managed_processes[p].stop() diff --git a/openpilot/selfdrive/test/process_replay/process_replay.py b/openpilot/selfdrive/test/process_replay/process_replay.py index a53dc95047..da0ccda50a 100755 --- a/openpilot/selfdrive/test/process_replay/process_replay.py +++ b/openpilot/selfdrive/test/process_replay/process_replay.py @@ -26,7 +26,7 @@ from openpilot.starpilot.schema_cache import CACHE_KEYS, get_cache, inspect_cach from openpilot.common.prefix import OpenpilotPrefix from openpilot.common.timeout import Timeout from openpilot.system.camerad.cameras.nv12_info import get_nv12_info -from openpilot.system.manager.process import PythonProcess, launcher as launch_python_process +from openpilot.system.manager.process import DaemonProcess, PythonProcess, launcher as launch_python_process from openpilot.system.manager.process_config import managed_processes from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_camera_state, available_streams from openpilot.selfdrive.test.process_replay.capture import ProcessOutputCapture @@ -176,7 +176,7 @@ class ProcessContainer: return self.cfg.subs def _clean_env(self): - for k in self.environ_config.keys(): + for k in self.environ_config or {}: if k in os.environ: del os.environ[k] @@ -229,6 +229,8 @@ class ProcessContainer: assert isinstance(self.process, PythonProcess) self.process.launcher = _launch_selfdrived_replay if self.capture is not None: + if isinstance(self.process, DaemonProcess): + raise ValueError("Capture requires a managed replay process") self.process.launcher = LauncherWithCapture(self.capture, self.process.launcher) # ty: ignore[invalid-assignment] # intentional wrapper self.process.start() @@ -268,6 +270,7 @@ class ProcessContainer: with self.prefix: self.process.signal(signal.SIGKILL) self.process.stop() + assert self.rc is not None self.rc.close_context() self.prefix.clean_dirs() self._clean_env() diff --git a/openpilot/selfdrive/test/test_onroad.py b/openpilot/selfdrive/test/test_onroad.py index ac869392b3..b445e67d39 100755 --- a/openpilot/selfdrive/test/test_onroad.py +++ b/openpilot/selfdrive/test/test_onroad.py @@ -20,7 +20,7 @@ from openpilot.cereal.services import SERVICE_LIST from openpilot.common.basedir import BASEDIR from openpilot.common.timeout import Timeout from openpilot.common.params import Params -from openpilot.selfdrive.selfdrived.events import EVENTS, ET +from openpilot.selfdrive.selfdrived.events import Alert, EVENTS, ET from openpilot.selfdrive.test.helpers import set_params_enabled, release_only, processes_context, log_collector from openpilot.common.hardware import HARDWARE from openpilot.common.hardware.hw import Paths @@ -451,7 +451,9 @@ class TestOnroad(OpenpilotTestCase): @release_only def test_startup(self): startup_alert = self.ts['selfdriveState']['alertText1'][0] - expected = EVENTS[log.OnroadEvent.EventName.startup][ET.PERMANENT].alert_text_1 + startup = EVENTS[log.OnroadEvent.EventName.startup][ET.PERMANENT] + assert isinstance(startup, Alert) + expected = startup.alert_text_1 assert startup_alert == expected, "wrong startup alert" def test_engagable(self): diff --git a/openpilot/selfdrive/ui/layouts/arabesque/tools/browser_session.py b/openpilot/selfdrive/ui/layouts/arabesque/tools/browser_session.py index 4c3e1abc40..4209c50cac 100644 --- a/openpilot/selfdrive/ui/layouts/arabesque/tools/browser_session.py +++ b/openpilot/selfdrive/ui/layouts/arabesque/tools/browser_session.py @@ -320,10 +320,13 @@ class BrowserSession: self._job_closing = False packet(self._socket, {'type': 'job_done'}) if self._socket is None: + listener, launcher = self._listener, self._launcher + if listener is None or launcher is None: + raise RuntimeError('Firefox launch resources unavailable') try: - peer, _ = self._listener.accept() + peer, _ = listener.accept() except BlockingIOError: - if now - self._started > 12 or self._launcher.poll() not in (None, 0): + if now - self._started > 12 or launcher.poll() not in (None, 0): raise RuntimeError('Isolated Firefox could not start; check the transient unit journal') from None return if credentials(peer)[1] != (0 if self._preparing else BROWSER_UID): @@ -340,7 +343,7 @@ class BrowserSession: if self._lock_fd is not None: os.close(self._lock_fd) self._lock_fd = None - self._listener.close() + listener.close() self._listener = None if (not self._preparing and not maintenance and (not self.ready or self._operation == 'qualify' and not self._uploaded) and now - self._started > 45): diff --git a/openpilot/selfdrive/ui/layouts/onboarding.py b/openpilot/selfdrive/ui/layouts/onboarding.py index a1f1d0f039..6949d8bfda 100644 --- a/openpilot/selfdrive/ui/layouts/onboarding.py +++ b/openpilot/selfdrive/ui/layouts/onboarding.py @@ -6,7 +6,7 @@ from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.button import Button, ButtonStyle from openpilot.system.ui.widgets.label import Label -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ui_state, live_params from openpilot.selfdrive.ui.layouts.training_guide import TrainingGuide from openpilot.common.version import terms_version, training_version @@ -67,7 +67,7 @@ class DeclinePage(Widget): click_callback=self._on_uninstall_clicked) def _on_uninstall_clicked(self): - ui_state.params.put_bool("DoUninstall", True, block=True) + live_params(ui_state.params).put_bool("DoUninstall", True, block=True) gui_app.request_close() def _render(self, _): @@ -108,13 +108,13 @@ class OnboardingWindow(Widget): self._state = OnboardingState.TERMS def _on_terms_accepted(self): - ui_state.params.put("HasAcceptedTerms", terms_version, block=True) + live_params(ui_state.params).put("HasAcceptedTerms", terms_version, block=True) self._state = OnboardingState.ONBOARDING if self._training_done: gui_app.pop_widget() def _on_completed_training(self): - ui_state.params.put("CompletedTrainingVersion", training_version, block=True) + live_params(ui_state.params).put("CompletedTrainingVersion", training_version, block=True) def _render(self, _): if self._state == OnboardingState.TERMS: diff --git a/openpilot/selfdrive/ui/layouts/settings/common.py b/openpilot/selfdrive/ui/layouts/settings/common.py index bba8606e64..5aeec443ee 100644 --- a/openpilot/selfdrive/ui/layouts/settings/common.py +++ b/openpilot/selfdrive/ui/layouts/settings/common.py @@ -1,5 +1,5 @@ -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ui_state, live_params def restart_needed_callback(_=None): - ui_state.params.put_bool("OnroadCycleRequested", True) + live_params(ui_state.params).put_bool("OnroadCycleRequested", True) diff --git a/openpilot/selfdrive/ui/layouts/settings/firehose.py b/openpilot/selfdrive/ui/layouts/settings/firehose.py index 1898af2a72..80471c90a7 100644 --- a/openpilot/selfdrive/ui/layouts/settings/firehose.py +++ b/openpilot/selfdrive/ui/layouts/settings/firehose.py @@ -81,7 +81,8 @@ class FirehoseLayout(FirehoseLayoutBase): y = self._draw_wrapped_text(x, y, w, tr(INSTRUCTIONS), gui_app.font(FontWeight.NORMAL), 40, self.LIGHT_GRAY) # bottom margin + remove effect of scroll offset - return int(round(y - self._scroll_panel.offset + 40)) + scroll_panel = self._scroll_panel + return int(round(y - (scroll_panel.offset if isinstance(scroll_panel, GuiScrollPanel) else 0) + 40)) def _draw_wrapped_text(self, x, y, width, text, font, font_size, color): wrapped = wrap_text(font, text, font_size, width) diff --git a/openpilot/selfdrive/ui/layouts/settings/initial_cruise_speed.py b/openpilot/selfdrive/ui/layouts/settings/initial_cruise_speed.py index c31a18b72a..82a7d8e0a1 100644 --- a/openpilot/selfdrive/ui/layouts/settings/initial_cruise_speed.py +++ b/openpilot/selfdrive/ui/layouts/settings/initial_cruise_speed.py @@ -3,7 +3,7 @@ from openpilot.starpilot.ui.raylib import rl from openpilot.common.constants import CV from openpilot.selfdrive.car.cruise import V_CRUISE_INITIAL, V_CRUISE_MAX, validated_initial_cruise_speed -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ui_state, live_params from openpilot.system.ui.lib.application import FontWeight, TextAlignment from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.widgets.button import Button, ButtonStyle @@ -31,7 +31,7 @@ def get_speed_options() -> tuple[list[int], int]: def set_initial_cruise_speed(speed: int) -> None: """Save an initial cruise speed in display units""" - ui_state.params.put("InitialCruiseSpeedKph", round(speed / _speed_conversion()), block=True) + live_params(ui_state.params).put("InitialCruiseSpeedKph", round(speed / _speed_conversion()), block=True) ui_state.update_params() diff --git a/openpilot/selfdrive/ui/layouts/settings/software.py b/openpilot/selfdrive/ui/layouts/settings/software.py index 5daa745d86..b0c0c03f14 100644 --- a/openpilot/selfdrive/ui/layouts/settings/software.py +++ b/openpilot/selfdrive/ui/layouts/settings/software.py @@ -4,7 +4,7 @@ import datetime from pathlib import Path from collections.abc import Callable from openpilot.common.time_helpers import system_time_valid -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ui_state, live_params from openpilot.starpilot.software.preferences import AUTOMATIC_DOWNLOADS, automatic_downloads from openpilot.starpilot.ui.brand import home_description from openpilot.system.ui.lib.application import gui_app @@ -56,7 +56,7 @@ class SoftwareLayout(Widget): def __init__(self): super().__init__() - self._onroad_label = ListItem(lambda: tr("Updates are only downloaded while the car is off.")) + self._onroad_label = ListItem(lambda: tr("Updates are only downloaded while the car is off."), action_item=None) self._version_item = text_item(lambda: tr("Current Version"), home_description(ui_state.params.get("UpdaterCurrentDescription") or "")) self._auto_updates_toggle = toggle_item( lambda: tr("Automatically Download Updates"), @@ -223,14 +223,14 @@ class SoftwareLayout(Widget): return def handle_uninstall_confirmation(result: DialogResult): if result == DialogResult.CONFIRM and ui_state.is_offroad() and (action_guard is None or action_guard()): - ui_state.params.put_bool("DoUninstall", True, block=True) + live_params(ui_state.params).put_bool("DoUninstall", True, block=True) dialog = ConfirmDialog(tr("Are you sure you want to uninstall?"), tr("Uninstall"), callback=handle_uninstall_confirmation) gui_app.push_widget(dialog) def _on_auto_updates_toggle(self, enabled: bool): if ui_state.is_offroad(): - ui_state.params.put_bool(AUTOMATIC_DOWNLOADS, enabled, block=True) + live_params(ui_state.params).put_bool(AUTOMATIC_DOWNLOADS, enabled, block=True) def _on_error_log(self): error = ui_state.params.get("LastUpdateException") or "" @@ -250,7 +250,7 @@ class SoftwareLayout(Widget): return # Trigger reboot to install update self._install_btn.action_item.set_enabled(False) - ui_state.params.put_bool("DoReboot", True, block=True) + live_params(ui_state.params).put_bool("DoReboot", True, block=True) def _on_select_branch(self, action_guard: Callable[[], bool] | None = None): if not ui_state.is_offroad() or ui_state.params.get_bool("IsTestedBranch"): @@ -276,7 +276,7 @@ class SoftwareLayout(Widget): self._branch_dialog is not None and self._branch_dialog.selection in branches and (action_guard is None or action_guard())): selection = self._branch_dialog.selection - ui_state.params.put("UpdaterTargetBranch", selection, block=True) + live_params(ui_state.params).put("UpdaterTargetBranch", selection, block=True) self._branch_btn.action_item.set_value(selection) self._download_btn.action_item.set_enabled(False) self._waiting_for_updater = True diff --git a/openpilot/selfdrive/ui/layouts/settings/toggles.py b/openpilot/selfdrive/ui/layouts/settings/toggles.py index 3a6bcd711b..15d94b3e27 100644 --- a/openpilot/selfdrive/ui/layouts/settings/toggles.py +++ b/openpilot/selfdrive/ui/layouts/settings/toggles.py @@ -3,7 +3,7 @@ from openpilot.starpilot.car.ford.longitudinal_preferences import release_long_a from openpilot.cereal import log from openpilot.common.params import Params, UnknownKeyName from openpilot.system.ui.widgets import Widget -from openpilot.system.ui.widgets.list_view import ListItem, multiple_button_item, toggle_item +from openpilot.system.ui.widgets.list_view import ListItem, ToggleAction, multiple_button_item, toggle_item from openpilot.system.ui.widgets.scroller_tici import Scroller from openpilot.system.ui.lib.multilang import tr, tr_noop from openpilot.selfdrive.ui.ui_state import ui_state @@ -213,7 +213,7 @@ class TogglesLayout(Widget): # TODO: make a param control list item so we don't need to manage internal state as much here # refresh toggles from params to mirror external changes for param in self._toggle_defs: - self._toggles[param].action_item.set_state(self._params.get_bool(param)) + self._toggle_action(param).set_state(self._params.get_bool(param)) self._metric_source = self._slc_offsets._raw("IsMetric") # these toggles need restart, block while engaged @@ -227,8 +227,13 @@ class TogglesLayout(Widget): def _render(self, rect): self._scroller.render(rect) + def _toggle_action(self, param: str) -> ToggleAction: + action = self._toggles[param].action_item + assert isinstance(action, ToggleAction) + return action + def _update_experimental_mode_icon(self): - icon = "experimental.png" if self._toggles["ExperimentalMode"].action_item.get_state() else "experimental_white.png" + icon = "experimental.png" if self._toggle_action("ExperimentalMode").get_state() else "experimental_white.png" self._toggles["ExperimentalMode"].set_icon(icon) @@ -239,12 +244,12 @@ class TogglesLayout(Widget): return ok if param == "IsMetric": ok = self._slc_offsets.change_units(state, self._metric_source) - self._toggles[param].action_item.set_state(self._params.get_bool(param)) + self._toggle_action(param).set_state(self._params.get_bool(param)) self._metric_source = self._slc_offsets._raw("IsMetric") self._update_toggles() return ok self._params.put_bool(param, state, block=True) - self._toggles[param].action_item.set_state(state) + self._toggle_action(param).set_state(state) if param == "ExperimentalMode": self._update_experimental_mode_icon() if self._toggle_defs[param][3]: diff --git a/openpilot/selfdrive/ui/layouts/training_guide.py b/openpilot/selfdrive/ui/layouts/training_guide.py index 754b3bf022..d15751c712 100644 --- a/openpilot/selfdrive/ui/layouts/training_guide.py +++ b/openpilot/selfdrive/ui/layouts/training_guide.py @@ -15,7 +15,7 @@ from openpilot.selfdrive.ui.onroad.alert_renderer import (ALERT_BORDER_RADIUS, A ALERT_LINE_SPACING, ALERT_MARGIN, ALERT_PADDING, AlertSize, AlertStatus) from openpilot.selfdrive.ui.onroad.augmented_road_view import BORDER_COLORS from openpilot.selfdrive.ui.onroad.hud_renderer import COLORS, FONT_SIZES, UI_CONFIG -from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus, live_params ASSETS = "training" MARGIN = 112 @@ -573,7 +573,7 @@ class TrainingGuide(Widget): self._step = 0 def _record_front(self, record: bool): - ui_state.params.put_bool("RecordFront", record, block=True) + live_params(ui_state.params).put_bool("RecordFront", record, block=True) self._next() def _render(self, rect: rl.Rectangle): diff --git a/openpilot/selfdrive/ui/mici/layouts/home.py b/openpilot/selfdrive/ui/mici/layouts/home.py index 7ab616b40e..79c8b267d9 100644 --- a/openpilot/selfdrive/ui/mici/layouts/home.py +++ b/openpilot/selfdrive/ui/mici/layouts/home.py @@ -13,7 +13,7 @@ from openpilot.system.ui.widgets.layouts import HBoxLayout from openpilot.system.ui.widgets.icon_widget import IconWidget from openpilot.system.ui.widgets.label import UnifiedLabel, gui_label from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos, TextAlignment, TextAlignmentVertical -from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState +from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState, live_params from openpilot.common.version import RELEASE_BRANCHES HEAD_BUTTON_FONT_SIZE = 40 @@ -176,7 +176,7 @@ class MiciHomeLayout(Widget): # long gating for experimental mode - only allow toggle if longitudinal control is available if ui_state.has_longitudinal_control: ui_state.experimental_mode = not ui_state.experimental_mode - ui_state.params.put("ExperimentalMode", ui_state.experimental_mode, block=True) + live_params(ui_state.params).put("ExperimentalMode", ui_state.experimental_mode, block=True) self._mouse_down_t = None self._did_long_press = True diff --git a/openpilot/selfdrive/ui/mici/layouts/onboarding.py b/openpilot/selfdrive/ui/mici/layouts/onboarding.py index ea5471796c..e520fe7fc6 100644 --- a/openpilot/selfdrive/ui/mici/layouts/onboarding.py +++ b/openpilot/selfdrive/ui/mici/layouts/onboarding.py @@ -13,7 +13,7 @@ from openpilot.selfdrive.ui.mici.widgets.button import GreyBigButton, BigPillBut from openpilot.system.ui.widgets.label import gui_label from openpilot.system.ui.lib.multilang import tr from openpilot.common.version import terms_version, training_version -from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.selfdrive.ui.ui_state import ui_state, device, live_params from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationCircleButton from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer from openpilot.selfdrive.ui.mici.onroad.cabin_camera_dialog import BaseCabinCameraDialog @@ -69,7 +69,7 @@ class TrainingGuidePreDMTutorial(NavScroller): def show_event(self): super().show_event() # Get driver monitoring model ready for next step - ui_state.params.put_bool("IsDriverViewEnabled", True) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", True) class DMBadFaceDetected(NavScroller): @@ -109,7 +109,7 @@ class TrainingGuideDMTutorial(NavWidget): # Disable driver monitoring model when device times out for inactivity def inactivity_callback(): - ui_state.params.put_bool("IsDriverViewEnabled", False) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", False) device.add_interactive_timeout_callback(inactivity_callback) @@ -121,7 +121,7 @@ class TrainingGuideDMTutorial(NavWidget): def _update_state(self): super()._update_state() if device.awake and not ui_state.params.get_bool("IsDriverViewEnabled"): - ui_state.params.put_bool("IsDriverViewEnabled", True) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", True) if not ui_state.received_since_started("driverMonitoringState"): return @@ -216,11 +216,11 @@ class TrainingGuideRecordFront(NavScroller): super().__init__() def on_accept(): - ui_state.params.put_bool("RecordFront", True) + live_params(ui_state.params).put_bool("RecordFront", True) continue_callback() def on_decline(): - ui_state.params.put_bool("RecordFront", False) + live_params(ui_state.params).put_bool("RecordFront", False) continue_callback() self._accept_button = BigConfirmationCircleButton("allow data uploading", gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64), @@ -317,7 +317,7 @@ class OnboardingWindow(Widget): self._training_guide.set_enabled(lambda: self.enabled) # for nav stack def _on_uninstall(self): - ui_state.params.put_bool("DoUninstall", True, block=True) + live_params(ui_state.params).put_bool("DoUninstall", True, block=True) def show_event(self): super().show_event() @@ -335,15 +335,15 @@ class OnboardingWindow(Widget): return self._accepted_terms and self._training_done def close(self): - ui_state.params.put_bool("IsDriverViewEnabled", False) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", False) self._completed_callback() def _on_terms_accepted(self): - ui_state.params.put("HasAcceptedTerms", terms_version, block=True) + live_params(ui_state.params).put("HasAcceptedTerms", terms_version, block=True) gui_app.push_widget(self._training_guide) def _on_completed_training(self): - ui_state.params.put("CompletedTrainingVersion", training_version, block=True) + live_params(ui_state.params).put("CompletedTrainingVersion", training_version, block=True) self.close() def _render(self, _): diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/developer.py b/openpilot/selfdrive/ui/mici/layouts/settings/developer.py index a681ef9ebb..b2f6b2e85c 100644 --- a/openpilot/selfdrive/ui/mici/layouts/settings/developer.py +++ b/openpilot/selfdrive/ui/mici/layouts/settings/developer.py @@ -7,7 +7,7 @@ from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigToggle, Big from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigInputDialog, BigConfirmationCircleButton from openpilot.system.ui.lib.application import gui_app from openpilot.selfdrive.ui.layouts.settings.common import restart_needed_callback -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ui_state, live_params from openpilot.starpilot.car.hyundai.aol import ioniq6_alpha_long_available from openpilot.starpilot.car.ford.longitudinal_preferences import release_long_available as ford_release_long_available from opendbc.car.volkswagen.meb_modes import MEB_CARS, settings_capable as meb_settings_capable @@ -199,13 +199,13 @@ class DeveloperLayoutMici(NavScroller): def _on_always_hold(self, state: bool): if ui_state.is_offroad(): - ui_state.params.put_bool(HOLD_KEY, state, block=True) + live_params(ui_state.params).put_bool(HOLD_KEY, state, block=True) self._always_hold_toggle.set_checked(ui_state.params.get_bool(HOLD_KEY)) def _on_joystick_debug_mode(self, state: bool): - ui_state.params.put_bool("JoystickDebugMode", state, block=True) - ui_state.params.put_bool("LongitudinalManeuverMode", False, block=True) - ui_state.params.put_bool("LateralManeuverMode", False, block=True) + live_params(ui_state.params).put_bool("JoystickDebugMode", state, block=True) + live_params(ui_state.params).put_bool("LongitudinalManeuverMode", False, block=True) + live_params(ui_state.params).put_bool("LateralManeuverMode", False, block=True) def _on_alpha_long_enabled(self, state: bool): def do_toggle(_state: bool): @@ -215,7 +215,7 @@ class DeveloperLayoutMici(NavScroller): ui_state.is_release and not (meb_settings_capable(ui_state.CP) or ford_release_long_available(ui_state.CP))))): self._update_toggles() return - ui_state.params.put_bool("AlphaLongitudinalEnabled", _state, block=True) + live_params(ui_state.params).put_bool("AlphaLongitudinalEnabled", _state, block=True) restart_needed_callback() self._update_toggles() diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/device/device_layout.py b/openpilot/selfdrive/ui/mici/layouts/settings/device/device_layout.py index 6bdf020eb3..03349e905e 100644 --- a/openpilot/selfdrive/ui/mici/layouts/settings/device/device_layout.py +++ b/openpilot/selfdrive/ui/mici/layouts/settings/device/device_layout.py @@ -15,7 +15,7 @@ from openpilot.selfdrive.ui.mici.onroad.cabin_camera_dialog import CabinCameraDi from openpilot.selfdrive.ui.mici.layouts.onboarding import TrainingGuide, TermsPage from openpilot.system.ui.lib.application import gui_app, MousePos from openpilot.system.ui.lib.multilang import tr -from openpilot.selfdrive.ui.ui_state import device, ui_state +from openpilot.selfdrive.ui.ui_state import ProjectionPrimeState, device, ui_state, live_params from openpilot.starpilot.ui.slc_offset_feature import native_parked from openpilot.starpilot.ui.calibration_reset import calibration_reset from openpilot.system.ui.widgets.html_render import HtmlRenderer @@ -40,7 +40,7 @@ class ReviewTrainingGuide(TrainingGuide): def hide_event(self): super().hide_event() device.set_override_interactive_timeout(None) - ui_state.params.put_bool("IsDriverViewEnabled", False) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", False) class MiciFccModal(NavRawScrollPanel): @@ -110,15 +110,19 @@ class PairBigButton(BigButton): def _update_state(self): super()._update_state() - self._show_commacare = (ui_state.prime_state.is_paired() and ui_state.prime_state.is_prime() - and ui_state.prime_state.has_commacare()) - if ui_state.prime_state.is_paired(): - self.set_icon(self._provider_icons.get(ui_state.prime_state.get_pairing_provider(), self._comma_icon)) + prime_state = ui_state.prime_state + if isinstance(prime_state, ProjectionPrimeState): + self._show_commacare = False + return + self._show_commacare = (prime_state.is_paired() and prime_state.is_prime() + and prime_state.has_commacare()) + if prime_state.is_paired(): + self.set_icon(self._provider_icons.get(prime_state.get_pairing_provider(), self._comma_icon)) self.set_text("paired") - if ui_state.prime_state.is_prime(): - self.set_value("prime" if ui_state.prime_state.is_full_prime() else "prime lite") + if prime_state.is_prime(): + self.set_value("prime" if prime_state.is_full_prime() else "prime lite") else: - self.set_value("claim prime trial" if ui_state.prime_state.can_claim_prime_trial() else "upgrade to prime") + self.set_value("claim prime trial" if prime_state.can_claim_prime_trial() else "upgrade to prime") else: self.set_icon(self._comma_icon) self.set_text("pair to connect") @@ -154,10 +158,10 @@ class DeviceLayoutMici(NavScroller): self._pending_pairing_grow_animation = False def power_off_callback(): - ui_state.params.put_bool("DoShutdown", True, block=True) + live_params(ui_state.params).put_bool("DoShutdown", True, block=True) def reboot_callback(): - ui_state.params.put_bool("DoReboot", True, block=True) + live_params(ui_state.params).put_bool("DoReboot", True, block=True) reset_calibration_btn = EngagedConfirmationButton("reset calibration", "reset", gui_app.texture("icons_mici/settings/device/lkas.png", 122, 64), self._reset_calibration, @@ -218,8 +222,8 @@ class DeviceLayoutMici(NavScroller): def _reset_driver_monitoring(self) -> None: if not self._can_reset_driver_monitoring(): return - ui_state.params.remove("IsRhdDetected") - ui_state.params.put_bool("OnroadCycleRequested", True, block=True) + live_params(ui_state.params).remove("IsRhdDetected") + live_params(ui_state.params).put_bool("OnroadCycleRequested", True, block=True) def _update_state(self): super()._update_state() diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/device/prime.py b/openpilot/selfdrive/ui/mici/layouts/settings/device/prime.py index 99487e878c..178d12a010 100644 --- a/openpilot/selfdrive/ui/mici/layouts/settings/device/prime.py +++ b/openpilot/selfdrive/ui/mici/layouts/settings/device/prime.py @@ -8,7 +8,7 @@ from openpilot.common.params import Params from openpilot.selfdrive.ui.mici.widgets.button import BigButton, GreyBigButton from openpilot.selfdrive.ui.mici.widgets.info import InfoLayoutMici from openpilot.selfdrive.ui.mici.widgets.qr import QR -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ProjectionPrimeState, ui_state from openpilot.system.ui.lib.application import gui_app from openpilot.system.ui.widgets.scroller import NavScroller @@ -22,17 +22,23 @@ class PairingInfoLayout(InfoLayoutMici): def _update_state(self): super()._update_state() - self.subtext1.set_text(ui_state.prime_state.get_pairing_account()) + prime_state = ui_state.prime_state + if isinstance(prime_state, ProjectionPrimeState): + self._provider_icon = None + self._show_commacare = False + return + self.subtext1.set_text(prime_state.get_pairing_account()) self.subtext2.set_text(self._get_prime_status()) - self._provider_icon = self._provider_icons.get(ui_state.prime_state.get_pairing_provider()) - self._show_commacare = active_provider().name == 'comma' and ui_state.prime_state.has_commacare() + self._provider_icon = self._provider_icons.get(prime_state.get_pairing_provider()) + self._show_commacare = active_provider().name == 'comma' and prime_state.has_commacare() @staticmethod def _get_prime_status() -> str: if active_provider().name != 'comma': return active_provider().label - if ui_state.prime_state.is_prime(): - return "prime" if ui_state.prime_state.is_full_prime() else "prime lite" + prime_state = ui_state.prime_state + if not isinstance(prime_state, ProjectionPrimeState) and prime_state.is_prime(): + return "prime" if prime_state.is_full_prime() else "prime lite" return "not subscribed" def _layout(self): @@ -66,7 +72,10 @@ class PrimeManagementScroller(NavScroller): if provider.name != 'comma': self._scroller.add_widgets([GreyBigButton(provider.label, 'Cloud account and recordings'), QR(provider.web)]) return - can_claim_trial = ui_state.prime_state.can_claim_prime_trial() + prime_state = ui_state.prime_state + if isinstance(prime_state, ProjectionPrimeState): + return + can_claim_trial = prime_state.can_claim_prime_trial() self._prime_icon = gui_app.texture("icons_mici/settings/device/green_cell.png", 64, 64) self._phone_icon = gui_app.texture("icons_mici/settings/device/phone.png", 85, 64) @@ -89,7 +98,7 @@ class PrimeManagementScroller(NavScroller): self._phone_icon ), ] - self._scroller.add_widgets(self._prime_management if ui_state.prime_state.is_prime() else self._prime_adverts) + self._scroller.add_widgets(self._prime_management if prime_state.is_prime() else self._prime_adverts) def _get_prime_url(self) -> str: provider = active_provider() @@ -113,14 +122,17 @@ class PrimeScroller(NavScroller): def __init__(self): super().__init__() self._params = Params() - self.initial_is_paired = ui_state.prime_state.is_paired() + prime_state = ui_state.prime_state + if isinstance(prime_state, ProjectionPrimeState): + raise RuntimeError('Pairing requires the live device') + self.initial_is_paired = prime_state.is_paired() self._last_pairing_qr_generation = float("-inf") self._manage_icon = gui_app.texture("icons_mici/settings/comma_icon.png", 33, 60) if active_provider().name != 'comma': self._manage_prime = BigButton(f'Open {active_provider().label}', 'Cloud account and recordings', icon=self._manage_icon) - elif not ui_state.prime_state.is_prime(): - title = "claim\nprime trial" if ui_state.prime_state.can_claim_prime_trial() else "upgrade\nto prime" + elif not prime_state.is_prime(): + title = "claim\nprime trial" if prime_state.can_claim_prime_trial() else "upgrade\nto prime" self._manage_prime = BigButton(title, icon=self._manage_icon) else: self._manage_prime = BigButton("manage prime", icon=self._manage_icon) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/network/esim_ui.py b/openpilot/selfdrive/ui/mici/layouts/settings/network/esim_ui.py index e2f2ead4b8..c1f9d5514e 100644 --- a/openpilot/selfdrive/ui/mici/layouts/settings/network/esim_ui.py +++ b/openpilot/selfdrive/ui/mici/layouts/settings/network/esim_ui.py @@ -9,7 +9,7 @@ from openpilot.cereal.visionipc import VisionStreamType from openpilot.common import qrcode from openpilot.common.swaglog import cloudlog from openpilot.selfdrive.ui.mici.onroad.cabin_camera_dialog import CabinCameraView -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ui_state, live_params from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.widgets.nav_widget import NavWidget @@ -70,13 +70,13 @@ class QRScannerDialog(NavWidget): def show_event(self): super().show_event() - ui_state.params.put_bool("DisableDriverCameraIR", True) - ui_state.params.put_bool("IsDriverViewEnabled", True) + live_params(ui_state.params).put_bool("DisableDriverCameraIR", True) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", True) def hide_event(self): super().hide_event() - ui_state.params.put_bool("IsDriverViewEnabled", False) - ui_state.params.put_bool("DisableDriverCameraIR", False) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", False) + live_params(ui_state.params).put_bool("DisableDriverCameraIR", False) def __del__(self): self._camera_view.close() diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/network/network_layout.py b/openpilot/selfdrive/ui/mici/layouts/settings/network/network_layout.py index b11de6c6f0..5296f6dcc7 100644 --- a/openpilot/selfdrive/ui/mici/layouts/settings/network/network_layout.py +++ b/openpilot/selfdrive/ui/mici/layouts/settings/network/network_layout.py @@ -3,7 +3,7 @@ from openpilot.selfdrive.ui.mici.layouts.settings.network.esim_ui import EsimUI from openpilot.selfdrive.ui.mici.layouts.settings.network.wifi_ui import WifiUIMici from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigMultiToggle, BigParamControl, BigToggle from openpilot.selfdrive.ui.mici.widgets.dialog import BigInputDialog -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ProjectionPrimeState, ui_state, live_params from openpilot.system.ui.lib.application import gui_app from openpilot.system.ui.lib.cellular_manager import CellularManager from openpilot.system.ui.lib.wifi_manager import WifiManager, Network, MeteredType @@ -73,7 +73,7 @@ class NetworkLayoutMici(NavScroller): self._cellular_manager = CellularManager() self._esim_ui = EsimUI( self._cellular_manager, - lambda: not ui_state.prime_state.is_full_prime(), + self._show_cell_settings, ) self._esim_button = EsimNetworkButton(self._cellular_manager) self._esim_button.set_click_callback(lambda: gui_app.push_widget(self._esim_ui)) @@ -104,10 +104,15 @@ class NetworkLayoutMici(NavScroller): # */ ]) + @staticmethod + def _show_cell_settings() -> bool: + state = ui_state.prime_state + return not isinstance(state, ProjectionPrimeState) and not state.is_full_prime() + def _update_state(self): super()._update_state() - show_cell_settings = not ui_state.prime_state.is_full_prime() + show_cell_settings = self._show_cell_settings() self._wifi_manager.set_ipv4_forward(show_cell_settings) self._roaming_btn.set_visible(show_cell_settings) self._apn_btn.set_visible(show_cell_settings) @@ -132,9 +137,9 @@ class NetworkLayoutMici(NavScroller): def update_apn(apn: str): apn = apn.strip() if apn == "": - ui_state.params.remove("GsmApn") + live_params(ui_state.params).remove("GsmApn") else: - ui_state.params.put("GsmApn", apn) + live_params(ui_state.params).put("GsmApn", apn) current_apn = ui_state.params.get("GsmApn") or "" dlg = BigInputDialog("enter APN...", current_apn, minimum_length=0, confirm_callback=update_apn) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/software.py b/openpilot/selfdrive/ui/mici/layouts/settings/software.py index 585902064c..a007584f53 100644 --- a/openpilot/selfdrive/ui/mici/layouts/settings/software.py +++ b/openpilot/selfdrive/ui/mici/layouts/settings/software.py @@ -10,7 +10,7 @@ from openpilot.selfdrive.ui.mici.layouts.settings.device.device_layout import En from openpilot.selfdrive.ui.mici.widgets.info import InfoLayoutMici from openpilot.selfdrive.ui.mici.widgets.button import BigButton from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ui_state, live_params from openpilot.starpilot.ui.brand import DISPLAY_VERSION from openpilot.system.ui.lib.application import gui_app, MousePos from openpilot.system.ui.lib.multilang import tr @@ -205,7 +205,7 @@ class InstallUpdateButton(BigButton): self.set_enabled(False) def run(): - ui_state.params.put_bool("DoReboot", True, block=True) + live_params(ui_state.params).put_bool("DoReboot", True, block=True) threading.Thread(target=run, daemon=True).start() @@ -258,7 +258,7 @@ class TargetBranchButton(BigButton): gui_app.push_widget(BranchSelectPage(self._on_select)) def _on_select(self, branch: str): - ui_state.params.put("UpdaterTargetBranch", branch, block=True) + live_params(ui_state.params).put("UpdaterTargetBranch", branch, block=True) self.set_value(branch) self._check_update_btn.check_for_update() @@ -283,7 +283,7 @@ class SoftwareLayoutMici(NavScroller): super().__init__() def uninstall_openpilot_callback(): - ui_state.params.put_bool("DoUninstall", True, block=True) + live_params(ui_state.params).put_bool("DoUninstall", True, block=True) uninstall_openpilot_btn = EngagedConfirmationButton("uninstall openpilot", "uninstall", gui_app.texture("icons_mici/settings/device/uninstall.png", 64, 64), diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/toggles.py b/openpilot/selfdrive/ui/mici/layouts/settings/toggles.py index ab2a6a1aac..88a5d79e55 100644 --- a/openpilot/selfdrive/ui/mici/layouts/settings/toggles.py +++ b/openpilot/selfdrive/ui/mici/layouts/settings/toggles.py @@ -4,7 +4,7 @@ from openpilot.system.ui.widgets.scroller import NavScroller from openpilot.selfdrive.ui.mici.widgets.button import BigParamControl, BigMultiParamToggle, BigToggle from openpilot.system.ui.lib.application import gui_app from openpilot.selfdrive.ui.layouts.settings.common import restart_needed_callback -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ui_state, live_params from openpilot.selfdrive.ui.mici.layouts.settings.initial_cruise_speed import InitialCruiseSpeedButton from openpilot.starpilot.ui.slc_offset_feature import SlcOffsetOwner, native_parked from openpilot.starpilot.galaxy.localization_settings import LocalizationSettingsOwner @@ -124,9 +124,9 @@ class TogglesLayoutMici(NavScroller): self._personality_toggle.set_enabled(not safe_mode) if safe_mode: if ui_state.params.get_bool("ExperimentalMode"): - ui_state.params.put_bool("ExperimentalMode", False, block=True) + live_params(ui_state.params).put_bool("ExperimentalMode", False, block=True) if ui_state.params.get("LongitudinalPersonality", return_default=True) != int(log.LongitudinalPersonality.relaxed): - ui_state.params.put("LongitudinalPersonality", int(log.LongitudinalPersonality.relaxed), block=True) + live_params(ui_state.params).put("LongitudinalPersonality", int(log.LongitudinalPersonality.relaxed), block=True) self._experimental_btn.set_checked(False) self._personality_toggle.set_value("relaxed") @@ -160,8 +160,8 @@ class TogglesLayoutMici(NavScroller): def _on_record_audio(self, desired: bool) -> None: # Keep filesystem waits off the UI thread, and persist the preference before # publishing the restart request through the same Params writer queue. - ui_state.params.put_bool("RecordAudio", desired) - ui_state.params.put_bool("OnroadCycleRequested", True) + live_params(ui_state.params).put_bool("RecordAudio", desired) + live_params(ui_state.params).put_bool("OnroadCycleRequested", True) def request_personality(self, index: int) -> bool: @@ -175,6 +175,6 @@ class TogglesLayoutMici(NavScroller): if ui_state.CP is None or not ui_state.has_longitudinal_control or not self._experimental_btn.enabled: return False desired = not ui_state.sm["selfdriveState"].experimentalMode - ui_state.params.put_bool("ExperimentalMode", desired) + live_params(ui_state.params).put_bool("ExperimentalMode", desired) self._experimental_btn.set_checked(desired) return True diff --git a/openpilot/selfdrive/ui/mici/onroad/cabin_camera_dialog.py b/openpilot/selfdrive/ui/mici/onroad/cabin_camera_dialog.py index 74e6b8e7c5..440e18a93f 100644 --- a/openpilot/selfdrive/ui/mici/onroad/cabin_camera_dialog.py +++ b/openpilot/selfdrive/ui/mici/onroad/cabin_camera_dialog.py @@ -3,7 +3,7 @@ from openpilot.cereal import log, messaging from openpilot.cereal.visionipc import VisionStreamType from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer -from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.selfdrive.ui.ui_state import ui_state, device, live_params from openpilot.system.ui.lib.application import gui_app, FontWeight, TextAlignment, TextAlignmentVertical from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.widgets import Widget @@ -39,19 +39,19 @@ class BaseCabinCameraDialog(Widget): def show_event(self): super().show_event() - ui_state.params.put_bool("IsDriverViewEnabled", True) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", True) self._publish_alert_sound(None) device.set_override_interactive_timeout(300) - ui_state.params.remove("DriverTooDistracted") + live_params(ui_state.params).remove("DriverTooDistracted") self._pm = messaging.PubMaster(['selfdriveState']) def hide_event(self): super().hide_event() - ui_state.params.put_bool("IsDriverViewEnabled", False) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", False) device.set_override_interactive_timeout(None) def _handle_mouse_release(self, _): - ui_state.params.remove("DriverTooDistracted") + live_params(ui_state.params).remove("DriverTooDistracted") def __del__(self): self.close() diff --git a/openpilot/selfdrive/ui/mici/widgets/dialog.py b/openpilot/selfdrive/ui/mici/widgets/dialog.py index ff45130bdc..60f1f58d25 100644 --- a/openpilot/selfdrive/ui/mici/widgets/dialog.py +++ b/openpilot/selfdrive/ui/mici/widgets/dialog.py @@ -81,7 +81,7 @@ class BigConfirmationDialog(BigDialogBase): def _on_confirm(self): if self._exit_on_confirm: self.dismiss(self._confirm_callback) - elif self._confirm_callback: + elif self._confirm_callback is not None: self._confirm_callback() def _update_state(self): diff --git a/openpilot/selfdrive/ui/onroad/cabin_camera_dialog.py b/openpilot/selfdrive/ui/onroad/cabin_camera_dialog.py index e4d704db3b..34eafde9cc 100644 --- a/openpilot/selfdrive/ui/onroad/cabin_camera_dialog.py +++ b/openpilot/selfdrive/ui/onroad/cabin_camera_dialog.py @@ -3,7 +3,7 @@ from openpilot.starpilot.ui.raylib import rl from openpilot.cereal.visionipc import VisionStreamType from openpilot.selfdrive.ui.onroad.cameraview import CameraView from openpilot.selfdrive.ui.onroad.driver_state import DriverStateRenderer -from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.selfdrive.ui.ui_state import ui_state, device, live_params from openpilot.system.ui.lib.application import gui_app, FontWeight, TextAlignment from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.widgets.label import gui_label @@ -15,11 +15,11 @@ class CabinCameraDialog(CameraView): self.driver_state_renderer = DriverStateRenderer() # TODO: this can grow unbounded, should be given some thought device.add_interactive_timeout_callback(gui_app.pop_widget) - ui_state.params.put_bool("IsDriverViewEnabled", True, block=True) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", True, block=True) def hide_event(self): super().hide_event() - ui_state.params.put_bool("IsDriverViewEnabled", False, block=True) + live_params(ui_state.params).put_bool("IsDriverViewEnabled", False, block=True) self.close() def _handle_mouse_release(self, _): diff --git a/openpilot/selfdrive/ui/tests/diff/replay_script.py b/openpilot/selfdrive/ui/tests/diff/replay_script.py index eea4eef50d..51888c7836 100644 --- a/openpilot/selfdrive/ui/tests/diff/replay_script.py +++ b/openpilot/selfdrive/ui/tests/diff/replay_script.py @@ -116,8 +116,10 @@ class Script: def set_prime_state(prime_type: PrimeType) -> None: - from openpilot.selfdrive.ui.ui_state import ui_state - ui_state.prime_state.set_type(prime_type) + from openpilot.selfdrive.ui.ui_state import ProjectionPrimeState, ui_state + state = ui_state.prime_state + assert not isinstance(state, ProjectionPrimeState) + state.set_type(prime_type) def setup_offroad_alerts() -> None: diff --git a/openpilot/selfdrive/ui/tests/profile_onroad.py b/openpilot/selfdrive/ui/tests/profile_onroad.py index d54b8598f9..0cb1b3560f 100755 --- a/openpilot/selfdrive/ui/tests/profile_onroad.py +++ b/openpilot/selfdrive/ui/tests/profile_onroad.py @@ -50,7 +50,7 @@ def patch_submaster(message_chunks): sm.recv_frame[service] = sm.frame sm.valid[service] = True sm.frame += 1 - ui_state.sm.update = mock_update # ty: ignore[invalid-assignment] # profiling hook + ui_state.sm.update = mock_update if __name__ == "__main__": diff --git a/openpilot/selfdrive/ui/tests/test_arabesque_browser.py b/openpilot/selfdrive/ui/tests/test_arabesque_browser.py index 23ea5e4185..6176af76b4 100644 --- a/openpilot/selfdrive/ui/tests/test_arabesque_browser.py +++ b/openpilot/selfdrive/ui/tests/test_arabesque_browser.py @@ -181,6 +181,7 @@ def test_first_use_prepares_without_frames_and_waits_before_launching(tmp_path, try: assert not session.error and session._preparing and not session.buffers launch.assert_called_once() + assert session._listener is not None client.connect(session._listener.getsockname()) session.poll() assert runtime.receive(client)[0] == {'type': 'prepare', 'operation': 'install', 'target': ''} @@ -875,6 +876,7 @@ def test_completed_peer_can_close_before_the_next_owner_heartbeat(controller_own peer = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) peer.settimeout(1) try: + assert session._listener is not None peer.connect(session._listener.getsockname()) session.poll() _, descriptors = runtime.receive(peer, 1 if maintenance else 0) @@ -900,6 +902,7 @@ def test_peer_closing_without_completion_still_fails(controller_owner, monkeypat peer = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) peer.settimeout(1) try: + assert session._listener is not None peer.connect(session._listener.getsockname()) session.poll() runtime.receive(peer) @@ -922,12 +925,15 @@ def test_controller_survives_qualification_and_commits_only_after_upload_and_job job.settimeout(1) with (tmp_path / 'lock').open('w+') as lock: try: + assert session._listener is not None control.connect(session._listener.getsockname()) session.poll() assert runtime.receive(control)[0]['operation'] == 'update' control_unit = session._unit runtime.packet(control, {'type': 'job', 'job': 'qualify', 'transaction': 'a' * 32, 'garbage': []}, [lock.fileno()]) session.poll() + assert session._job is not None + assert session._job._listener is not None job.connect(session._job._listener.getsockname()) session.poll() init, fds = runtime.receive(job, 3) @@ -967,6 +973,7 @@ def test_maintenance_can_exceed_45_seconds_but_qualification_needs_gpu_ack(contr peer = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) peer.settimeout(1) try: + assert session._listener is not None peer.connect(session._listener.getsockname()) session.poll() _, fds = runtime.receive(peer, 1 if purpose == 'copy' else 3) diff --git a/openpilot/selfdrive/ui/tests/test_mici_projection_batch.py b/openpilot/selfdrive/ui/tests/test_mici_projection_batch.py index 4ed0cfecdb..b0feb5c0f0 100644 --- a/openpilot/selfdrive/ui/tests/test_mici_projection_batch.py +++ b/openpilot/selfdrive/ui/tests/test_mici_projection_batch.py @@ -192,9 +192,13 @@ def test_radar_only_reuses_lane_geometry_without_changing_path_filters_or_clip(r np.testing.assert_array_equal(renderer._path.projected_points, reference._path.projected_points) assert renderer._path.projected_points.shape != old_path.shape filter_updates = 2 if renderer_class is ModelRenderer else 0 - assert renderer._acceleration_x_filter.update.call_count == reference._acceleration_x_filter.update.call_count == filter_updates - assert renderer._acceleration_x_filter2.update.call_count == reference._acceleration_x_filter2.update.call_count == filter_updates - assert renderer._update_experimental_gradient.call_count == reference._update_experimental_gradient.call_count == 2 + for name in ("_acceleration_x_filter", "_acceleration_x_filter2"): + current, expected = getattr(renderer, name), getattr(reference, name) + assert isinstance(current, Mock) and isinstance(expected, Mock) + assert current.update.call_count == expected.update.call_count == filter_updates + gradient, expected_gradient = renderer._update_experimental_gradient, reference._update_experimental_gradient + assert isinstance(gradient, Mock) and isinstance(expected_gradient, Mock) + assert gradient.call_count == expected_gradient.call_count == 2 renderer._car_space_transform[0, 0] += 1 renderer._update_model(lead, points[:, 0], update_lane_geometry=True) batch_calls = renderer._map_lines_to_polygons.call_args_list @@ -205,6 +209,7 @@ def test_radar_only_reuses_lane_geometry_without_changing_path_filters_or_clip(r assert batch_calls[-1].kwargs['invert_last'] is True assert batch_calls[-1].kwargs['z_offsets'] == (0, 0, 0, 0, 0, 0, renderer._path_offset_z) renderer._map_lines_to_polygons.reset_mock() + assert renderer._clip_region is not None renderer._clip_region.x += 1 renderer._update_model(lead, points[:, 0], update_lane_geometry=False) batch_calls = renderer._map_lines_to_polygons.call_args_list diff --git a/openpilot/selfdrive/ui/ui.py b/openpilot/selfdrive/ui/ui.py index 037626cbfd..f75509373b 100755 --- a/openpilot/selfdrive/ui/ui.py +++ b/openpilot/selfdrive/ui/ui.py @@ -87,8 +87,9 @@ def main(): pm = messaging.PubMaster(['uiDebug']) star = layout.star if star_ui else None + close_layout = getattr(layout, "close", None) try: - poll_arabesque = layout.poll_arabesque if BIG_UI else None + poll_arabesque = getattr(layout, "poll_arabesque", None) if BIG_UI else None for should_render, frame_time, cpu_time in gui_app.render(before_frame=lambda: update_frame(preview, controllers, star, poll_game_mode, poll_arabesque)): if should_render: if camera_core_ui and not main_thread_configured: @@ -119,9 +120,10 @@ def main(): if controllers is not None: controllers.close() finally: - layout.close() - elif BIG_UI: - layout.close() + if close_layout is not None: + close_layout() + elif BIG_UI and close_layout is not None: + close_layout() if __name__ == "__main__": diff --git a/openpilot/selfdrive/ui/ui_state.py b/openpilot/selfdrive/ui/ui_state.py index 2904617455..1b648cde71 100644 --- a/openpilot/selfdrive/ui/ui_state.py +++ b/openpilot/selfdrive/ui/ui_state.py @@ -67,6 +67,12 @@ class ProjectionParams: return self._source.get_param_path(*args, **kwargs) +def live_params(params: Params | ProjectionParams) -> Params: + if isinstance(params, ProjectionParams): + raise AttributeError("Projection parameters are read-only") + return params + + class ProjectionPrimeState: """Saved pairing label only; projection never starts the API or alert owner.""" @@ -228,8 +234,9 @@ class UIState: return self.sm.recv_frame[service] > self.started_frame def update(self) -> None: - if getattr(self, "replay_clock", None) is not None: - before = self.replay_clock.sample() + replay_clock = getattr(self, "replay_clock", None) + if replay_clock is not None: + before = replay_clock.sample() cache_epoch = getattr(self, "_replay_state_epoch", self.replay_sample.epoch if self.replay_sample is not None else None) if before.epoch is not None and before.epoch != cache_epoch: self._reset_replay_state() @@ -237,7 +244,7 @@ class UIState: self.replay_needs_reprime = False self._replay_reprime_services = set() self.sm.update(0) - sample = self.replay_clock.sample() + sample = replay_clock.sample() if sample.epoch is not None and sample.epoch != before.epoch: # A seek straddled this receive. Keep only its eligible new primer, and # withhold this mixed frame until the next coherent clock sample. @@ -501,8 +508,9 @@ class UIState: self.chestnut_compiled = self.chestnut_active is True or self.chestnut_output_seen return now = time.monotonic() - if not self.started and (self._gpu_artifacts_at is None or now < self._gpu_artifacts_at or now - self._gpu_artifacts_at >= 1.): - self.chestnut_compiled, self.chestnut_checking = self._gpu_artifacts.selected_gpu_status() + artifacts = self._gpu_artifacts + if artifacts is not None and not self.started and (self._gpu_artifacts_at is None or now < self._gpu_artifacts_at or now - self._gpu_artifacts_at >= 1.): + self.chestnut_compiled, self.chestnut_checking = artifacts.selected_gpu_status() self._gpu_artifacts_at = now if cable_connected(): self.usb_disconnected_ts = None diff --git a/openpilot/selfdrive/ui/widgets/prime.py b/openpilot/selfdrive/ui/widgets/prime.py index c01d2f0e94..a24656ea9d 100644 --- a/openpilot/selfdrive/ui/widgets/prime.py +++ b/openpilot/selfdrive/ui/widgets/prime.py @@ -1,6 +1,6 @@ from openpilot.starpilot.ui.raylib import rl -from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.ui_state import ProjectionPrimeState, ui_state from openpilot.system.ui.lib.application import gui_app, FontWeight from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.lib.text_measure import measure_text_cached @@ -15,7 +15,10 @@ class PrimeWidget(Widget): PRIME_BG_COLOR = rl.Color(51, 51, 51, 255) def _render(self, rect): - if ui_state.prime_state.is_prime(): + state = ui_state.prime_state + if isinstance(state, ProjectionPrimeState): + return + if state.is_prime(): self._render_for_prime_user(rect) else: self._render_for_non_prime_users(rect) diff --git a/openpilot/starpilot/analytics/tests/test_runtime.py b/openpilot/starpilot/analytics/tests/test_runtime.py index 61fe8fdf6c..e1ba0f4519 100644 --- a/openpilot/starpilot/analytics/tests/test_runtime.py +++ b/openpilot/starpilot/analytics/tests/test_runtime.py @@ -165,6 +165,7 @@ def test_registered_native_params_roundtrip_and_restart_context(): assert restored.context['driving_model'] == 'verified' assert restored.metadata['dongle_id'] == obj.metadata['dongle_id'] restored.poll_once() + assert isinstance(restored.client, Mock) restored.client.send.assert_not_called() del restored, obj, params diff --git a/openpilot/starpilot/aol/tests/honda_pandad_order.py b/openpilot/starpilot/aol/tests/honda_pandad_order.py index 3f7b107adb..82ff5bef4e 100644 --- a/openpilot/starpilot/aol/tests/honda_pandad_order.py +++ b/openpilot/starpilot/aol/tests/honda_pandad_order.py @@ -25,8 +25,11 @@ class PandadOrder: def exchange(self, line): assert self.process.poll() is None + assert self.process.stdin is not None self.process.stdin.write(line + '\n') + assert self.process.stdin is not None self.process.stdin.flush() + assert self.process.stdout is not None result = self.process.stdout.readline().strip().split() assert result, self.process.poll() return result @@ -97,8 +100,10 @@ class PandadOrder: return wire, {'before': before, 'plan': (capable, request, retain), 'heartbeat': self.heartbeat, 'after': after, 'session': session} def close(self): + assert self.process.stdin is not None self.process.stdin.close() try: assert self.process.wait(timeout=10) == 0 finally: + assert self.process.stdout is not None self.process.stdout.close() diff --git a/openpilot/starpilot/aol/tests/hyundai_cpp_order.py b/openpilot/starpilot/aol/tests/hyundai_cpp_order.py index 0cfc2fdccf..e487f84894 100644 --- a/openpilot/starpilot/aol/tests/hyundai_cpp_order.py +++ b/openpilot/starpilot/aol/tests/hyundai_cpp_order.py @@ -24,8 +24,11 @@ class PandadOrder: def exchange(self, line): assert self.process.poll() is None + assert self.process.stdin is not None self.process.stdin.write(line + '\n') + assert self.process.stdin is not None self.process.stdin.flush() + assert self.process.stdout is not None result = self.process.stdout.readline().strip().split() assert result, self.process.poll() return result @@ -52,10 +55,12 @@ class PandadOrder: 'after': after, 'session': session} def close(self): + assert self.process.stdin is not None self.process.stdin.close() try: assert self.process.wait(timeout=10) == 0 finally: + assert self.process.stdout is not None self.process.stdout.close() diff --git a/openpilot/starpilot/aol/tests/stock_lateral_test_helpers.py b/openpilot/starpilot/aol/tests/stock_lateral_test_helpers.py index ec758d16b5..484986fb92 100644 --- a/openpilot/starpilot/aol/tests/stock_lateral_test_helpers.py +++ b/openpilot/starpilot/aol/tests/stock_lateral_test_helpers.py @@ -58,7 +58,9 @@ def callers(cleanup, family, lateral_only): card.slc_producer_session = 'authority-card' physical = car_state() physical.cruiseState.available = True + assert card.aol_card_intent is not None card.aol_card_intent.update(physical, now_ns=9_990_000_000) + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch, 'Actual family main-edge owner did not arm' def receive(now, state=None): @@ -87,6 +89,7 @@ def callers(cleanup, family, lateral_only): ): actual, rd = card.state_update() assert actual is physical + assert card.aol_card_intent is not None return card.aol_card_intent.allowed_latch for tick in (0, 1): @@ -161,14 +164,18 @@ def _hkg_family_callers(self, full_op=True): self.assertEqual(card.CP.to_dict(), sd.CP.to_dict()) from openpilot.starpilot.aol.vehicle import policy_for + assert card.aol_card_intent is not None self.assertEqual(card.aol_card_intent.explicit_latch, policy_for(card.CP).explicit_latch) card.slc_producer_session = 'authority-card' cs = car_state() cs.cruiseState.available = True + assert card.aol_card_intent is not None card.aol_card_intent.update(cs, now_ns=9_980_000_000) cs.buttonEvents = [car.CarState.ButtonEvent(type=car.CarState.ButtonEvent.Type.lkas, pressed=True)] + assert card.aol_card_intent is not None card.aol_card_intent.update(cs, now_ns=9_990_000_000) cs.buttonEvents = [] + assert card.aol_card_intent is not None self.assertTrue(card.aol_card_intent.allowed_latch) def receive(now, *, axis=None, event=None, state=None): @@ -199,9 +206,11 @@ def _hkg_family_callers(self, full_op=True): ): actual, _ = card.state_update() self.assertIs(actual, observed) + assert card.aol_card_intent is not None return card.aol_card_intent.allowed_latch def drive(tick, **kwargs): + assert card.aol_card_intent is not None kwargs.setdefault('latched', card.aol_card_intent.allowed_latch) return step(tick, **kwargs) @@ -296,16 +305,21 @@ def _honda_family_callers(self, full_op=True): self.assertEqual(card.CP.to_dict(), sd.CP.to_dict()) from openpilot.starpilot.aol.vehicle import policy_for + assert card.aol_card_intent is not None self.assertEqual(card.aol_card_intent.explicit_latch, policy_for(card.CP).explicit_latch) card.slc_producer_session = 'authority-card' cs = car_state() cs.cruiseState.available = False + assert card.aol_card_intent is not None card.aol_card_intent.update(cs, now_ns=9_970_000_000) cs.cruiseState.available = True + assert card.aol_card_intent is not None card.aol_card_intent.update(cs, now_ns=9_980_000_000) cs.buttonEvents = [car.CarState.ButtonEvent(type=car.CarState.ButtonEvent.Type.lkas, pressed=True)] + assert card.aol_card_intent is not None card.aol_card_intent.update(cs, now_ns=9_990_000_000) cs.buttonEvents = [] + assert card.aol_card_intent is not None self.assertTrue(card.aol_card_intent.allowed_latch) actual_clock_gettime_ns = time.clock_gettime_ns @@ -341,9 +355,11 @@ def _honda_family_callers(self, full_op=True): self.assertTrue(card.startup_panda_configured()) actual, _ = card.state_update() self.assertIs(actual, observed) + assert card.aol_card_intent is not None return card.aol_card_intent.allowed_latch def drive(tick, **kwargs): + assert card.aol_card_intent is not None kwargs.setdefault('latched', card.aol_card_intent.allowed_latch) return step(tick, **kwargs) diff --git a/openpilot/starpilot/aol/tests/test_canfd_location_native_recovery.py b/openpilot/starpilot/aol/tests/test_canfd_location_native_recovery.py index 6bc748acca..4e6e2c9ddc 100644 --- a/openpilot/starpilot/aol/tests/test_canfd_location_native_recovery.py +++ b/openpilot/starpilot/aol/tests/test_canfd_location_native_recovery.py @@ -350,6 +350,7 @@ def test_actual_canfd_card_host_native_location_recovery(family, unavailable_tic step(main=1, lkas=1, engaged=False) for _ in range(40): state, axis, host, command, steering = step(main=1, engaged=False) + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch assert native.aol_get_permission_mask() == 1 and not native.get_controls_allowed() assert axis.lateralActive and command.latActive and not host.enabled diff --git a/openpilot/starpilot/aol/tests/test_ccnc_full_stop_intent.py b/openpilot/starpilot/aol/tests/test_ccnc_full_stop_intent.py index 903a8594b5..448fcf42b6 100644 --- a/openpilot/starpilot/aol/tests/test_ccnc_full_stop_intent.py +++ b/openpilot/starpilot/aol/tests/test_ccnc_full_stop_intent.py @@ -136,7 +136,9 @@ def test_actual_card_disarming_preserves_intent_then_brake_fallback(identity): card = Car.__new__(Car) card.CP = cp def intent_at(now): + assert card.aol_card_intent is not None allowed, pause_lat, pause_long = card.aol_card_intent.output(cs) + assert card.aol_card_intent is not None return decode_intent(encode_intent(IntentState(PRODUCER, 1, now, now, now + 200_000_000, allowed, pause_lat, pause_long, True, card.aol_card_intent.allowed_latch))) card.aol_transport_feedback = TransportPauseFeedback(cp) diff --git a/openpilot/starpilot/aol/tests/test_distracted_lateral.py b/openpilot/starpilot/aol/tests/test_distracted_lateral.py index c5de09266d..f28bab311a 100644 --- a/openpilot/starpilot/aol/tests/test_distracted_lateral.py +++ b/openpilot/starpilot/aol/tests/test_distracted_lateral.py @@ -5,7 +5,7 @@ from unittest import mock import pytest from openpilot.cereal import log -from openpilot.selfdrive.selfdrived.events import EVENTS, ET, EventName +from openpilot.selfdrive.selfdrived.events import Alert, EVENTS, ET, EventName from openpilot.starpilot.aol.tests.stock_lateral_test_helpers import callers from openpilot.starpilot.aol.tests.test_ioniq_availability import car_state @@ -41,6 +41,7 @@ def test_actual_armed_dm_escalation_retains_lateral_and_drops_long(family, full, event = EventName.driverDistracted3 if vision else EventName.driverUnresponsive3 assert event in sd.events.names alert = EVENTS[event][ET.PERMANENT] + assert isinstance(alert, Alert) assert alert.audible_alert == log.SelfdriveState.AudibleAlert.warningImmediate assert alert.alert_status == log.SelfdriveState.AlertStatus.critical assert not sd.enabled and not command.longActive diff --git a/openpilot/starpilot/aol/tests/test_ev6_stock_parity.py b/openpilot/starpilot/aol/tests/test_ev6_stock_parity.py index 25a77d3ab3..19f9fb4fa8 100644 --- a/openpilot/starpilot/aol/tests/test_ev6_stock_parity.py +++ b/openpilot/starpilot/aol/tests/test_ev6_stock_parity.py @@ -70,7 +70,9 @@ def test_actual_card_stock_lkas_then_main_respects_saved_binding(main_action): assert card.CS_prev.canValid and not card.CS_prev.canTimeout assert card.CS_prev.cruiseState.available if tick == 21: + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch == (main_action == 0) assert not card.last_actuators_output.torqueOutputCan # No native permission was provided. finally: @@ -92,13 +94,17 @@ def test_actual_controller_dash_follows_aol_without_changing_actuation(alpha): ci = CarInterface(stock.params(CAR.KIA_EV6)) ci.CP.safetyConfigs[-1].safetyParam |= 0x800 try: - parser = CANParser(DBC[CAR.KIA_EV6][Bus.pt], [('LKAS', 0)], ci.CC.CAN.ACAN) + from opendbc.car.hyundai.carcontroller import CarController + + controller = ci.CC + assert isinstance(controller, CarController) + parser = CANParser(DBC[CAR.KIA_EV6][Bus.pt], [('LKAS', 0)], controller.CAN.ACAN) for tick in range(120): now = 10_000_000_000 + tick * 10_000_000 ci.update([(now, packets(ci, tick))]) command = structs.CarControl(enabled=40 <= tick < 80, latActive=20 <= tick < 60) _, frames = ci.apply(command.as_reader(), now) - steering = [frame for frame in frames if frame[0] == 0x50 and frame[2] == ci.CC.CAN.ACAN] + steering = [frame for frame in frames if frame[0] == 0x50 and frame[2] == controller.CAN.ACAN] assert len(steering) == 1 parser.update([(now, steering)]) values = parser.vl['LKAS'] diff --git a/openpilot/starpilot/aol/tests/test_forte_integration.py b/openpilot/starpilot/aol/tests/test_forte_integration.py index 527ab0a806..738183e5c2 100644 --- a/openpilot/starpilot/aol/tests/test_forte_integration.py +++ b/openpilot/starpilot/aol/tests/test_forte_integration.py @@ -157,7 +157,9 @@ class TestForteIntegration(unittest.TestCase): stream = ForteStream(car=car, source=source, main_action=9, controller_mode=mode) self.assertEqual(stream.cp.safetyConfigs[0].safetyParam, 0x1c00 if source else 0x1400) self.assertEqual(stream.cp.alternativeExperience, 32) + assert stream.lateral_controller is not None self.assertEqual(stream.lateral_controller.controller_mode, mode) + assert stream.lateral_controller is not None self.assertEqual(bool(stream.lateral_controller.starpilot_extension), mode == ControllerMode.STARPILOT) self.assertTrue(self.warm(stream, main=True).lateral_active, case) self.assertGreater(stream.cs.vEgo, 19., case) @@ -168,6 +170,7 @@ class TestForteIntegration(unittest.TestCase): for _ in range(180): self.assertTrue(stream.tick(main=True).lateral_active, case) self.assertLessEqual(abs(stream.last_torque), 255, case) + assert stream.lateral_controller is not None context = (f'{case}; vEgo={stream.cs.vEgo}, angle={stream.cs.steeringAngleDeg}, ' + f'driverTorque={stream.cs.steeringTorque}, normalized={stream.last_normalized_torque}, ' + f'sentTorque={stream.last_torque}, factor={stream.lateral_controller.torque_params.latAccelFactor}') diff --git a/openpilot/starpilot/aol/tests/test_forte_physical_arm_join.py b/openpilot/starpilot/aol/tests/test_forte_physical_arm_join.py index c6c879d365..480d93a088 100644 --- a/openpilot/starpilot/aol/tests/test_forte_physical_arm_join.py +++ b/openpilot/starpilot/aol/tests/test_forte_physical_arm_join.py @@ -12,6 +12,7 @@ from opendbc.can import CANPacker from opendbc.car.hyundai.interface import CarInterface from opendbc.car.hyundai.radar_interface import RadarInterface from opendbc.car.hyundai.values import CAR +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix @@ -255,6 +256,8 @@ def _exercise_forte_join(gesture, withdrawal, monkeypatch): assert steering for frame in received['sendcan'].sendcan: assert native.safety_tx_hook(libsafety_py.make_CANPacket(frame.address, frame.src - offset, frame.dat)) + assert card.aol_card_intent is not None + assert card.aol_transport_feedback is not None trace.append( { 'tick': tick, @@ -292,7 +295,9 @@ def _exercise_forte_join(gesture, withdrawal, monkeypatch): for _ in range(26): step(main=False, main_button=_ < 2) assert native.safety_config_valid() and not native.safety_test_toyota_rx_summary_invalid() - assert card.aol_card_intent.main_off_seen and not card.aol_transport_feedback.failed, ('FORTE_STARTUP_NOT_READY', trace[-30:]) + assert (require_value(card.aol_card_intent).main_off_seen and + not require_value(card.aol_transport_feedback).failed), ('FORTE_STARTUP_NOT_READY', trace[-30:]) + assert card.aol_card_intent is not None assert not card.aol_card_intent.allowed_latch for _ in range(2): step(main=gesture == 'main', lkas=gesture == 'lkas', main_button=gesture == 'main', withdraw_request=withdrawal == 'no-request') @@ -302,6 +307,7 @@ def _exercise_forte_join(gesture, withdrawal, monkeypatch): if withdrawal == 'no-request': assert not command.latActive and (not axis.lateralActive) if withdrawal == 'no-request': + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch, ('FORTE_ARMED_INTENT_PRESERVED_WITHOUT_OUTPUT_ACK', trace[-26:]) assert not native.aol_get_permission_mask() return diff --git a/openpilot/starpilot/aol/tests/test_gm.py b/openpilot/starpilot/aol/tests/test_gm.py index 7d6fa1973e..28118007b3 100644 --- a/openpilot/starpilot/aol/tests/test_gm.py +++ b/openpilot/starpilot/aol/tests/test_gm.py @@ -382,7 +382,7 @@ class TestGmAol(unittest.TestCase): self.assertFalse(card.CP.openpilotLongitudinalControl) self.assertEqual(card.CP.safetyConfigs[0].safetyParam, 16) self.assertEqual(card.CP.alternativeExperience, 32) - self.assertIsNotNone(card.aol_card_intent) + assert card.aol_card_intent is not None cs = structs.CarState(canValid=True, gearShifter='drive', vEgo=20.) cs.cruiseState.available = True cs.cruiseState.enabled = False @@ -1083,8 +1083,11 @@ class TestGmAol(unittest.TestCase): axis.aolAxisState.observedMonoTime, axis.aolAxisState.validUntilMonoTime = now, now + 30_000_000 state = messaging.new_message('carState', valid=True, logMonoTime=now) state.carState = cs + assert controls is not None controls.sm.update_msgs((now + 1_000) / 1e9, [axis.as_reader(), receipt.as_reader(), state.as_reader()]) + assert controls is not None command, lateral_log = controls.state_control() + assert controls is not None controls.publish(command, lateral_log) self.assertTrue(command.latActive) self.assertEqual(command.longActive, not cs.seatbeltUnlatched) diff --git a/openpilot/starpilot/aol/tests/test_gm_ascm_receive_order.py b/openpilot/starpilot/aol/tests/test_gm_ascm_receive_order.py index 2571ecd4b3..97fdb81252 100644 --- a/openpilot/starpilot/aol/tests/test_gm_ascm_receive_order.py +++ b/openpilot/starpilot/aol/tests/test_gm_ascm_receive_order.py @@ -6,6 +6,7 @@ from opendbc.car.gm.tests.test_volt_sdgm_control import sdgm_params from opendbc.car.gm.tests.test_ascm_intercept import params as ascm_params from opendbc.car.gm.values import CAR, apply_gm_auto_hold from opendbc.car.structs import car +from openpilot.common.test import require_value from openpilot.cereal import log, messaging from openpilot.common.prefix import OpenpilotPrefix from openpilot.common.realtime import Ratekeeper @@ -75,8 +76,8 @@ def test_ascm_exact_card_raw_companion_survives_older_cached_projection(c9, rada card.state_publish(cs, None) publish(older, fault=condition in ('sm_fault','sm_expired_fault'), valid=condition not in ('sm_invalid','sm_expired_invalid')) - assert actual_recv(sd.car_state_sock).logMonoTime == older - cached = actual_recv(latest).as_builder() + assert require_value(actual_recv(sd.car_state_sock)).logMonoTime == older + cached = require_value(actual_recv(latest)).as_builder() assert cached.logMonoTime == older if condition == 'sm_wrong_source': cached.starpilotCarState.sourceCarStateMonoTime -= 1 @@ -87,6 +88,7 @@ def test_ascm_exact_card_raw_companion_survives_older_cached_projection(c9, rada def receive_first(sock): publish(source, fault=condition == 'raw_fault', enabled=condition != 'missing_exact', valid=condition != 'source_invalid') first = actual_recv(sock) + assert first is not None assert first.logMonoTime == source return first @@ -247,6 +249,7 @@ def test_normal_control_receipts_with_aol_disabled(sdgm, c9, initial_active, con with patch('openpilot.selfdrive.car.card.messaging.new_message', side_effect=lambda *a, **kw: actual_message(*a, **dict(kw, logMonoTime=stamp))): card.state_publish(cs, None) received = messaging.recv_one(cs_sock) + assert received is not None assert received.logMonoTime == stamp return received diff --git a/openpilot/starpilot/aol/tests/test_gm_held_brake_successor.py b/openpilot/starpilot/aol/tests/test_gm_held_brake_successor.py index 9eda6d81d7..6117ce3272 100644 --- a/openpilot/starpilot/aol/tests/test_gm_held_brake_successor.py +++ b/openpilot/starpilot/aol/tests/test_gm_held_brake_successor.py @@ -13,6 +13,7 @@ from opendbc.car import Bus, structs from opendbc.car.gm.tests.test_volt_sdgm_control import sdgm_params from opendbc.car.gm.values import DBC from opendbc.safety.tests.libsafety import libsafety_py as native +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.common.prefix import OpenpilotPrefix from openpilot.starpilot.aol.intent import read_settings @@ -323,7 +324,7 @@ def exercise_sdgm(c9, alpha, condition="healthy"): sd.CS_prev = sd.CS_prev.as_builder() sd.CS_prev.cruiseState.enabled = True if condition in ("future_current", "old_current"): - source = decision_ns + 1 if condition == "future_current" else old_axis.sourceCarStateMonoTime + source = decision_ns + 1 if condition == "future_current" else require_value(old_axis).sourceCarStateMonoTime state = captured["carState"] assert state is not None state.logMonoTime = source @@ -357,6 +358,7 @@ def exercise_sdgm(c9, alpha, condition="healthy"): authority_message=captured.get("starpilotCarState"), ) if negative: + assert old_axis is not None assert old_axis.validUntilMonoTime < decision_ns assert not axis.lateralActive and not cc.latActive, (condition, axis.to_dict(), sd.events.names) assert not axis.longitudinalActive and not cc.longActive @@ -365,9 +367,12 @@ def exercise_sdgm(c9, alpha, condition="healthy"): old_axis = axis receive_card(decision_ns, control=False) if tick == 390: + assert old_axis is not None assert old_axis.validUntilMonoTime < decision_ns + assert old_axis is not None old_deadline = old_axis.validUntilMonoTime receive_card(decision_ns) + assert old_axis is not None assert old_axis.validUntilMonoTime == old_deadline assert axis.validUntilMonoTime == decision_ns + 30_000_000 assert not cc.enabled and not cc.longActive and not safety.get_controls_allowed() diff --git a/openpilot/starpilot/aol/tests/test_gm_receipt_clock_ipc.py b/openpilot/starpilot/aol/tests/test_gm_receipt_clock_ipc.py index a969ffd163..73ca00871f 100644 --- a/openpilot/starpilot/aol/tests/test_gm_receipt_clock_ipc.py +++ b/openpilot/starpilot/aol/tests/test_gm_receipt_clock_ipc.py @@ -60,12 +60,14 @@ def test_real_card_socket_clock_crossing_preserves_sdgm_axes(c9, full_op): def receive_first(sock): publish(source) first = actual_recv(sock) + assert first is not None assert first.logMonoTime == source publish(later) return first def receive_latest(_timeout): message = actual_recv(latest) + assert message is not None assert message.logMonoTime == later sd.sm.update_msgs(clock[0] / 1e9, [message]) diff --git a/openpilot/starpilot/aol/tests/test_gm_route1c_receive_order.py b/openpilot/starpilot/aol/tests/test_gm_route1c_receive_order.py index c7e122294f..9008b69675 100644 --- a/openpilot/starpilot/aol/tests/test_gm_route1c_receive_order.py +++ b/openpilot/starpilot/aol/tests/test_gm_route1c_receive_order.py @@ -5,6 +5,7 @@ from unittest.mock import patch import pytest from opendbc.car.gm.tests.test_volt_sdgm_control import sdgm_params from opendbc.car.structs import car +from openpilot.common.test import require_value from openpilot.cereal import log, messaging from openpilot.common.prefix import OpenpilotPrefix from openpilot.common.realtime import Ratekeeper @@ -75,8 +76,8 @@ def test_exact_card_raw_companion_survives_older_cached_projection(c9, full_op, card.state_publish(cs, None) publish(older, fault=condition in ('sm_fault', 'sm_expired_fault'), valid=condition not in ('sm_invalid', 'sm_expired_invalid')) - assert actual_recv(sd.car_state_sock).logMonoTime == older - cached = actual_recv(latest).as_builder() + assert require_value(actual_recv(sd.car_state_sock)).logMonoTime == older + cached = require_value(actual_recv(latest)).as_builder() assert cached.logMonoTime == older if condition == 'sm_wrong_source': cached.starpilotCarState.sourceCarStateMonoTime -= 1 @@ -87,6 +88,7 @@ def test_exact_card_raw_companion_survives_older_cached_projection(c9, full_op, def receive_first(sock): publish(source, fault=condition == 'raw_fault', enabled=condition != 'missing_exact') first = actual_recv(sock) + assert first is not None assert first.logMonoTime == source return first diff --git a/openpilot/starpilot/aol/tests/test_gm_steering_receive_order.py b/openpilot/starpilot/aol/tests/test_gm_steering_receive_order.py index 373f959893..69b87390b0 100644 --- a/openpilot/starpilot/aol/tests/test_gm_steering_receive_order.py +++ b/openpilot/starpilot/aol/tests/test_gm_steering_receive_order.py @@ -4,6 +4,7 @@ from unittest.mock import patch import pytest from opendbc.car.gm.tests.test_volt_sdgm_control import sdgm_params from opendbc.car.structs import car +from openpilot.common.test import require_value from openpilot.cereal import log, messaging from openpilot.common.prefix import OpenpilotPrefix from openpilot.common.realtime import Ratekeeper @@ -61,8 +62,8 @@ def test_exact_card_raw_companion_survives_older_cached_projection(c9, full_op, card.state_publish(cs, None) publish(older, fault=condition in ('sm_fault','sm_expired_fault'), valid=condition not in ('sm_invalid','sm_expired_invalid')) - assert actual_recv(sd.car_state_sock).logMonoTime == older - cached = actual_recv(latest).as_builder() + assert require_value(actual_recv(sd.car_state_sock)).logMonoTime == older + cached = require_value(actual_recv(latest)).as_builder() assert cached.logMonoTime == older if condition == 'sm_wrong_source': cached.starpilotCarState.sourceCarStateMonoTime -= 1 @@ -73,6 +74,7 @@ def test_exact_card_raw_companion_survives_older_cached_projection(c9, full_op, def receive_first(sock): publish(source, fault=condition == 'raw_fault', enabled=condition != 'missing_exact') first = actual_recv(sock) + assert first is not None assert first.logMonoTime == source return first diff --git a/openpilot/starpilot/aol/tests/test_hkg_cancel_joined.py b/openpilot/starpilot/aol/tests/test_hkg_cancel_joined.py index 45d8dced2d..0f62c42995 100644 --- a/openpilot/starpilot/aol/tests/test_hkg_cancel_joined.py +++ b/openpilot/starpilot/aol/tests/test_hkg_cancel_joined.py @@ -13,6 +13,7 @@ from opendbc.car import structs from opendbc.car.hyundai.interface import CarInterface from opendbc.car.hyundai.radar_interface import RadarInterface from opendbc.car.hyundai.values import CAR +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix @@ -330,6 +331,7 @@ def _exercise_join(identity, alternate, incidental, withdrawal, monkeypatch, *, wire = held_cancel_wire cancel_hold_ticks -= 1 prior_wire = actual_wire + assert wire is not None messages = [device.as_reader(), pandas.as_reader(), wire.as_reader()] messages += [previous_sd[name] for name in ('selfdriveState', 'aolAxisState', 'onroadEvents') if name in previous_sd] if 'onroadEvents' not in previous_sd: @@ -369,6 +371,7 @@ def _exercise_join(identity, alternate, incidental, withdrawal, monkeypatch, *, validated = current_native(sd.sm, sd.CP, now_ns=source_ns, axis_session_id=sd.aol_session_id) bootstrap_mismatch = False if two_panda or cancel_health_order: + assert wire is not None source_report = decode_safety(wire.aolSafetyWire) assert source_report is not None bootstrap_mismatch = source_report.axisSessionId != sd.aol_session_id @@ -394,7 +397,7 @@ def _exercise_join(identity, alternate, incidental, withdrawal, monkeypatch, *, if state.canValid: assert 'sendcan' in received and received['sendcan'].valid steering = [frame for frame in received['sendcan'].sendcan - if frame.address == (0x110 if alternate else 0x50) and frame.src == card.CI.CC.CAN.ACAN] + if frame.address == (0x110 if alternate else 0x50) and frame.src == require_value(card).CI.CC.CAN.ACAN] assert steering for frame in received['sendcan'].sendcan: assert native.safety_tx_hook(libsafety_py.make_CANPacket(frame.address, frame.src - offset, frame.dat)) @@ -404,6 +407,7 @@ def _exercise_join(identity, alternate, incidental, withdrawal, monkeypatch, *, step() if two_panda: assert bootstrap_refusals, 'Actual startup session mismatch was not exercised' + assert card.aol_card_intent is not None assert not card.aol_card_intent.allowed_latch assert native.safety_config_valid() # All selected physical RX sources are actually primed. for _ in range(2): @@ -433,10 +437,12 @@ def _exercise_join(identity, alternate, incidental, withdrawal, monkeypatch, *, assert axis.longitudinalActive and command.longActive # Full engagement is a legitimate driver-owned intent epoch. Anchor # after its real publication, immediately before incidental buttons. + assert card.aol_card_intent is not None edge = card.aol_card_intent._last_latch_edge_ns for _ in range(2): gesture = 'cancel' if two_panda else incidental state, axis, host, command, _ = step(main=int(gesture == 'main'), button=4 if gesture == 'cancel' else 0) + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch, ( ('HKG_INDEPENDENT_LATCH_DROPPED', cancel_diagnostics[-1:]) if two_panda else 'HKG_INDEPENDENT_LATCH_DROPPED') assert native.aol_get_permission_mask() & 1, 'HKG_NATIVE_LATERAL_DROPPED' @@ -452,8 +458,10 @@ def _exercise_join(identity, alternate, incidental, withdrawal, monkeypatch, *, nonzero = False for _ in range(20): state, axis, host, command, steering = step() + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch, ( ('HKG_INDEPENDENT_LATCH_DROPPED', cancel_diagnostics[-1:]) if two_panda else 'HKG_INDEPENDENT_LATCH_DROPPED') + assert card.aol_card_intent is not None assert card.aol_card_intent._last_latch_edge_ns == edge, 'HKG_INCIDENTAL_EDGE_RENEWED' assert native.aol_get_permission_mask() & 1, 'HKG_NATIVE_LATERAL_DROPPED' assert axis.lateralActive and command.latActive, 'HKG_JOINED_LATERAL_DROPPED' @@ -473,6 +481,7 @@ def _exercise_join(identity, alternate, incidental, withdrawal, monkeypatch, *, for _ in range(20): state, axis, host, command, _ = step() assert card.aol_card_intent.allowed_latch and axis.lateralActive and command.latActive + assert card.aol_card_intent is not None assert card.aol_card_intent._last_latch_edge_ns == edge assert not host.enabled and not axis.longitudinalActive and not command.longActive assert not native.get_controls_allowed() diff --git a/openpilot/starpilot/aol/tests/test_honda_recovery_lifecycle.py b/openpilot/starpilot/aol/tests/test_honda_recovery_lifecycle.py index e06a91ba09..9bcf8db162 100644 --- a/openpilot/starpilot/aol/tests/test_honda_recovery_lifecycle.py +++ b/openpilot/starpilot/aol/tests/test_honda_recovery_lifecycle.py @@ -19,6 +19,7 @@ from opendbc.car.fw_versions import match_fw_to_car from opendbc.car.honda.values import CAR, HondaFlags, DBC from opendbc.can.dbc import DBC as CANDBC from opendbc.safety.tests.libsafety import libsafety_py +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix @@ -320,7 +321,7 @@ class TestHondaCurrentCaller(unittest.TestCase): self.assertTrue(cs.cruiseState.available) self.assertEqual(cs.cruiseState.enabled, 21 <= tick < (51 if native_brake_first else 50) and not cancelled or reengage) intent = decode_intent(published['aolIntentWire'].aolIntentWire) - self.assertIsNotNone(intent) + assert intent is not None # Initial receipt is unavailable until actual negotiator completes its zero acknowledgment. absent = messaging.new_message('aolSafetyWire', 0, valid=False, logMonoTime=now) current_receipt = receipt if receipt is not None else absent @@ -401,6 +402,7 @@ class TestHondaCurrentCaller(unittest.TestCase): self.assertEqual(card.sm.logMonoTime['carControl'], previous_event.logMonoTime) self.assertFalse(outgoing) self.assertNotIn('sendcan', published) + assert card.aol_transport_feedback is not None row = { 'tick': tick, 'heartbeat': pandad.heartbeat, @@ -412,7 +414,7 @@ class TestHondaCurrentCaller(unittest.TestCase): 'stored_latch': card.aol_card_intent.allowed_latch, 'latch_clear_reason': card.aol_card_intent.latch_clear_reason, 'transport_failed': card.aol_transport_feedback.failed, - 'axis': published.get('aolAxisState').to_dict() if 'aolAxisState' in published else None, + 'axis': require_value(published.get('aolAxisState')).to_dict() if 'aolAxisState' in published else None, 'previous_events': [(str(e.name), e.immediateDisable, e.softDisable, e.userDisable) for e in card.sm['onroadEvents']], 'armed': intent.lateralArmed, 'standard_enabled': sd.enabled, diff --git a/openpilot/starpilot/aol/tests/test_honda_route_regressions.py b/openpilot/starpilot/aol/tests/test_honda_route_regressions.py index 1507df43ba..9ba7d894e3 100644 --- a/openpilot/starpilot/aol/tests/test_honda_route_regressions.py +++ b/openpilot/starpilot/aol/tests/test_honda_route_regressions.py @@ -73,11 +73,12 @@ def eps_sample(cp, stamp, *, withdrawn, brake=False, gas=False): sm, native = sample(cp, stamp, stamp, 2, active=not withdrawn, allowed=False, event_stamp=stamp if withdrawn else NOW) event = sm.messages['onroadEvents'].as_builder() - event.onroadEvents = [{'name': 'steerOverride', 'overrideLateral': True}] + events = [{'name': 'steerOverride', 'overrideLateral': True}] if brake: - event.onroadEvents = [*(e.to_dict() for e in event.onroadEvents), {'name': 'pedalPressed', 'userDisable': True}] + events.append({'name': 'pedalPressed', 'userDisable': True}) if gas: - event.onroadEvents = [*(e.to_dict() for e in event.onroadEvents), {'name': 'gasPressedOverride', 'overrideLongitudinal': True}] + events.append({'name': 'gasPressedOverride', 'overrideLongitudinal': True}) + event.onroadEvents = events sm.messages['onroadEvents'] = event.as_reader() return sm, native diff --git a/openpilot/starpilot/aol/tests/test_meb_actual_callers.py b/openpilot/starpilot/aol/tests/test_meb_actual_callers.py index 5bcfb2a02f..74b78e2049 100644 --- a/openpilot/starpilot/aol/tests/test_meb_actual_callers.py +++ b/openpilot/starpilot/aol/tests/test_meb_actual_callers.py @@ -83,6 +83,7 @@ def test_meb_full_engagement_brake_reverse_drive_actual_callers(identity, stock, for envelope in messages: if envelope.which() == 'pandaStates': envelope = envelope.as_builder() + assert quiet is not None envelope.pandaStates[0].controlsAllowed = bool(quiet.get_controls_allowed()) actual.append(envelope) return original_update(timestamp, actual) @@ -252,6 +253,7 @@ def test_meb_full_engagement_brake_reverse_drive_actual_callers(identity, stock, assert not quiet.safety_tx_hook(make_msg(bus - offset, addr, dat=data)) emitted.extend(sent) if fault_phase and tick in (119, 120, 124, 125, 129, 130, 132, 139, 140, 145, 150, 159, 160, 169, 170, 175, 180): + assert card.aol_card_intent is not None fault_trace.append((tick, permission, card.aol_card_intent.allowed_latch, state.steerFaultTemporary, state.steerFaultPermanent, axis.desiredLateral, axis.lateralActive, axis.nativeAcknowledged, command.latActive, str(axis.faultReason), diff --git a/openpilot/starpilot/aol/tests/test_mqb_actual_callers.py b/openpilot/starpilot/aol/tests/test_mqb_actual_callers.py index 480ec79622..1903a67bc3 100644 --- a/openpilot/starpilot/aol/tests/test_mqb_actual_callers.py +++ b/openpilot/starpilot/aol/tests/test_mqb_actual_callers.py @@ -17,6 +17,7 @@ from opendbc.car.volkswagen.interface import CarInterface from opendbc.car.volkswagen.values import CAR from opendbc.safety.tests.common import make_msg from opendbc.safety.tests.libsafety import libsafety_py +from openpilot.common.test import require_value from openpilot.cereal import log, messaging from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix @@ -97,6 +98,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, for envelope in messages: if envelope.which() == 'pandaStates': envelope = envelope.as_builder() + assert quiet is not None envelope.pandaStates[0].controlsAllowed = bool(quiet.get_controls_allowed()) actual.append(envelope) return original_update(timestamp, actual) @@ -175,7 +177,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, native.set_timer(1_000_000 + tick * 10_000) update_heartbeat = (parked_boot or main_cycle or creep_start and tick >= 12) and (not delayed_heartbeat or tick % 10 == 1) if update_heartbeat and not heartbeat_after_can: - native.set_aol_test_heartbeat(bool((card.aol_card_intent.allowed_latch or request) and tick >= startup_block_until)) + native.set_aol_test_heartbeat(bool((require_value(card.aol_card_intent).allowed_latch or request) and tick >= startup_block_until)) if quiet is not None: quiet.set_timer(1_000_000 + tick * 10_000) quiet.safety_tick() @@ -239,7 +241,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, native.safety_rx_hook(make_msg(bus - offset, addr, dat=data)) native.safety_tick() if update_heartbeat and heartbeat_after_can: - native.set_aol_test_heartbeat(bool((card.aol_card_intent.allowed_latch or request) and tick >= startup_block_until)) + native.set_aol_test_heartbeat(bool((require_value(card.aol_card_intent).allowed_latch or request) and tick >= startup_block_until)) native.aol_set_host_request(request) permission = native.aol_get_permission_mask() if early_brake and tick == 60: @@ -269,6 +271,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, if tick >= 15 and startup_stall is None: assert state.canValid and not state.canTimeout if (parked_boot and 15 <= tick < 30) or (reverse_boot and 15 <= tick < (35 if reverse_unbraked else 40)): + assert card.aol_card_intent is not None assert not card.aol_card_intent.allowed_latch, 'VW_PARKED_START_CONSUMED_MAIN_ARM' if delayed_heartbeat and not startup_vetoes_checked: from copy import copy @@ -339,7 +342,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, if startup_floor_dip and getattr(card.aol_card_intent, 'startup_floor_pending', False) and not floor_vetoes_checked: assert_floor_recovery_vetoes(card, state, now) floor_vetoes_checked = True - if startup_probe_denials and not route2c_denials_checked and card.aol_card_intent.startup_ready: + if startup_probe_denials and not route2c_denials_checked and require_value(card.aol_card_intent).startup_ready: assert_readiness_denials(card, state, now) route2c_denials_checked = True intent = card.pm.messages['aolIntentWire'].as_builder() @@ -354,13 +357,16 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, 'companion': 'starpilotCarState' in card.pm.messages, 'timeout': stalled and startup_stall_mode == 'frozen-timeout'} if startup_stall is not None else {})) if rushed_start and 30 <= tick < 42: + assert card.aol_card_intent is not None assert not card.aol_card_intent.allowed_latch, 'VW_STARTUP_ARMED_BEFORE_HOST_READY' assert not command.latActive and not command.longActive if startup_floor_dip and state.vEgo <= cp.minSteerSpeed: assert not command.latActive and not command.longActive - if startup_floor_dip and command.latActive and not card.aol_card_intent.startup_granted: + if startup_floor_dip and command.latActive and not require_value(card.aol_card_intent).startup_granted: + assert card.aol_card_intent is not None assert now <= card.aol_card_intent.startup_arm_ns + 200_000_000 if brake_delivery_delay and 66 <= tick < 75: + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch assert command.latActive and not command.longActive if early_brake and tick == 60: @@ -371,6 +377,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, return assert log.OnroadEvent.EventName.controlsMismatch not in sd.events.names, 'VW_EARLY_BRAKE_STEERING_MISMATCH' assert not command.longActive + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch if brake_held_engagement and 22 <= tick < 29: assert state.standstill and state.brakePressed @@ -387,6 +394,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, from openpilot.starpilot.aol.wire import encode_safety feedback = card.aol_transport_feedback def retained(sources=card.sm, cs=state, latched=True, feedback=feedback, now=now): + assert feedback is not None return feedback._native_long_withdrawal_lateral_current(sources, card.CP, cs, sources['aolAxisState'], now, latched=latched, producer=card.slc_producer_session) proof = retained() @@ -413,29 +421,36 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, assert retained(sources=bad_sources) is not None cancel_join_vetoes_checked = True if cancel_axis_expiry and tick == 58: + assert card.aol_card_intent is not None assert not card.aol_card_intent.allowed_latch assert not command.latActive and not command.longActive return if cruise_cancel and 58 <= tick < 65: + assert card.aol_card_intent is not None + assert card.aol_transport_feedback is not None assert card.aol_card_intent.allowed_latch, ('VW_CANCEL_CLEARED_LATERAL_INTENT', tick, native_phase, card.aol_card_intent.latch_clear_reason, card.aol_transport_feedback.failed, card.aol_transport_feedback.signature, axis.to_dict(), list(sd.events.names)) assert command.latActive and permission & 1, 'VW_CANCEL_WITHDREW_LATERAL_PERMISSION' assert not command.longActive and not permission & 2, 'VW_CANCEL_RESTORED_LONG' if main_cycle and 62 <= tick < 65: + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch assert command.latActive, 'VW_MAIN_ON_REQUIRES_SET_AFTER_HEARTBEAT_WITHDRAWAL' assert not command.longActive if pq_eps_pause and 46 <= tick < 50: assert state.steerFaultTemporary and not command.latActive + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch if pq_eps_pause and 51 <= tick < 60: assert not command.latActive # Await the next genuine 10 Hz native acknowledgment. if pq_eps_pause and 62 <= tick < 65: + assert card.aol_card_intent is not None assert command.latActive and permission & 1, (tick, permission, request, state.to_dict(), axis.to_dict(), list(sd.events.names), card.aol_card_intent.allowed_latch, card.aol_card_intent._fault_inhibit) assert log.OnroadEvent.EventName.controlsMismatch not in sd.events.names if manual_speed_withdrawal and 50 <= tick < 65: + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch, 'VW_MANUAL_CRUISE_MINIMUM_CLEARED_AOL' assert command.latActive and not command.longActive if tick >= 112: @@ -443,6 +458,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, if stop_and_resume and 45 <= tick < 56: assert state.standstill and not command.latActive and not axis.desiredLateral, "VW_STOP_LATERAL_REQUEST_NOT_PAUSED" assert log.OnroadEvent.EventName.controlsMismatch not in sd.events.names, "VW_STOP_CONTROLS_MISMATCH" + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch if alpha and not cp.autoResumeSng: assert cp.minEnableSpeed > 0 and not command.longActive @@ -450,7 +466,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, assert axis.desiredLongitudinal and axis.longitudinalActive and command.longActive, ( "VW_STOP_LONG_DROPPED", tick, gearbox, alpha, permission, request, axis.to_dict(), list(sd.events.names)) if stop_and_resume and 60 <= tick < 65: - assert command.latActive and card.aol_card_intent.allowed_latch + assert command.latActive and require_value(card.aol_card_intent).allowed_latch request = int(axis.desiredLateral) | (int(axis.desiredLongitudinal) << 1) # Feed the exact serialized Controls publication into the actual Card caller. frames = [controls.pm.messages['carControl'], sd.pm.messages['aolAxisState'], @@ -499,6 +515,8 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, assert not quiet.safety_tx_hook(make_msg(bus - offset, addr, dat=data)) if receipt_sink is not None: native_wire = card.sm['aolSafetyWire'] + assert card.aol_card_intent is not None + assert card.aol_transport_feedback is not None receipt_sink.append({ 'tick': tick, 'now_ns': now, 'permission_mask': int(permission), 'host_request': request, 'card_stalled': stalled, 'published_car_state_ns': int(card.pm.messages['carState'].logMonoTime), @@ -537,8 +555,11 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, lat_commands.append(command.latActive) long_commands.append(command.longActive) if startup_stall is not None: + assert card.aol_card_intent is not None assert card.aol_card_intent.startup_arm_ns == 10_350_000_000 + assert card.aol_card_intent is not None assert card.aol_card_intent.startup_aborted + assert card.aol_card_intent is not None assert not card.aol_card_intent.allowed_latch return if delayed_heartbeat and not reverse_boot and alpha and gearbox == 'manual' and native_phase == 0: @@ -554,11 +575,12 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, assert not any(long_commands[:46]), 'Creep AOL must not enable longitudinal below its independent minimum' if startup_expect_expiry: assert not any(lat_commands[35:]) and not any(long_commands) - assert card.aol_card_intent.startup_aborted and not card.aol_card_intent.allowed_latch + assert require_value(card.aol_card_intent).startup_aborted and not require_value(card.aol_card_intent).allowed_latch return if rushed_start: assert any(lat_commands[43:75]) - elif reverse_boot and not startup_floor_dip and card.aol_card_intent.startup_drive_identity is not None: + elif reverse_boot and not startup_floor_dip and require_value(card.aol_card_intent).startup_drive_identity is not None: + assert card.aol_card_intent is not None arm_tick = (card.aol_card_intent.startup_arm_ns - 10_000_000_000) // 10_000_000 first_active = next((tick for tick, active in enumerate(lat_commands) if active), None) assert first_active is not None and max(45, arm_tick) <= first_active <= arm_tick + 20 diff --git a/openpilot/starpilot/aol/tests/test_panda_inventory.py b/openpilot/starpilot/aol/tests/test_panda_inventory.py index f68ad151fc..5e0e48f9a8 100644 --- a/openpilot/starpilot/aol/tests/test_panda_inventory.py +++ b/openpilot/starpilot/aol/tests/test_panda_inventory.py @@ -8,6 +8,7 @@ from unittest import mock import pytest +from openpilot.common.test import require_value from openpilot.cereal import custom, log, messaging from openpilot.common.prefix import OpenpilotPrefix from openpilot.selfdrive.car.tests.test_hyundai_aol import candidate @@ -283,8 +284,11 @@ class _Ev6CancelCaller: def intent(self, *, fault=False, active=False, now=None): now = self.last_now if now is None else now owner = self.card.aol_card_intent + assert owner is not None owner.observe_physical_samples(self.card.CI.CS, now_ns=now) + assert owner is not None owner.update(self.cs, now_ns=now, fault_active=fault, standard_enabled=active) + assert owner is not None owner.observe_full_engagement(self.cs, enabled=active, active=active, source_ns=now, observation_valid=True, now_ns=now, fault_active=fault) return owner @@ -298,6 +302,7 @@ class _Ev6CancelCaller: self.parse(Buttons.NONE) assert not self.intent().allowed_latch assert self.intent(active=True, now=self.last_now + 1).allowed_latch + assert self.card.aol_card_intent is not None assert self.card.aol_card_intent.physical.authorized def evidence(self, *, partial=False, lat_only=False, now=None, mutation=None, event=None): @@ -362,12 +367,13 @@ class _Ev6CancelCaller: self.evidence() assert not self.fault() feedback = self.card.aol_transport_feedback - assert feedback.session and feedback.lateral_baseline_ns and feedback.lateral_inventory + assert require_value(feedback).session and require_value(feedback).lateral_baseline_ns and require_value(feedback).lateral_inventory + assert self.card.aol_card_intent is not None assert self.card.aol_card_intent.allowed_latch def assert_no_exemption(self): feedback = self.card.aol_transport_feedback - assert not feedback.qualified and not feedback.awaiting and not feedback.paused + assert not require_value(feedback).qualified and not require_value(feedback).awaiting and not require_value(feedback).paused @pytest.mark.parametrize('order', ['wire_before_press', 'press_before_wire']) @@ -385,22 +391,26 @@ def test_ev6_cancel_real_card_async_orders_retain_only_existing_intent(order): caller.evidence() assert caller.card.aol_cancel_source(caller.cs, caller.last_now) > 0 assert not caller.fault() + assert caller.card.aol_transport_feedback is not None first = caller.card.aol_transport_feedback.longitudinal_cancel_ns assert first > 0 caller.assert_no_exemption() caller.parse(Buttons.NONE) caller.evidence(partial=True) assert not caller.fault() + assert caller.card.aol_transport_feedback is not None assert caller.card.aol_transport_feedback.longitudinal_cancel_ns == first - assert caller.card.aol_card_intent.allowed_latch and caller.card.aol_card_intent.output(caller.cs)[0] + assert require_value(caller.card.aol_card_intent).allowed_latch and require_value(caller.card.aol_card_intent).output(caller.cs)[0] assert not ordinary_axis_acknowledged(caller.card.sm, caller.cp, now_ns=caller.last_now) caller.parse() caller.evidence(lat_only=True) assert not caller.fault() assert ordinary_axis_acknowledged(caller.card.sm, caller.cp, now_ns=caller.last_now) assert not caller.native.requestedLongitudinal and not caller.native.longitudinalAllowed + assert caller.card.aol_transport_feedback is not None assert caller.card.aol_transport_feedback.longitudinal_cancel_ns == 0 caller.assert_no_exemption() + assert caller.card.aol_card_intent is not None assert caller.card.aol_card_intent.allowed_latch @@ -416,6 +426,7 @@ def test_ev6_cancel_rejects_changed_identity_and_continuity(mutation): caller.evidence(partial=True, mutation=mutation) assert caller.fault() caller.assert_no_exemption() + assert caller.card.aol_card_intent is not None assert not caller.card.aol_card_intent.allowed_latch @@ -434,6 +445,7 @@ def test_ev6_cancel_requires_current_parser_batch_and_two_clock_receipts(source) assert caller.card.aol_cancel_source(caller.cs, now) == 0 assert caller.fault() caller.assert_no_exemption() + assert caller.card.aol_card_intent is not None assert not caller.card.aol_card_intent.allowed_latch @@ -445,25 +457,31 @@ def test_ev6_cancel_deadline_cannot_be_renewed_by_duplicate_held_or_release(): caller.parse(Buttons.CANCEL) caller.evidence(partial=True) assert not caller.fault() + assert caller.card.aol_transport_feedback is not None first = caller.card.aol_transport_feedback.longitudinal_cancel_ns assert not caller.fault() # Identical Card observation is not a new occurrence. + assert caller.card.aol_transport_feedback is not None assert caller.card.aol_transport_feedback.longitudinal_cancel_ns == first for button in (Buttons.CANCEL, Buttons.NONE): caller.parse(button) caller.evidence(partial=True) assert not caller.fault() + assert caller.card.aol_transport_feedback is not None assert caller.card.aol_transport_feedback.longitudinal_cancel_ns == first # Fresh typed IPC keeps the independent 30ms baseline current. Explicit # input times exercise the deadline without a global clock override/sleep. for offset in range(20_000_000, 180_000_001, 20_000_000): caller.evidence(partial=True, now=first + offset) assert not caller.card.aol_disarming_fault(caller.cs, caller.last_now, caller.last_now) + assert caller.card.aol_transport_feedback is not None assert caller.card.aol_transport_feedback.longitudinal_cancel_ns == first caller.assert_no_exemption() + assert caller.card.aol_transport_feedback is not None assert first + 200_000_001 - caller.card.aol_transport_feedback.lateral_baseline_ns <= 30_000_000 caller.evidence(partial=True, now=first + 200_000_001) assert caller.fault() caller.assert_no_exemption() + assert caller.card.aol_card_intent is not None assert not caller.card.aol_card_intent.allowed_latch @@ -481,6 +499,7 @@ def test_ev6_cancel_lateral_and_hard_fault_vetoes_remain_closed(mutation): caller.evidence(partial=True, mutation=mutation) assert caller.fault() caller.assert_no_exemption() + assert caller.card.aol_card_intent is not None assert not caller.card.aol_card_intent.allowed_latch @@ -496,10 +515,11 @@ def test_ev6_cancel_needs_physical_occurrence_and_accepted_lateral_baseline(case caller.parse(Buttons.CANCEL if case == 'no_baseline' else Buttons.NONE) caller.evidence(partial=True) fault = caller.fault() + assert caller.card.aol_transport_feedback is not None assert caller.card.aol_transport_feedback.longitudinal_cancel_ns == 0 caller.assert_no_exemption() if case == 'non_cancel': - assert fault and not caller.card.aol_card_intent.allowed_latch + assert fault and not require_value(caller.card.aol_card_intent).allowed_latch assert not caller.native.longitudinalAllowed @@ -514,6 +534,7 @@ def test_ev6_cancel_never_exempts_controls_mismatch_or_critical_events(event): caller.evidence(partial=True, event=event) assert caller.fault() caller.assert_no_exemption() + assert caller.card.aol_card_intent is not None assert not caller.card.aol_card_intent.allowed_latch diff --git a/openpilot/starpilot/aol/tests/test_seatbelt_cold_start.py b/openpilot/starpilot/aol/tests/test_seatbelt_cold_start.py index 0579fe5ae8..b7f2784e9a 100644 --- a/openpilot/starpilot/aol/tests/test_seatbelt_cold_start.py +++ b/openpilot/starpilot/aol/tests/test_seatbelt_cold_start.py @@ -8,6 +8,7 @@ import pytest from opendbc.car.hyundai.interface import CarInterface from opendbc.car.hyundai.radar_interface import RadarInterface from opendbc.car.structs import car +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix @@ -68,13 +69,18 @@ def factory_callers(cleanup, full_op, *, pause_brake_mps=0., arm=True): assert sd.CP.as_builder().to_bytes() == card.CP.as_reader().as_builder().to_bytes() state = fixture.car_state() state.cruiseState.available, state.seatbeltUnlatched = True, True + assert card.aol_card_intent is not None assert not card.aol_card_intent.allowed_latch if arm: + assert card.aol_card_intent is not None card.aol_card_intent.update(state, now_ns=9_980_000_000) state.buttonEvents = [car.CarState.ButtonEvent(type=car.CarState.ButtonEvent.Type.lkas, pressed=True)] + assert card.aol_card_intent is not None card.aol_card_intent.update(state, now_ns=9_990_000_000) + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch state.buttonEvents = [car.CarState.ButtonEvent(type=car.CarState.ButtonEvent.Type.lkas, pressed=False)] + assert card.aol_card_intent is not None card.aol_card_intent.update(state, now_ns=9_999_000_000) state.buttonEvents = [] class Publisher: @@ -88,6 +94,7 @@ def factory_callers(cleanup, full_op, *, pause_brake_mps=0., arm=True): observed = kwargs['observed_state'] now = 10_000_000_000 + tick * 10_000_000 if 'latched' in kwargs: + assert card.aol_card_intent is not None assert kwargs['latched'] == card.aol_card_intent.allowed_latch def stamped_message(*args, **options): options.setdefault('logMonoTime', now) @@ -99,7 +106,7 @@ def factory_callers(cleanup, full_op, *, pause_brake_mps=0., arm=True): intent = decode_intent(actual.aolIntentWire) assert actual.valid and intent.producerSessionId == card.slc_producer_session assert intent.carStateLogMonoTime == card.pm.messages['carState'].logMonoTime == now - assert intent.settingsQualified and intent.lateralArmed == card.aol_card_intent.allowed_latch + assert intent.settingsQualified and intent.lateralArmed == require_value(card.aol_card_intent).allowed_latch kwargs['intent_message'] = actual return drive(tick, **kwargs) return card, sd, controls, published_drive, state diff --git a/openpilot/starpilot/aol/tests/test_seatbelt_lateral.py b/openpilot/starpilot/aol/tests/test_seatbelt_lateral.py index 2e40805d51..630b8827fe 100644 --- a/openpilot/starpilot/aol/tests/test_seatbelt_lateral.py +++ b/openpilot/starpilot/aol/tests/test_seatbelt_lateral.py @@ -154,12 +154,17 @@ def test_actual_ioniq_first_unbuckled_admission_needs_no_buckled_baseline(): state = car_state() state.cruiseState.available = True state.seatbeltUnlatched = True + assert card.aol_card_intent is not None assert not card.aol_card_intent.allowed_latch + assert card.aol_card_intent is not None card.aol_card_intent.update(state, now_ns=9_990_000_000) state.buttonEvents = [car.CarState.ButtonEvent(type=car.CarState.ButtonEvent.Type.lkas, pressed=True)] + assert card.aol_card_intent is not None card.aol_card_intent.update(state, now_ns=10_000_000_000) + assert card.aol_card_intent is not None assert card.aol_card_intent.allowed_latch state.buttonEvents = [] + assert card.aol_card_intent is not None axis, _, command = drive(0, observed_state=state, latched=card.aol_card_intent.allowed_latch, native_request_long=False) assert axis.faultReason == 'none' and axis.lateralActive and command.latActive diff --git a/openpilot/starpilot/aol/tests/test_sonata_cruise_only_withdrawal.py b/openpilot/starpilot/aol/tests/test_sonata_cruise_only_withdrawal.py index 9470e1b7b7..0c2f5bc2c1 100644 --- a/openpilot/starpilot/aol/tests/test_sonata_cruise_only_withdrawal.py +++ b/openpilot/starpilot/aol/tests/test_sonata_cruise_only_withdrawal.py @@ -15,6 +15,7 @@ from opendbc.car.hyundai.values import CAR from opendbc.car.hyundai.classic_scc_aol import qualified as qualified_classic from opendbc.safety.tests.libsafety import libsafety_py from opendbc.safety.tests.test_hyundai import checksum +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix @@ -349,7 +350,7 @@ def test_cruise_only_withdrawal_keeps_authorized_aol(raw_fault, withdrawal, monk brake=withdrawal == 'brake', button=4 if withdrawal == 'cruise-cancel' and index < 2 else 0) observations.append({'cruise_enabled': state.cruiseState.enabled, 'main_available': state.cruiseState.available, 'brake': state.brakePressed, 'buttons': [event.to_dict() for event in state.buttonEvents], - 'native_before_allowed': last_native[0].lateralAllowed, 'native_before_requested': last_native[0].requestedLateral, + 'native_before_allowed': require_value(last_native[0]).lateralAllowed, 'native_before_requested': require_value(last_native[0]).requestedLateral, 'native_controls': native.get_controls_allowed(), 'native_after_mask': native.aol_get_permission_mask(), 'axis': axis.to_dict(), 'command_lat': command.latActive, 'command_long': command.longActive, 'intent_allowed': card.aol_card_intent.allowed_latch, 'fault_rearm': card.aol_card_intent.fault_rearm, diff --git a/openpilot/starpilot/aol/tests/test_sonata_mapped_button_callers.py b/openpilot/starpilot/aol/tests/test_sonata_mapped_button_callers.py index 1e2d5a981c..bf95d36c75 100644 --- a/openpilot/starpilot/aol/tests/test_sonata_mapped_button_callers.py +++ b/openpilot/starpilot/aol/tests/test_sonata_mapped_button_callers.py @@ -15,6 +15,7 @@ from opendbc.car.hyundai.values import CAR from opendbc.car.hyundai.classic_scc_aol import qualified as qualified_classic from opendbc.safety.tests.libsafety import libsafety_py from opendbc.safety.tests.test_hyundai import checksum +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix @@ -357,7 +358,7 @@ def test_main_then_lkas_toggle_runs_real_parser_card_native_and_commands(raw_fau brake=withdrawal == 'brake', button=4 if withdrawal == 'cruise-cancel' and index < 2 else 0) observations.append({'cruise_enabled': state.cruiseState.enabled, 'main_available': state.cruiseState.available, 'brake': state.brakePressed, 'buttons': [event.to_dict() for event in state.buttonEvents], - 'native_before_allowed': last_native[0].lateralAllowed, 'native_before_requested': last_native[0].requestedLateral, + 'native_before_allowed': require_value(last_native[0]).lateralAllowed, 'native_before_requested': require_value(last_native[0]).requestedLateral, 'native_controls': native.get_controls_allowed(), 'native_after_mask': native.aol_get_permission_mask(), 'axis': axis.to_dict(), 'command_lat': command.latActive, 'command_long': command.longActive, 'intent_allowed': card.aol_card_intent.allowed_latch, 'fault_rearm': card.aol_card_intent.fault_rearm, diff --git a/openpilot/starpilot/aol/tests/test_sonata_temporary_withdrawals.py b/openpilot/starpilot/aol/tests/test_sonata_temporary_withdrawals.py index c1e3d73720..503052cecd 100644 --- a/openpilot/starpilot/aol/tests/test_sonata_temporary_withdrawals.py +++ b/openpilot/starpilot/aol/tests/test_sonata_temporary_withdrawals.py @@ -15,6 +15,7 @@ from opendbc.car.hyundai.values import CAR from opendbc.car.hyundai.classic_scc_aol import qualified as qualified_classic from opendbc.safety.tests.libsafety import libsafety_py from opendbc.safety.tests.test_hyundai import checksum +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix @@ -405,7 +406,7 @@ def test_classic_stock_temporary_withdrawal_recovers_with_real_cpp( brake=withdrawal == 'brake', button=4 if withdrawal == 'cruise-cancel' and index < 2 else 0) observations.append({'cruise_enabled': state.cruiseState.enabled, 'main_available': state.cruiseState.available, 'brake': state.brakePressed, 'buttons': [event.to_dict() for event in state.buttonEvents], - 'native_before_allowed': last_native[0].lateralAllowed, 'native_before_requested': last_native[0].requestedLateral, + 'native_before_allowed': require_value(last_native[0]).lateralAllowed, 'native_before_requested': require_value(last_native[0]).requestedLateral, 'native_controls': native.get_controls_allowed(), 'native_after_mask': native.aol_get_permission_mask(), 'axis': axis.to_dict(), 'command_lat': command.latActive, 'command_long': command.longActive, 'intent_allowed': card.aol_card_intent.allowed_latch, 'fault_rearm': card.aol_card_intent.fault_rearm, diff --git a/openpilot/starpilot/aol/tests/test_toyota.py b/openpilot/starpilot/aol/tests/test_toyota.py index e4e32348b8..87ab6caa95 100644 --- a/openpilot/starpilot/aol/tests/test_toyota.py +++ b/openpilot/starpilot/aol/tests/test_toyota.py @@ -333,6 +333,8 @@ class TestHighlanderAol(unittest.TestCase): self.assertTrue(sd.aol_replay) state = structs.CarState(canValid=True, gearShifter=structs.CarState.GearShifter.drive) state.cruiseState.available = True + assert selected.aol_card_intent is not None selected.aol_card_intent.update(state.as_reader()) + assert selected.aol_card_intent is not None self.assertEqual(selected.aol_card_intent.allowed_latch, enabled) del controls, sd, selected diff --git a/openpilot/starpilot/aol/tests/test_transition_diagnostic.py b/openpilot/starpilot/aol/tests/test_transition_diagnostic.py index c21e65a291..7ed638d962 100644 --- a/openpilot/starpilot/aol/tests/test_transition_diagnostic.py +++ b/openpilot/starpilot/aol/tests/test_transition_diagnostic.py @@ -219,8 +219,10 @@ def test_declared_proofs_with_controlled_schedule(schedule): assert updates == [guard] * expected_updates assert axis_checks[0]['accepted'] == (schedule not in ('cross_no_pending', 'expired_empty')) diagnostic = controls.aol_transition_diagnostic + assert diagnostic is not None assert (diagnostic.pending is None) == expected if not expected: + assert diagnostic is not None assert isinstance(diagnostic.pending, tuple) order = [] headers = [] @@ -281,7 +283,9 @@ def test_declared_proofs_with_controlled_schedule(schedule): with patch.object(controlsd.time, 'monotonic_ns', return_value=now[0]): repeated, _ = controls.state_control() assert not repeated.latActive and diagnostic.pending is None + assert diagnostic is not None assert diagnostic.emitted == 1 + assert diagnostic is not None assert diagnostic.pending is None diff --git a/openpilot/starpilot/aol/tests/test_vehicle_policy_cache.py b/openpilot/starpilot/aol/tests/test_vehicle_policy_cache.py index 09f13ca27d..1002d14658 100644 --- a/openpilot/starpilot/aol/tests/test_vehicle_policy_cache.py +++ b/openpilot/starpilot/aol/tests/test_vehicle_policy_cache.py @@ -6,7 +6,7 @@ from unittest.mock import Mock, patch import warnings import pytest -from capnp import KjException +from capnp.lib.capnp import KjException from opendbc.car import gen_empty_fingerprint, structs from opendbc.car.car_helpers import interfaces diff --git a/openpilot/starpilot/aol/transport_pause_session.py b/openpilot/starpilot/aol/transport_pause_session.py index 0075e9eaf7..2c835e428e 100644 --- a/openpilot/starpilot/aol/transport_pause_session.py +++ b/openpilot/starpilot/aol/transport_pause_session.py @@ -49,7 +49,7 @@ class TransportPause: return False, False return True, False if (eligible and expired_healthy_source and previously_active and previous is not None and - previous.allowedLatch and previous.lateralArmed and raw.allowedLatch and raw.lateralArmed and + previous.allowedLatch and previous.lateralArmed and raw is not None and raw.allowedLatch and raw.lateralArmed and not user_disable): self.active = True self.producer = producer diff --git a/openpilot/starpilot/audio/tests/test_complete_alert_assets.py b/openpilot/starpilot/audio/tests/test_complete_alert_assets.py index ae9cb58fe5..cc472b99fd 100644 --- a/openpilot/starpilot/audio/tests/test_complete_alert_assets.py +++ b/openpilot/starpilot/audio/tests/test_complete_alert_assets.py @@ -10,7 +10,7 @@ from openpilot.starpilot.audio.sound_pack import BUILTIN_FILES, SoundPackLoader, def production_filenames(): source = Path(__file__).resolve().parents[3] / 'selfdrive/ui/soundd.py' tree = ast.parse(source.read_text()) - sounds = next(node for node in tree.body if isinstance(node, ast.AnnAssign) and node.target.id == 'sound_list') + sounds = next(node for node in tree.body if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == 'sound_list') return tuple(dict.fromkeys(value.elts[0].value for value in sounds.value.values)) diff --git a/openpilot/starpilot/bluetooth/tests/test_accept_pair.py b/openpilot/starpilot/bluetooth/tests/test_accept_pair.py index 4999f77c9b..9b46bba5a0 100644 --- a/openpilot/starpilot/bluetooth/tests/test_accept_pair.py +++ b/openpilot/starpilot/bluetooth/tests/test_accept_pair.py @@ -231,6 +231,7 @@ class AcceptPairOwnerTest(unittest.TestCase): self.owner.request(operation, session=self.identity) self.assertEqual(raised.exception.code, 'busy') FakeWindowBlueZ.bonded.set() + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(2)) self.assertEqual(self.paired, [('11:22:33:44:55:66', 'Pixel', (A2DP_SOURCE,))]) self.assertEqual(self.owner.snapshot(session=self.identity)['pairing']['state'], 'paired') @@ -277,6 +278,7 @@ class AcceptPairOwnerTest(unittest.TestCase): self.owner.request('accept_pair', session=self.identity) self.wait_for_claim() self.owner.request('cancel_pair', session=self.identity) + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(2)) self.assertEqual(self.paired, []) @@ -288,6 +290,7 @@ class AcceptPairOwnerTest(unittest.TestCase): self.assertEqual(FakeWindowBlueZ.instances[0].visibility, [('/org/bluez/hci0', True, False)]) self.assertTrue(isinstance(self.owner.pairing, OpenPairingSession)) self.owner.request('cancel_pair', session=self.identity) + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(2)) self.assertFalse(journal.exists()) @@ -298,6 +301,7 @@ class AcceptPairOwnerTest(unittest.TestCase): self.wait_for_claim() self.assertEqual(FakeWindowBlueZ.instances[0].visibility, []) self.owner.request('cancel_pair', session=self.identity) + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(2)) self.assertFalse(journal.exists()) diff --git a/openpilot/starpilot/bluetooth/tests/test_owner.py b/openpilot/starpilot/bluetooth/tests/test_owner.py index a56bccf70a..d685973b1e 100644 --- a/openpilot/starpilot/bluetooth/tests/test_owner.py +++ b/openpilot/starpilot/bluetooth/tests/test_owner.py @@ -41,7 +41,12 @@ class FakeBlueZ: return None def _devices(self, _objects): - return [dict(device, path='/org/bluez/hci0/dev_' + device['address'].replace(':', '_')) for device in self.devices] + devices = [] + for device in self.devices: + address = device['address'] + assert isinstance(address, str) + devices.append(dict(device, path='/org/bluez/hci0/dev_' + address.replace(':', '_'))) + return devices def pair(self, address, path, session): self.operations.append(('pair', address)) @@ -152,6 +157,7 @@ class BluetoothOwnerTest(unittest.TestCase): with self.assertRaises(BluetoothRejected): self.owner.request('pairing_response', session=('wrong', b'generation'), prompt_id=prompt['id'], accepted=True) self.owner.request('pairing_response', session=identity, prompt_id=prompt['id'], accepted=True) + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(1)) self.assertTrue(FakeBlueZ.devices[-1]['paired']) FakeBlueZ.devices[-1]['paired'] = False @@ -162,7 +168,9 @@ class BluetoothOwnerTest(unittest.TestCase): self.assertEqual(self.owner.snapshot(session=identity)['pairing']['state'], 'pairing') self.owner.session_valid = lambda _identity: False self.owner.snapshot(session=identity) + assert pairing is not None self.assertTrue(pairing.done.wait(1)) + assert pairing is not None self.assertEqual(pairing.state, 'canceled') self.assertFalse(FakeBlueZ.devices[-1]['paired']) @@ -431,17 +439,21 @@ class BluetoothOwnerTest(unittest.TestCase): self.assertEqual(FakeBlueZ.closed, 0) self.assertEqual(FakeBlueZ.operations, [('scan', None)]) timer = self.owner.scan_timer + assert timer is not None self.assertTrue(timer.daemon) now[0] = 29.0 self.owner.snapshot() self.assertEqual(FakeBlueZ.closed, 0) now[0] = 30.0 + assert timer is not None timer.fire() self.assertEqual(FakeBlueZ.operations[-1], ('stop_scan', None)) self.owner.request('scan') old_timer = self.owner.scan_timer self.owner.request('scan') + assert old_timer is not None self.assertTrue(old_timer.cancelled) + assert old_timer is not None old_timer.fire() self.assertEqual(FakeBlueZ.operations[-1], ('scan', None)) self.owner.close() @@ -453,6 +465,7 @@ class BluetoothOwnerTest(unittest.TestCase): self.owner.snapshot() self.assertEqual(FakeBlueZ.operations[-1], ('scan', None)) now[0] += self.owner.SCAN_SECONDS + assert self.owner.scan_timer is not None self.owner.scan_timer.fire() self.assertEqual(FakeBlueZ.operations[-1], ('stop_scan', None)) @@ -543,6 +556,7 @@ class BluetoothOwnerTest(unittest.TestCase): with self.assertRaises(BluetoothRejected): self.owner.request('pairing_response', session=identity, prompt_id='0' * 32, accepted=True) self.owner.request('pairing_response', session=identity, prompt_id=prompt['id'], accepted=True) + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(1)) result = self.owner.snapshot(session=identity) self.assertEqual(result['pairing']['state'], 'paired') @@ -556,6 +570,7 @@ class BluetoothOwnerTest(unittest.TestCase): self.owner.cancel_session(('other', b'generation')) self.assertEqual(self.owner.snapshot(session=identity)['pairing']['state'], 'pairing') self.owner.cancel_session(identity) + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(1)) self.assertEqual(self.owner.snapshot(session=identity)['pairing']['state'], 'canceled') self.assertFalse(FakeBlueZ.devices[-1]['paired']) @@ -563,7 +578,9 @@ class BluetoothOwnerTest(unittest.TestCase): self.owner.request('pair', address='11:22:33:44:55:66', session=identity) self.owner.session_valid = lambda _identity: False self.owner.snapshot(session=identity) + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(1)) + assert self.owner.pairing is not None self.assertEqual(self.owner.pairing.state, 'canceled') def test_radio_loss_cancels_pending_pair_even_without_followup_action(self): @@ -574,7 +591,9 @@ class BluetoothOwnerTest(unittest.TestCase): pairing = self.owner.pairing self.helper.unlink() self.assertEqual(self.owner.snapshot(session=identity)['errorCode'], 'radio_unavailable') + assert pairing is not None self.assertTrue(pairing.done.wait(1)) + assert pairing is not None self.assertEqual(pairing.state, 'canceled') self.assertFalse(FakeBlueZ.devices[-1]['paired']) @@ -587,7 +606,9 @@ class BluetoothOwnerTest(unittest.TestCase): self.owner.request('pair', address='11:22:33:44:55:66', session=identity) pairing = self.owner.pairing valid[0] = False + assert pairing is not None self.assertTrue(pairing.done.wait(1)) + assert pairing is not None self.assertEqual(pairing.state, 'canceled') self.assertFalse(FakeBlueZ.devices[-1]['paired']) @@ -600,7 +621,9 @@ class BluetoothOwnerTest(unittest.TestCase): self.owner.request('pair', address='11:22:33:44:55:66', session=identity) pairing = self.owner.pairing now[0] = 71.0 + assert pairing is not None self.assertTrue(pairing.done.wait(1)) + assert pairing is not None self.assertEqual(pairing.state, 'canceled') self.assertFalse(FakeBlueZ.devices[-1]['paired']) diff --git a/openpilot/starpilot/car/ford/bluepilot.py b/openpilot/starpilot/car/ford/bluepilot.py index 7328133b4a..14e430229e 100644 --- a/openpilot/starpilot/car/ford/bluepilot.py +++ b/openpilot/starpilot/car/ford/bluepilot.py @@ -226,10 +226,10 @@ class FordBluePilotController(BluePilotLateral): measured = self.inputs.get_current_curvature(CS) self.last_measured_curvature = measured if math.isfinite(measured) else 0.0 self.lateral_active = bool(CC.latActive) - if self.starpilot_selected and (not self.starpilot_frame_valid or not self.angle.inputs_valid(CS, actuators)): - CC = structs.CarControl.new_message(latActive=False) if self.starpilot_selected: angle = cast("StarPilotFordController", self.angle) + if not self.starpilot_frame_valid or not angle.inputs_valid(CS, actuators): + CC = structs.CarControl.new_message(latActive=False) angle.native_curvature_bounds = None if self.measured_seen and CS.out.vEgoRaw > 10.: if self.native_pinion_model is not None: diff --git a/openpilot/starpilot/car/honda/tests/test_bosch_a_integration.py b/openpilot/starpilot/car/honda/tests/test_bosch_a_integration.py index 1a1c9e5ed2..ddb0873817 100644 --- a/openpilot/starpilot/car/honda/tests/test_bosch_a_integration.py +++ b/openpilot/starpilot/car/honda/tests/test_bosch_a_integration.py @@ -8,6 +8,7 @@ from opendbc.car.honda.interface import CarInterface from opendbc.car.honda.radar_interface import RadarInterface from opendbc.car.honda.tests.test_bosch_a_radar import sweep, make_f0, make_aux from opendbc.car.honda.values import CAR +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.selfdrive.controls.radard import RadarD from openpilot.starpilot.car.honda.tests.test_radar_pipeline import source_tick @@ -50,6 +51,7 @@ def test_decoder_coast_and_floor_keep_geometry_without_kalman_measurements(ident source_tick(sm, i, rr, speed=20, probability=0.99, distance=50) radar.update(sm, sm['radarTracks']) assert track.cnt == count and track.kf.x == state and not track.measured + assert radar.radar_state is not None assert radar.radar_state.leadOne.radar rr = decoder.update([(3_000_000_000, [])]) source_tick(sm, 20, rr, speed=20) @@ -73,7 +75,9 @@ def test_floor_born_stopped_object_uses_closing_range_fit_in_planner_lead(identi track = radar.tracks[1] assert point.vRel < -19.5 and not point.deprecated.measured assert track.cnt == 0 and not track.measured + assert radar.radar_state is not None assert radar.radar_state.leadOne.radar + assert radar.radar_state is not None assert radar.radar_state.leadOne.vLeadK < 0.5 assert track.kf.x[0][0] == 8.0 from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import LongitudinalMpc @@ -130,9 +134,10 @@ def test_sustained_rejections_bound_history_without_changing_points(identity, re decoder = RadarInterface(cp) for batch, original in zip(batches, expected, strict=True): assert decoder.update(batch).to_bytes() == original + assert decoder.bosch_a is not None track = decoder.bosch_a._tracks[1] run = track.rejected_run if rejected_range else track.inconsistent_run - original_run = reference.bosch_a._tracks[1].rejected_run if rejected_range else reference.bosch_a._tracks[1].inconsistent_run + original_run = require_value(reference.bosch_a)._tracks[1].rejected_run if rejected_range else require_value(reference.bosch_a)._tracks[1].inconsistent_run assert len(original_run) > 250 assert len(run) <= 2 + max(decoder_module.BOSCH_A_REANCHOR_WINDOW, math.ceil(BOSCH_A_FREQ_HZ * decoder_module.BOSCH_A_COAST_FIT_WINDOW_S)) assert run[0] == original_run[0] diff --git a/openpilot/starpilot/car/honda/tests/test_radar_pipeline.py b/openpilot/starpilot/car/honda/tests/test_radar_pipeline.py index daaf16f438..d2cbd1904a 100644 --- a/openpilot/starpilot/car/honda/tests/test_radar_pipeline.py +++ b/openpilot/starpilot/car/honda/tests/test_radar_pipeline.py @@ -9,6 +9,7 @@ from opendbc.car.honda.interface import CarInterface from opendbc.car.honda.radar_interface import RadarInterface from opendbc.car.honda.tests.test_bosch_a_radar import make_f0, sweep from opendbc.car.honda.values import CAR +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.selfdrive.controls.radard import RadarD @@ -95,8 +96,10 @@ def test_actual_decoder_radard_maturity_stale_retirement_and_recovery(identity): source_tick(sm, index, rr) radar.update(sm, sm['radarTracks']) if index < 3: + assert radar.radar_state is not None assert not radar.radar_state.leadOne.present - assert radar.radar_state.leadOne.present and radar.radar_state.leadOne.radar + assert require_value(radar.radar_state).leadOne.present and require_value(radar.radar_state).leadOne.radar + assert radar.radar_state is not None assert radar.radar_state.leadOne.radarTrackId == 1 stale = decoder.update([(1_500_000_000, [])]) assert stale.errors.radarUnavailableTemporary and not stale.points diff --git a/openpilot/starpilot/car/mazda/stock_intent.py b/openpilot/starpilot/car/mazda/stock_intent.py index b4ea9dd4b4..5fd43e767e 100644 --- a/openpilot/starpilot/car/mazda/stock_intent.py +++ b/openpilot/starpilot/car/mazda/stock_intent.py @@ -57,7 +57,7 @@ class MazdaStockCardIntent(AolCardIntent): now_ns - axis.sourceCarStateMonoTime <= AXIS_MAX_AGE_NS) except (AttributeError, KeyError, TypeError, ValueError, OverflowError): self.startup_native_ready = False - if self.startup_native_ready: + if self.startup_native_ready and native is not None: binding = (str(axis.sessionId), producer, int(axis.intentIntegrityEpoch), native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory)) if binding != self.startup_binding: diff --git a/openpilot/starpilot/car/rivian/tests/test_aol_lifecycle.py b/openpilot/starpilot/car/rivian/tests/test_aol_lifecycle.py index 8546d37cf2..69fecd0c87 100644 --- a/openpilot/starpilot/car/rivian/tests/test_aol_lifecycle.py +++ b/openpilot/starpilot/car/rivian/tests/test_aol_lifecycle.py @@ -175,6 +175,7 @@ def test_actual_rivian_aol_engage_brake_reverse_fault_recovery(alpha, monkeypatc # This conveys no actuator request and cannot arm a native token. if prior_axis is not None and armed is not None: axis = prior_axis.aolAxisState + assert prior_intent is not None stamp = int(prior_intent.logMonoTime) retained = bool(armed.settingsQualified and armed.lateralArmed and armed.producerSessionId == axis.intentProducerSessionId and @@ -274,6 +275,7 @@ def test_actual_rivian_aol_engage_brake_reverse_fault_recovery(alpha, monkeypatc for frame in received['sendcan'].sendcan: tx.append(bool(safety.safety_tx_hook(make_msg(frame.src, frame.address, dat=frame.dat)))) assert all(tx) + assert card.aol_card_intent is not None row = { 'tick': tick, 'feature': feature, diff --git a/openpilot/starpilot/car/subaru/tests/pandad_order.py b/openpilot/starpilot/car/subaru/tests/pandad_order.py index faa011baa0..84f7aa735a 100644 --- a/openpilot/starpilot/car/subaru/tests/pandad_order.py +++ b/openpilot/starpilot/car/subaru/tests/pandad_order.py @@ -24,8 +24,11 @@ class PandadOrder: def exchange(self, line): assert self.process.poll() is None + assert self.process.stdin is not None self.process.stdin.write(line + '\n') + assert self.process.stdin is not None self.process.stdin.flush() + assert self.process.stdout is not None result = self.process.stdout.readline().strip().split() assert result, self.process.poll() return result @@ -93,8 +96,10 @@ class PandadOrder: return wire, {'before': before, 'plan': (capable, request, retain), 'heartbeat': self.heartbeat, 'after': after, 'session': session} def close(self): + assert self.process.stdin is not None self.process.stdin.close() try: assert self.process.wait(timeout=10) == 0 finally: + assert self.process.stdout is not None self.process.stdout.close() diff --git a/openpilot/starpilot/car/subaru/tests/test_smoothing_model_join.py b/openpilot/starpilot/car/subaru/tests/test_smoothing_model_join.py index 0a6fd030ee..b2e36150ce 100644 --- a/openpilot/starpilot/car/subaru/tests/test_smoothing_model_join.py +++ b/openpilot/starpilot/car/subaru/tests/test_smoothing_model_join.py @@ -1,5 +1,6 @@ """Execute the production common action join with each installed action owner.""" import ast +from capnp.lib.capnp import _DynamicStructBuilder, _DynamicStructReader from pathlib import Path from types import SimpleNamespace import math @@ -58,6 +59,7 @@ def test_actual_common_join_once_and_acceleration_unchanged(owner, tau, kona_tau 'lat_action_t': .2, 'long_action_t': .2, 'v_ego': 2., 'subaru_tau': tau, 'volkswagen_tau': 0., 'kona_tau': kona_tau, 'filter_action': filter_action} exec(common_join(), scope) action = scope['action'] + assert isinstance(action, (_DynamicStructBuilder, _DynamicStructReader)) total_tau = tau + kona_tau alpha = 1. - math.exp(-.05 / total_tau) if total_tau > 0. else 1. expected = alpha * baseline.desiredCurvature + (1. - alpha) * previous.desiredCurvature diff --git a/openpilot/starpilot/car/tesla/tests/test_radar_pipeline.py b/openpilot/starpilot/car/tesla/tests/test_radar_pipeline.py index 4c6ab303e1..93bc2b5515 100644 --- a/openpilot/starpilot/car/tesla/tests/test_radar_pipeline.py +++ b/openpilot/starpilot/car/tesla/tests/test_radar_pipeline.py @@ -1,6 +1,7 @@ from opendbc.can import CANPacker from opendbc.car import structs from opendbc.car.tesla.tests.test_preap_radar import frames, radar_params, radar_interface +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.selfdrive.controls.radard import RadarD @@ -64,13 +65,14 @@ def test_actual_preap_decoder_to_radard_tracks_errors_retirement_and_recovery(): source_tick(sm, 31, speed=10.0, probability=1.0, distance=30.0) radar.update(sm, sm["radarTracks"]) assert radar.tracks[identifier].cnt == count + 1 - assert radar.radar_state.leadOne.present and radar.radar_state.leadOne.radar + assert require_value(radar.radar_state).leadOne.present and require_value(radar.radar_state).leadOne.radar trigger = packer.make_can_msg("RadarPoint31_B", 1, {"Index2": 0}) for step in range(5): rr = decoder.update([(4_000_000_000 + step * 125_000_000, [trigger])]) with structs.RadarData.from_bytes(rr.to_bytes()) as decoded: source_tick(sm, 70, decoded) radar.update(sm, sm["radarTracks"]) + assert radar.radar_state is not None assert radar.radar_state.radarErrors.canError rr = decoder.update([(4_625_000_000, frames(packer, fault=True, index=1))]) with structs.RadarData.from_bytes(rr.to_bytes()) as decoded: diff --git a/openpilot/starpilot/car/tesla/tests/test_speed_sync_context.py b/openpilot/starpilot/car/tesla/tests/test_speed_sync_context.py index 10f77dfd3c..d5b0b6ed6f 100644 --- a/openpilot/starpilot/car/tesla/tests/test_speed_sync_context.py +++ b/openpilot/starpilot/car/tesla/tests/test_speed_sync_context.py @@ -395,6 +395,7 @@ def test_the_real_controller_scrolls_only_with_cards_admission(tmp_path, model): for _ in range(frames): now = time.clock_gettime_ns(time.CLOCK_BOOTTIME) counter = (counter + 1) % 16 + assert controller.speed_sync is not None controller.speed_sync.observe([(now, [(0x286, di_frame(counter, 50, 0), 0), (0x3C2, NEUTRAL, 1)])]) if admit: publish_context(card, cs.out) diff --git a/openpilot/starpilot/car/toyota/tests/test_legacy_radar_pre_warning.py b/openpilot/starpilot/car/toyota/tests/test_legacy_radar_pre_warning.py index db38ab85c9..3f84bbefd9 100644 --- a/openpilot/starpilot/car/toyota/tests/test_legacy_radar_pre_warning.py +++ b/openpilot/starpilot/car/toyota/tests/test_legacy_radar_pre_warning.py @@ -8,6 +8,7 @@ from opendbc.car import Bus, gen_empty_fingerprint from opendbc.car.toyota.interface import CarInterface from opendbc.car.toyota.radar_interface import RadarInterface from opendbc.car.toyota.values import CAR, DBC +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.common.prefix import OpenpilotPrefix from openpilot.starpilot.aol.tests import test_ioniq_availability as fixture @@ -55,6 +56,7 @@ def test_legacy_ready_radar_pre_warning_keeps_live_measurements(candidate, alpha radar = RadarInterface(cp) packer = CANPacker(DBC[cp.carFingerprint][Bus.radar]) result = feed(radar, packer, counter=counter, target=target) + assert radar.rcp is not None assert radar.rcp.can_valid assert not result.errors.radarUnavailableTemporary, 'LEGACY_RADAR_PRE_WARNING' assert not result.errors.canError @@ -90,7 +92,7 @@ def test_real_radar_faults_and_receive_checks_remain(profile, condition): result = feed(radar, packer, **options) assert result.errors.canError or result.errors.radarUnavailableTemporary if condition.startswith('missing'): - assert result.errors.canError and not radar.rcp.can_valid + assert result.errors.canError and not require_value(radar.rcp).can_valid else: assert result.errors.radarUnavailableTemporary diff --git a/openpilot/starpilot/car/toyota/tests/test_rav4h_caller_native.py b/openpilot/starpilot/car/toyota/tests/test_rav4h_caller_native.py index 7b847d69bd..4144e23ff1 100644 --- a/openpilot/starpilot/car/toyota/tests/test_rav4h_caller_native.py +++ b/openpilot/starpilot/car/toyota/tests/test_rav4h_caller_native.py @@ -507,6 +507,7 @@ def run_case(stock, scenario='nominal', *, aol=True, candidate=CAR.TOYOTA_RAV4H, native_tx_accepted += int(accepted_tx) native_tx_rejected += int(not accepted_tx) if accepted_tx != expected_tx: + assert outgoing is not None refusal = {'tick': tick, 'candidate': str(candidate), 'scenario': scenario, 'address': f.address, 'data': bytes(f.dat).hex(), 'bus': f.src, 'outgoingValid': bool(outgoing.valid), 'CP': host.CP.to_dict(), 'CS': cs.to_dict(), 'CC': cc.to_dict(), 'beforeNativeTX': before_tx, diff --git a/openpilot/starpilot/conditional_mode/host.py b/openpilot/starpilot/conditional_mode/host.py index 0db44ce6fa..03d0c18f4e 100644 --- a/openpilot/starpilot/conditional_mode/host.py +++ b/openpilot/starpilot/conditional_mode/host.py @@ -136,7 +136,8 @@ class ConditionalModeHost: ) manual_valid = manual_valid or (selection.choice is ModeChoice.STOCK and self.projector.stop_detector.committed) if ( - safe_value is None + safe_mode is None + or safe_value is None or safe_value is True or not self.projector.barrier_mono_ns < safe_mode.observed_mono_ns or not manual_valid diff --git a/openpilot/starpilot/conditional_mode/projection.py b/openpilot/starpilot/conditional_mode/projection.py index 1e5bd5890b..a9b2f263ed 100644 --- a/openpilot/starpilot/conditional_mode/projection.py +++ b/openpilot/starpilot/conditional_mode/projection.py @@ -521,15 +521,16 @@ class SceneProjector: raw_road = None filtered_curve = None curve_usable = False + left_blinker, right_blinker = _field(car, 'leftBlinker'), _field(car, 'rightBlinker') if ( model is not None and horizon is not None and speed is not None and curvature is not None - and type(_field(car, 'leftBlinker')) is bool - and type(_field(car, 'rightBlinker')) is bool + and type(left_blinker) is bool + and type(right_blinker) is bool ): - raw = frozen_raw_curve(model, speed, curvature, car.leftBlinker, car.rightBlinker) + raw = frozen_raw_curve(model, speed, curvature, left_blinker, right_blinker) if raw is not None: raw_road, raw_curve = raw if type(curve_mode) is bool: diff --git a/openpilot/starpilot/conditional_mode/status.py b/openpilot/starpilot/conditional_mode/status.py index fd357039aa..ef39ff6027 100644 --- a/openpilot/starpilot/conditional_mode/status.py +++ b/openpilot/starpilot/conditional_mode/status.py @@ -78,7 +78,8 @@ class StatusPublisher: self.sequence += 1 fingerprint = settings_fingerprint(snapshot) decision = proposal.decision - authority = proposal.projected.authority if proposal.projected is not None else None + projected = proposal.projected + authority = projected.authority if projected is not None else None permitted = ( fingerprint is not None and proposal.status == 'proposed' @@ -95,7 +96,7 @@ class StatusPublisher: and type(proposal.override_experimental) is bool and proposal.override_experimental == decision.requested_experimental and (proposal.choice in (ModeChoice.CEM, ModeChoice.CCM) or - proposal.choice is ModeChoice.STOCK and proposal.projected.scene.committed_stop is True and + proposal.choice is ModeChoice.STOCK and projected is not None and projected.scene.committed_stop is True and decision.reason.value == 'cem_stop' and proposal.override_experimental is True) ) event.slcState.conditionalMode = { diff --git a/openpilot/starpilot/conditional_mode/tests/test_adjacent.py b/openpilot/starpilot/conditional_mode/tests/test_adjacent.py index ac11c83825..505192676a 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_adjacent.py +++ b/openpilot/starpilot/conditional_mode/tests/test_adjacent.py @@ -59,6 +59,7 @@ class TestAdjacentEvidence(unittest.TestCase): candidate = AdjacentTrack(raw.identifier, raw.dRel, raw.yRel, raw.vLead) result = evaluate(frame(tracks=(candidate,))) self.assertTrue(result.ambiguous) + assert result.left is not None self.assertEqual(result.left.track_id, 17) def test_left_right_closest_and_selected_primary_exclusion(self): @@ -70,11 +71,15 @@ class TestAdjacentEvidence(unittest.TestCase): ) result = evaluate(frame(tracks=tracks)) self.assertTrue(result.ambiguous) + assert result.left is not None self.assertEqual(result.left.track_id, 3) + assert result.right is not None self.assertEqual(result.right.track_id, 4) excluded = evaluate(frame(tracks=tracks, primary={3, 4})) self.assertTrue(excluded.ambiguous) + assert excluded.left is not None self.assertEqual(excluded.left.track_id, 1) + assert excluded.right is not None self.assertEqual(excluded.right.track_id, 2) self.assertEqual(result.observed_mono_ns, MONO + 10_000_000) @@ -84,9 +89,11 @@ class TestAdjacentEvidence(unittest.TestCase): tracks = (AdjacentTrack(1, 10.0, 6.0, 8.0), AdjacentTrack(2, 20.0, 3.0, 8.0)) result = evaluate(frame(tracks=tracks)) self.assertTrue(result.ambiguous) + assert result.left is not None self.assertEqual(result.left.track_id, 1) slow_near = evaluate(frame(tracks=(AdjacentTrack(1, 10.0, 3.0, 1.0), AdjacentTrack(2, 20.0, 3.0, 8.0)))) self.assertTrue(slow_near.ambiguous) + assert slow_near.left is not None self.assertEqual(slow_near.left.track_id, 1) self.assertFalse(evaluate(frame()).ambiguous) self.assertFalse(evaluate(frame(tracks=tracks, standstill=True)).ambiguous) diff --git a/openpilot/starpilot/conditional_mode/tests/test_controller_mode_status.py b/openpilot/starpilot/conditional_mode/tests/test_controller_mode_status.py index 39eefdc002..b23a0c30ba 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_controller_mode_status.py +++ b/openpilot/starpilot/conditional_mode/tests/test_controller_mode_status.py @@ -3,6 +3,7 @@ from typing import Any import unittest from types import SimpleNamespace as NS +from openpilot.common.test import require_value from openpilot.starpilot.conditional_mode.traffic_status import TrafficDisplayProjector @@ -24,7 +25,7 @@ class TestControllerModeStatus(unittest.TestCase): args: dict[str, Any] = {'now_mono_ns': now, 'now_boot_ns': now+2_000_000_000, 'drive_id': now-1_000_000_000, 'settings_fingerprint': 'b'*64, 'map_fingerprint': None, 'map_assigned': False, 'profile_valid': True, 'long_active': True, 'selfdrive_enabled': True, 'car_valid': True, 'system_long': True} - self.assertEqual(reader.project(NS(trafficMode=wire), **args).state, 'active') + self.assertEqual(require_value(reader.project(NS(trafficMode=wire), **args)).state, 'active') self.assertIsNone(reader.project(NS(trafficMode=wire), **changed_arguments(args, {'now_mono_ns': now+100_000_001}))) self.assertIsNone(reader.project(NS(trafficMode=wire), **changed_arguments(args, {'settings_fingerprint': 'c'*64}))) wire.controllerSource = False diff --git a/openpilot/starpilot/conditional_mode/tests/test_effective_status.py b/openpilot/starpilot/conditional_mode/tests/test_effective_status.py index ece2d5f464..d6822dc4f3 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_effective_status.py +++ b/openpilot/starpilot/conditional_mode/tests/test_effective_status.py @@ -6,6 +6,7 @@ import time import unittest from unittest.mock import patch +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.starpilot.conditional_mode.consumer import ConsumerResult, ModeConsumer from openpilot.starpilot.conditional_mode.effective_status import LIFETIME_NS, observation, publish_ack @@ -59,7 +60,7 @@ class TestEffectiveStatus(unittest.TestCase): state = messaging.log_from_bytes(sent['selfdriveState']) ack = messaging.log_from_bytes(sent['starpilotSelfdriveState']) value = observation(ack.starpilotSelfdriveState, ack.logMonoTime) - self.assertIsNotNone(value) + assert value is not None self.assertEqual(value.selfdrive_state_ns, state.logMonoTime) self.assertEqual(value.effective_experimental, state.selfdriveState.experimentalMode) self.assertEqual(value.reason, 'cem_speed') @@ -69,7 +70,7 @@ class TestEffectiveStatus(unittest.TestCase): daemon.publish_selfdriveState(NS(vEgo=12.0)) fallback = messaging.log_from_bytes(sent['starpilotSelfdriveState']) value = observation(fallback.starpilotSelfdriveState, fallback.logMonoTime) - self.assertIsNotNone(value) + assert value is not None self.assertFalse(value.accepted) self.assertIsNone(value.reason) @@ -85,7 +86,7 @@ class TestEffectiveStatus(unittest.TestCase): self.assertEqual(str(decoded.starpilotSelfdriveState.alertStatus), 'userPrompt') self.assertEqual(str(decoded.starpilotSelfdriveState.alertSound), 'prompt') value = observation(decoded.starpilotSelfdriveState, NOW) - self.assertIsNotNone(value) + assert value is not None self.assertTrue(value.accepted) self.assertEqual(value.choice, ModeChoice.CEM) self.assertEqual(value.selfdrive_state_ns, NOW - 1_000_000) @@ -100,7 +101,7 @@ class TestEffectiveStatus(unittest.TestCase): raw = event.to_bytes() decoded = messaging.log_from_bytes(raw).starpilotSelfdriveState value = observation(decoded, NOW) - self.assertIsNotNone(value) + assert value is not None self.assertFalse(value.accepted) self.assertIsNone(value.reason) self.assertEqual(value.planner_sequence, 0) @@ -116,4 +117,4 @@ class TestEffectiveStatus(unittest.TestCase): wrong_mode = publish_ack(session=SESSION, sequence=6, observed_ns=NOW, selfdrive_state_ns=NOW - 1_000_000, drive_id=NOW - 1_000_000_000, effective_experimental=False, result=ConsumerResult(False, True, 'proposed'), accepted_proposal=proposal()) - self.assertFalse(observation(messaging.log_from_bytes(wrong_mode.to_bytes()).starpilotSelfdriveState, NOW).accepted) + self.assertFalse(require_value(observation(messaging.log_from_bytes(wrong_mode.to_bytes()).starpilotSelfdriveState, NOW)).accepted) diff --git a/openpilot/starpilot/conditional_mode/tests/test_manual.py b/openpilot/starpilot/conditional_mode/tests/test_manual.py index c4002d3ed9..1411a218f2 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_manual.py +++ b/openpilot/starpilot/conditional_mode/tests/test_manual.py @@ -66,14 +66,20 @@ class ManualSettingsTests(unittest.TestCase): params.put('LongDistanceButtonControl', 5, block=True) buttons = read_button_map(params, include_ioniq_media=True) self.assertEqual(buttons, ButtonMap(lkas=5, distance_long=5)) + assert buttons is not None self.assertTrue(buttons.assigned(Gesture(Button.LKAS, Press.SHORT))) + assert buttons is not None self.assertTrue(buttons.assigned(Gesture(Button.DISTANCE, Press.LONG))) + assert buttons is not None self.assertFalse(buttons.assigned(Gesture(Button.DISTANCE, Press.SHORT))) params.put('ModeButtonControl', 5, block=True) params.put('LongStarButtonControl', 5, block=True) buttons = read_button_map(params, include_ioniq_media=True) + assert buttons is not None self.assertTrue(buttons.assigned(Gesture(Button.MODE, Press.SHORT))) + assert buttons is not None self.assertTrue(buttons.assigned(Gesture(Button.CUSTOM, Press.LONG))) + assert buttons is not None self.assertFalse(buttons.assigned(Gesture(Button.CUSTOM, Press.SHORT))) Path(params.get_param_path('ModeButtonControl')).write_bytes(b'05') self.assertIsNone(read_button_map(params, include_ioniq_media=True)) @@ -196,10 +202,12 @@ class ManualSessionTests(unittest.TestCase): owner = ManualSession() self.assertIsNone(owner.start(ModeChoice.CEM, 100, 101, persist_manual=True)) restored = owner.start(ModeChoice.CEM, 100, 101, persist_manual=True, persisted_code=2) + assert restored is not None self.assertEqual((restored.intent, owner.code), (ManualIntent.FORCE_EXPERIMENTAL, 2)) self.assertIsNone(owner.start(ModeChoice.CCM, 100, 101, persist_manual=True, persisted_code=True)) self.assertIsNone(owner.start(ModeChoice.STOCK, 100, 101, persist_manual=False)) initial = owner.start(ModeChoice.CEM, 100, 101, persist_manual=False) + assert initial is not None self.assertEqual((initial.intent, initial.drive_id, initial.observed_mono_ns), (ManualIntent.NONE, 100, 101)) def test_frozen_ce_and_cc_cycle_with_replay_rejection(self): @@ -209,6 +217,7 @@ class ManualSessionTests(unittest.TestCase): owner.start(choice, 100, 101, persist_manual=False) first_state = owner.apply(sequence=1, drive_id=100, observed_ns=102, effective_experimental=True, assigned=True) + assert first_state is not None self.assertEqual(first_state.intent, ManualIntent.FORCE_CHILL) self.assertEqual(owner.code, first_code) self.assertIsNone(owner.apply(sequence=1, drive_id=100, observed_ns=103, @@ -217,9 +226,11 @@ class ManualSessionTests(unittest.TestCase): effective_experimental=False, assigned=True)) automatic = owner.apply(sequence=2, drive_id=100, observed_ns=104, effective_experimental=False, assigned=True) + assert automatic is not None self.assertEqual(automatic.intent, ManualIntent.NONE) second_state = owner.apply(sequence=3, drive_id=100, observed_ns=105, effective_experimental=False, assigned=True) + assert second_state is not None self.assertEqual(second_state.intent, ManualIntent.FORCE_EXPERIMENTAL) self.assertEqual(owner.code, second_code) self.assertIsNone(owner.apply(sequence=4, drive_id=100, observed_ns=106, diff --git a/openpilot/starpilot/conditional_mode/tests/test_manual_saved.py b/openpilot/starpilot/conditional_mode/tests/test_manual_saved.py index 9a00f0d039..d02b8fb2af 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_manual_saved.py +++ b/openpilot/starpilot/conditional_mode/tests/test_manual_saved.py @@ -8,6 +8,7 @@ import time import unittest from unittest.mock import patch +from openpilot.common.test import require_value from openpilot.common.params import Params from openpilot.starpilot.conditional_mode.manual_saved import ( KEY, ManualSavedOwner, SavedCodes, decode, encode, read_codes, @@ -76,6 +77,7 @@ class ManualSavedTests(unittest.TestCase): restored = second.begin_drive(second_snapshot, choice=ModeChoice.CCM, drive_id=self.drive_id + 2_000_000_000, now_ns=self.now) self.assertEqual((restored.code, restored.intent), (None, None)) + assert second_snapshot.preferences is not None self.assertEqual(second_snapshot.preferences.mode, ModeChoice.CEM) self.assertEqual(read_codes(self.params).codes, SavedCodes(0, 1)) @@ -155,6 +157,7 @@ class ManualSavedTests(unittest.TestCase): owner.close() self.assertLess(time.monotonic() - before, 0.1) release.set() + assert owner.worker is not None owner.worker.join(timeout=1.0) self.assertIsNone(read_codes(self.params).raw) @@ -193,7 +196,7 @@ class ManualSavedTests(unittest.TestCase): release.set() assert owner.worker is not None owner.worker.join(timeout=1.0) - self.assertEqual(owner.poll(snapshot=snapshot, drive_id=self.drive_id, now_ns=self.now).status, 'external_edit') + self.assertEqual(require_value(owner.poll(snapshot=snapshot, drive_id=self.drive_id, now_ns=self.now)).status, 'external_edit') self.assertEqual(read_codes(self.params).codes, SavedCodes(2, 2)) def test_same_source_refresh_allows_queue_and_staged_commit(self): @@ -224,7 +227,7 @@ class ManualSavedTests(unittest.TestCase): release.set() assert owner.worker is not None owner.worker.join(timeout=1.0) - self.assertEqual(owner.poll(snapshot=again, drive_id=self.drive_id, now_ns=self.now).status, 'saved') + self.assertEqual(require_value(owner.poll(snapshot=again, drive_id=self.drive_id, now_ns=self.now)).status, 'saved') self.assertEqual(read_codes(self.params).codes, SavedCodes(1, 0)) def test_invalid_saved_bytes_do_not_disable_nonpersistent_manual_start(self): diff --git a/openpilot/starpilot/conditional_mode/tests/test_paired_clock.py b/openpilot/starpilot/conditional_mode/tests/test_paired_clock.py index 124ccdd983..cdebeed850 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_paired_clock.py +++ b/openpilot/starpilot/conditional_mode/tests/test_paired_clock.py @@ -26,7 +26,7 @@ class TestPairedClock(unittest.TestCase): patch.object(projection.time, 'monotonic_ns', side_effect=(before, after)), \ patch.object(projection.time, 'clock_gettime_ns', return_value=now + offset): result = projection.paired_clocks_ns() - self.assertIsNotNone(result) + assert result is not None assert result is not None self.assertEqual(result, (now, now + offset, skew)) return result @@ -103,6 +103,7 @@ class TestPairedClock(unittest.TestCase): model_ns=expiry + 1, car_state_ns=expiry + 1).accepted) self.assertEqual(self.fixture.consumer.rejection, 'proposal_invalid') self.assertEqual(self.fixture.consumer.last, original) + assert self.fixture.consumer.last is not None self.assertEqual(self.fixture.consumer.last.expires_ns, expiry) self.assertEqual(event.as_reader().as_builder().to_bytes(), original_envelope) diff --git a/openpilot/starpilot/conditional_mode/tests/test_runtime_settings.py b/openpilot/starpilot/conditional_mode/tests/test_runtime_settings.py index 1fe454125c..4a7bd88345 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_runtime_settings.py +++ b/openpilot/starpilot/conditional_mode/tests/test_runtime_settings.py @@ -10,6 +10,7 @@ import tempfile import unittest from unittest.mock import patch +from openpilot.common.test import require_value from openpilot.common.params import Params from openpilot.starpilot.conditional_mode.policy import ModeChoice from openpilot.starpilot.conditional_mode.preferences import CEMOptions, SavedPreferences, encode_preferences @@ -73,6 +74,7 @@ class ConditionalRuntimeSettingsTest(unittest.TestCase): self.assertEqual(snapshot.revision, 1) verdict = self.owner.verdict(snapshot, now_mono_ns=1_100_000_000, drive_id=7) self.assertEqual(verdict.status, 'ready') + assert verdict.selection is not None self.assertIs(verdict.selection.choice, ModeChoice.CEM) self.assertFalse(verdict.safe_mode) self.assertIsNone(self.params.get(DOCUMENT_KEY)) @@ -85,7 +87,7 @@ class ConditionalRuntimeSettingsTest(unittest.TestCase): first = owner.refresh(1_000_000_000) self.assertIs(first.document_state, DocumentState.VALID) self.assertEqual(first.preferences, document) - self.assertEqual(owner.verdict(first, now_mono_ns=1_050_000_000, drive_id=9).selection.settings.cem_speed_mps, 10.0) + self.assertEqual(require_value(owner.verdict(first, now_mono_ns=1_050_000_000, drive_id=9).selection).settings.cem_speed_mps, 10.0) with patch('openpilot.starpilot.conditional_mode.runtime_settings.read_saved') as saved_read: for i in range(20): self.assertTrue(owner.affirm(first, now_mono_ns=1_050_000_000 + i * 10_000_000)) @@ -106,7 +108,9 @@ class ConditionalRuntimeSettingsTest(unittest.TestCase): if elapsed % 110_000_000 == 0: self.owner.refresh(start + elapsed) self.assertTrue(self.owner.affirm(snapshot, now_mono_ns=start + elapsed), elapsed) + assert self.owner.current is not None self.assertEqual(self.owner.current.revision, snapshot.revision) + assert self.owner.current is not None self.assertFalse(self.owner.affirm(snapshot, now_mono_ns=self.owner.current.verified_mono_ns + REFRESH_NS + 1)) def test_external_revision_and_safe_mode_are_independent(self): @@ -126,7 +130,7 @@ class ConditionalRuntimeSettingsTest(unittest.TestCase): recovered = self.owner.refresh(3_000_000_000) self.assertEqual(recovered.revision, 3) self.assertIs(recovered.safe_mode_state, SafeModeState.FALSE) - self.assertIs(self.owner.verdict(recovered, now_mono_ns=3_050_000_000, drive_id=9).selection.choice, ModeChoice.CEM) + self.assertIs(require_value(self.owner.verdict(recovered, now_mono_ns=3_050_000_000, drive_id=9).selection).choice, ModeChoice.CEM) def test_corrupt_document_preserves_source_then_recovers(self): raw = b'{"version":1,"version":1}' @@ -140,7 +144,7 @@ class ConditionalRuntimeSettingsTest(unittest.TestCase): self.path(DOCUMENT_KEY).write_bytes(encode_preferences(self.saved(ModeChoice.CCM))) recovered = self.owner.refresh(2_000_000_000) self.assertEqual(recovered.revision, 2) - self.assertEqual(self.owner.verdict(recovered, now_mono_ns=2_050_000_000, drive_id=1).selection.choice, + self.assertEqual(require_value(self.owner.verdict(recovered, now_mono_ns=2_050_000_000, drive_id=1).selection).choice, ModeChoice.CEM) self.assertEqual(self.path(DOCUMENT_KEY).read_bytes(), encode_preferences(self.saved(ModeChoice.CCM))) @@ -192,7 +196,7 @@ class ConditionalRuntimeSettingsTest(unittest.TestCase): self.path(DOCUMENT_KEY).write_bytes(encode_preferences(self.saved())) not_due = self.owner.refresh(1_250_000_000) self.assertIs(not_due, first) - self.assertIs(self.owner.verdict(first, now_mono_ns=1_250_000_000, drive_id=1).selection.choice, + self.assertIs(require_value(self.owner.verdict(first, now_mono_ns=1_250_000_000, drive_id=1).selection).choice, ModeChoice.CEM) changed = self.owner.refresh(2_000_000_000) self.assertIs(changed.document_state, DocumentState.VALID) diff --git a/openpilot/starpilot/conditional_mode/tests/test_scene_cadence.py b/openpilot/starpilot/conditional_mode/tests/test_scene_cadence.py index 58f71d96f1..f5623fcfee 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_scene_cadence.py +++ b/openpilot/starpilot/conditional_mode/tests/test_scene_cadence.py @@ -17,7 +17,7 @@ class TestSceneCadence(unittest.TestCase): sm.recv_time['carControl'] = (now - 2_000_000) / 1e9 result = projector.project(sm, CP, now_mono_ns=now, now_boot_ns=BOOT + 200_000_000, sample_skew_ns=1000, safe_mode=False) - self.assertIsNotNone(result.authority) + assert result.authority is not None self.assertTrue(result.authority.long_active) self.assertTrue(result.authority.driving_enabled) diff --git a/openpilot/starpilot/conditional_mode/tests/test_status_consumer.py b/openpilot/starpilot/conditional_mode/tests/test_status_consumer.py index ae35d7fd21..c4f84eb558 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_status_consumer.py +++ b/openpilot/starpilot/conditional_mode/tests/test_status_consumer.py @@ -147,6 +147,7 @@ class TestModeTransport(unittest.TestCase): # replaced. A model tick must keep the prior accepted pair and stop. now = MONO + 31 * 50_000_000 self.assertIs(self.owner.refresh(now, force=True), accepted) + assert self.owner.current is not None self.assertEqual(self.owner.current.verified_mono_ns, accepted.verified_mono_ns) model_tick(31, ModeChoice.CEM) return original_replace(source, destination) @@ -163,6 +164,7 @@ class TestModeTransport(unittest.TestCase): assert change is not None self.assertTrue(ui.apply(replace(change, value='End to End'))) drive.refresh_saved_driving_mode(MONO + 32 * 50_000_000) + assert self.owner.current is not None self.assertEqual(self.owner.current.experimental_raw, b'1') model_tick(32, ModeChoice.STOCK, after_verdict=refresh_experimental_between_main_snapshot_and_baseline) diff --git a/openpilot/starpilot/conditional_mode/tests/test_traffic.py b/openpilot/starpilot/conditional_mode/tests/test_traffic.py index b9641fc74b..c3b13123b4 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_traffic.py +++ b/openpilot/starpilot/conditional_mode/tests/test_traffic.py @@ -9,6 +9,7 @@ from types import SimpleNamespace from opendbc.car.car_helpers import interfaces from opendbc.car.honda.values import CAR as HONDA_CAR from opendbc.car.hyundai.values import CAR as HYUNDAI_CAR, HyundaiFlags +from openpilot.common.test import require_value from openpilot.cereal import log, messaging from openpilot.common.params import Params from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner @@ -213,7 +214,7 @@ class TrafficOwnerTests(unittest.TestCase): 'settings_fingerprint': verdict.settings_fingerprint, 'map_fingerprint': verdict.map_fingerprint, 'map_assigned': True, 'profile_valid': True, 'long_active': True, 'selfdrive_enabled': True, 'car_valid': True, 'system_long': True} - self.assertEqual(reader.project(state, **args).state, 'active') + self.assertEqual(require_value(reader.project(state, **args)).state, 'active') args['now_mono_ns'] += 101_000_000 self.assertIsNone(reader.project(state, **args)) @@ -267,7 +268,7 @@ class TrafficOwnerTests(unittest.TestCase): self.assertEqual(status.reason, 'active') on = solve(accepted.effective, NOW + 50_000_000) self.assertLess(on, ordinary) - self.assertIsNotNone(planner.last_profile) + assert planner.last_profile is not None # The real long axis going inactive (Nostalgia paddle/AOL lateral-only) # keeps the same-drive intent but immediately removes Traffic MPC tuning. @@ -304,7 +305,7 @@ class TrafficOwnerTests(unittest.TestCase): self.assertFalse(absent.profile_mode) # An unused assignment cannot suppress ordinary tuning. ordinary = host.sample(NOW, log.LongitudinalPersonality.standard, 20.0, self.cp, traffic_mode=absent.profile_mode) - self.assertIsNotNone(ordinary) + assert ordinary is not None self.assertAlmostEqual(ordinary.follow_seconds, 2.1) sm, _ = messages(lead=True) sm['carControl'].longActive = True @@ -317,18 +318,18 @@ class TrafficOwnerTests(unittest.TestCase): self.assertTrue(on.profile_mode) traffic = host.sample(NOW + 100_000_000, log.LongitudinalPersonality.standard, 20.0, self.cp, traffic_mode=on.profile_mode) - self.assertIsNotNone(traffic) + assert traffic is not None update_curve_frame(planner, sm, self.cp, NOW + 100_000_000, profile_tuning=traffic, traffic_mode=on.profile_mode) held = self.sample(NOW + 450_000_000) self.assertTrue(held.profile_mode and held.requested) retained = host.sample(NOW + 450_000_000, log.LongitudinalPersonality.standard, 20.0, self.cp, traffic_mode=held.profile_mode) - self.assertIsNotNone(retained) + assert retained is not None self.assertEqual(retained.follow_seconds, traffic.follow_seconds) update_curve_frame(planner, sm, self.cp, NOW + 450_000_000, profile_tuning=retained, traffic_mode=held.profile_mode) - self.assertIsNotNone(planner.last_profile) + assert planner.last_profile is not None self.sm.payloads['carState'].canValid = False lost = self.sample(NOW + 500_000_000) self.assertIsNone(lost.profile_mode) diff --git a/openpilot/starpilot/conditional_mode/tests/test_ui_action.py b/openpilot/starpilot/conditional_mode/tests/test_ui_action.py index c86f1bcc81..eaf006c440 100644 --- a/openpilot/starpilot/conditional_mode/tests/test_ui_action.py +++ b/openpilot/starpilot/conditional_mode/tests/test_ui_action.py @@ -145,6 +145,7 @@ class TestUiAction(unittest.TestCase): event = self.request(stamp + 10_000_000, effective=effective) proposal, snapshot = self.sample(stamp + 20_000_000, ui_event=event, effective=effective) self.assertEqual(self.owner.manual.code, next_manual_status(self.choice, 0, effective)) + assert self.owner.manual_state is not None self.assertEqual(self.owner.manual_state.intent, ManualIntent.FORCE_CHILL if effective else ManualIntent.FORCE_EXPERIMENTAL) self.assertIs(proposal.override_experimental, not effective) consumer = ModeConsumer() @@ -165,6 +166,7 @@ class TestUiAction(unittest.TestCase): self.assertIs(result.experimental, not effective) event = self.request(stamp + 60_000_000, effective=not effective) self.sample(stamp + 70_000_000, ui_event=event, effective=not effective) + assert self.owner.manual_state is not None self.assertEqual(self.owner.manual_state.intent, ManualIntent.NONE) self.assertEqual(self.owner.manual.code, 0) self.assertIsNone(self.params.get('ExperimentalMode')) @@ -232,6 +234,7 @@ class TestUiAction(unittest.TestCase): assert context is not None self.ack(stamp + 10_000_000) current = self.ui.context(self.sm, self.cp, now_ns=stamp + 10_001_000) + assert current is not None self.assertEqual(context.token, current.token) self.params.put_bool('SafeMode', True, block=True) self.assertFalse(self.ui.dispatch(context, self.sm, self.cp, self.publisher, now_ns=stamp + 10_002_000)) @@ -325,6 +328,7 @@ class TestUiAction(unittest.TestCase): return actual(fd) with patch.object(manual_saved.os, 'fsync', side_effect=blocked): self.sample(stamp + 20_000_000, ui_event=event) + assert self.owner.manual_state is not None self.assertEqual(self.owner.manual_state.intent, ManualIntent.NONE) self.sample(stamp + 21_000_000) self.assertTrue(entered.wait(1)) @@ -332,16 +336,20 @@ class TestUiAction(unittest.TestCase): repeated.slcAction.conditionalManual.sequence += 1 self.sample(stamp + 22_000_000, ui_event=repeated) self.assertEqual(self.owner.manual.code, 2) + assert self.owner.manual_state is not None self.assertEqual(self.owner.manual_state.intent, ManualIntent.NONE) release.set() + assert self.owner.manual_saved.worker is not None self.owner.manual_saved.worker.join(timeout=1) self.sample(stamp + 30_000_000) if failure: + assert self.owner.manual_state is not None self.assertEqual(self.owner.manual_state.intent, ManualIntent.NONE) self.assertEqual(self.owner.manual_saved.status, 'write_failed') self.assertIsNone(read_codes(self.params).raw) else: self.settle(stamp + 40_000_000) + assert self.owner.manual_state is not None self.assertEqual(self.owner.manual_state.intent, ManualIntent.FORCE_EXPERIMENTAL) self.assertEqual(read_codes(self.params).codes, SavedCodes(2, 0)) diff --git a/openpilot/starpilot/controllers/tests/test_coast_idle.py b/openpilot/starpilot/controllers/tests/test_coast_idle.py index f6c00b1c34..3a13a75a31 100644 --- a/openpilot/starpilot/controllers/tests/test_coast_idle.py +++ b/openpilot/starpilot/controllers/tests/test_coast_idle.py @@ -163,8 +163,14 @@ class TestCoastIdle(unittest.TestCase): del sm.data[name] else: sm.data[name] = replacement - expected = KeyError if replacement is None and name == 'deviceState' else \ - (AttributeError, KjException) if name == 'deviceState' and replacement.schema == structs.CarParams.schema else FallbackReached + if name != 'deviceState': + expected = FallbackReached + elif replacement is None: + expected = KeyError + elif replacement.schema == structs.CarParams.schema: + expected = (AttributeError, KjException) + else: + expected = FallbackReached with self.subTest(name=name, replacement=type(replacement)), \ patch('openpilot.starpilot.saved_source.read_saved', side_effect=FallbackReached): with self.assertRaises(expected): diff --git a/openpilot/starpilot/controllers/tests/test_mode_actions.py b/openpilot/starpilot/controllers/tests/test_mode_actions.py index 05b80e99de..a0656450a2 100644 --- a/openpilot/starpilot/controllers/tests/test_mode_actions.py +++ b/openpilot/starpilot/controllers/tests/test_mode_actions.py @@ -1,6 +1,7 @@ from types import SimpleNamespace as NS from unittest.mock import patch +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.starpilot.controllers.mode_actions import ModeActionOwner, SwitchbackCooldown @@ -122,7 +123,7 @@ def test_actual_alpha_off_wheel_switchback_mapping_and_replay_denial(): 'observedMonoTime': stamp, 'validUntilMonoTime': stamp + 100_000_000, 'driveStartMonoTime': fixtures.DRIVE, 'sourceCarStateMonoTime': stamp, 'settingsFingerprint': settings_fingerprint(f.settings.refresh(fixtures.NOW)), - 'buttonMapFingerprint': read_button_map(f.params, include_ioniq_media=True).fingerprint(), + 'buttonMapFingerprint': require_value(read_button_map(f.params, include_ioniq_media=True)).fingerprint(), 'sourceEpoch': 0, 'sourceBootTime': fixtures.BOOT - 5_000_000, 'toggle': True, 'button': 'mode', 'press': 'short'} owner = ModeActionOwner() diff --git a/openpilot/starpilot/controllers/tests/test_selfie.py b/openpilot/starpilot/controllers/tests/test_selfie.py index 4e68223470..bf200bf3c9 100644 --- a/openpilot/starpilot/controllers/tests/test_selfie.py +++ b/openpilot/starpilot/controllers/tests/test_selfie.py @@ -46,6 +46,7 @@ def test_async_capture_records_real_index_and_galaxy_image(tmp_path): assert not owner.submit(lambda: True) camera.release.set() assert store.done.wait(2) + assert owner.worker is not None owner.worker.join(2) assert not owner.busy events = SentryEvents(store).snapshot()['events'] @@ -66,6 +67,7 @@ def test_denied_or_revoked_capture_never_publishes_event(tmp_path): assert camera.entered.wait(2) allowed[0] = False camera.release.set() + assert owner.worker is not None owner.worker.join(2) assert not owner.busy assert SentryEvents(store).snapshot()['events'] == [] @@ -121,6 +123,7 @@ def test_no_fresh_camera_frame_releases_worker_without_record(tmp_path): store = EventStore(tmp_path / 'events') owner = SelfieCapture(camera=MissingCamera(), store=store) assert owner.submit(lambda: True) + assert owner.worker is not None owner.worker.join(2) assert not owner.busy and owner.last_result is None assert SentryEvents(store).snapshot()['events'] == [] diff --git a/openpilot/starpilot/controllers/tests/test_wheel_ipc.py b/openpilot/starpilot/controllers/tests/test_wheel_ipc.py index 0f75c582e8..fc690f8034 100644 --- a/openpilot/starpilot/controllers/tests/test_wheel_ipc.py +++ b/openpilot/starpilot/controllers/tests/test_wheel_ipc.py @@ -37,5 +37,6 @@ def test_actual_card_and_ui_publisher_coexist_and_modes_use_only_ui_channel(): request = ModeActionPublisher() assert request.dispatch('traffic', sm, cp, ui, now_ns=NOW) event = messaging.recv_one(planner_ui) + assert event is not None assert str(event.slcAction.kind) == 'trafficModeToggle' assert ModeActionOwner().update(event, sm, cp, now_ns=NOW) diff --git a/openpilot/starpilot/curve_speed/tests/test_status.py b/openpilot/starpilot/curve_speed/tests/test_status.py index 9f3faa1e25..427b8c54b1 100644 --- a/openpilot/starpilot/curve_speed/tests/test_status.py +++ b/openpilot/starpilot/curve_speed/tests/test_status.py @@ -85,7 +85,9 @@ class TestCurveStatus(unittest.TestCase): self.assertEqual(before, after) self.assertFalse(decoded.valid) status = observation(decoded.slcState, stamp) + assert status is not None self.assertTrue(status.applied) + assert status is not None self.assertFalse(status.curve_only) def test_invalid_and_contradictory_nested_status_is_not_displayable(self): diff --git a/openpilot/starpilot/curve_speed/tests/test_target.py b/openpilot/starpilot/curve_speed/tests/test_target.py index 1590378c4e..8589960e82 100644 --- a/openpilot/starpilot/curve_speed/tests/test_target.py +++ b/openpilot/starpilot/curve_speed/tests/test_target.py @@ -60,6 +60,7 @@ class TestTarget(unittest.TestCase): velocity=SimpleNamespace(x=[10.0, 10.0, 10.0]), position=SimpleNamespace(x=[-6.64888977208733e-11, 10.0, 20.0])) profile = CurveProfile.from_model(model, 100) + assert profile is not None self.assertEqual(profile.distances, (0.0, 10.0, 20.0)) self.assertLess(model.position.x[0], 0.0) for distances in ([-1.0001e-6, 10.0, 20.0], [0.0, -1e-11, 20.0], [-1e-11, 10.0, 9.0]): diff --git a/openpilot/starpilot/flm/event_collection.py b/openpilot/starpilot/flm/event_collection.py index 46ac8b927d..3c38ba9bb2 100644 --- a/openpilot/starpilot/flm/event_collection.py +++ b/openpilot/starpilot/flm/event_collection.py @@ -187,7 +187,8 @@ class EventCollectionAdapter(TorqueCollectionAdapter): self.original_context_receipts.record_control(evidence) return prepared - def physical_observable(self, value): + @staticmethod + def physical_observable(value): # Raw storage is shared by all scheduled groups, including crawl FF. # Per-coordinate excitation and independent model/admission stay in child. return value.speed_mps >= 2 and abs(value.roll_rad) < .3 diff --git a/openpilot/starpilot/flm/event_collector.py b/openpilot/starpilot/flm/event_collector.py index 226b7ee4d5..70a8df1413 100644 --- a/openpilot/starpilot/flm/event_collector.py +++ b/openpilot/starpilot/flm/event_collector.py @@ -121,6 +121,8 @@ class EventFullrateCollector(FullrateCollector): """A known accepted result changes collection lineage, not live health.""" try: trace = value.effect_trace + if self.fit_result is None: + return False profile = self.fit_result.profile trace.validate() previous = self.ready[-1][0] diff --git a/openpilot/starpilot/flm/event_controller_replay.py b/openpilot/starpilot/flm/event_controller_replay.py index b504ac8e2c..e7a24b7cd1 100644 --- a/openpilot/starpilot/flm/event_controller_replay.py +++ b/openpilot/starpilot/flm/event_controller_replay.py @@ -343,6 +343,8 @@ class EventControllerReplay: # protocol's <=4 marker coordinates or infer neutral from zero markers. source = trial elif prepare_ns > 0: + if transition is None: + raise ValueError("Missing original replay transition") source = transition.source_for_frame(prepare_ns, trace, new_owner=activation_tick) elif self.activation_plan is not None: raise ValueError('event activation post-treatment owner clock missing') @@ -850,6 +852,8 @@ class EventControllerReplay: if frame.control_ns == windows[index][0]: transition.reset() previous_prepare = 0 + if self.activation_plan is None: + return None activation = self.activation_plan.activation_for(*windows[index]) if activation is None: return None @@ -1049,7 +1053,7 @@ class EventControllerReplay: maximum_base = maximum_trial = 0.0 for stamp in sorted(baseline): event = self.emissions.events[stamp] if encoded else None - control_ns = event.control_ns if encoded else stamp + control_ns = event.control_ns if event is not None else stamp window = next((index for index, (a, b) in enumerate(self.replay_windows) if a <= control_ns <= b), None) if window is None: return False diff --git a/openpilot/starpilot/flm/feedback_observation.py b/openpilot/starpilot/flm/feedback_observation.py index c09e2f10a4..77578f45dd 100644 --- a/openpilot/starpilot/flm/feedback_observation.py +++ b/openpilot/starpilot/flm/feedback_observation.py @@ -3,7 +3,7 @@ Capture only; no native/current/profile authority. Original source and native replay must independently verify every apply before creating a verified tape. """ -from dataclasses import asdict, dataclass, replace, fields, Field, _FIELD +from dataclasses import asdict, dataclass, replace, fields, Field import math import re import struct @@ -84,6 +84,9 @@ class CoPublication: carrier_observed_ns: int +_RECORD_FIELD_KIND = fields(CoPublication)[0]._field_type + + @dataclass(frozen=True) class CoConsumption: version: int @@ -333,7 +336,7 @@ def _plain_record_values(item, kind): declared = [] for name, field in metadata.items(): if (type(name) is not str or type(field) is not Field or type(field.name) is not str or field.name != name or - field._field_type is not _FIELD or name in namespace): + field._field_type is not _RECORD_FIELD_KIND or name in namespace): return None declared.append(name) owned = object.__getattribute__(item, '__dict__') diff --git a/openpilot/starpilot/flm/fit_process.py b/openpilot/starpilot/flm/fit_process.py index c3b238c87d..db1a34848b 100644 --- a/openpilot/starpilot/flm/fit_process.py +++ b/openpilot/starpilot/flm/fit_process.py @@ -66,8 +66,11 @@ class FitProcess: self.last_start_ns = now_ns return False try: - os.set_blocking(self.child.stdin.fileno(), False) - os.set_blocking(self.child.stdout.fileno(), False) + stdin, stdout = self.child.stdin, self.child.stdout + if stdin is None or stdout is None: + raise OSError("Fit subprocess pipes unavailable") + os.set_blocking(stdin.fileno(), False) + os.set_blocking(stdout.fileno(), False) except OSError: self.close('fit_pipe_setup_failed') self.last_start_ns = now_ns @@ -110,9 +113,16 @@ class FitProcess: if child.poll() is not None: self._close() return None + stdin, stdout = child.stdin, child.stdout + if stdout is None: + self.cancel('fit_output_closed') + return None if self.position < len(self.pending): + if stdin is None: + self.cancel('fit_input_closed') + return None try: - self.position += os.write(child.stdin.fileno(), self.pending[self.position : self.position + CHUNK]) + self.position += os.write(stdin.fileno(), self.pending[self.position : self.position + CHUNK]) except BlockingIOError: pass except BrokenPipeError: @@ -123,7 +133,7 @@ class FitProcess: child.stdin = None self.pending = b'' try: - part = os.read(child.stdout.fileno(), CHUNK) + part = os.read(stdout.fileno(), CHUNK) except BlockingIOError: part = None if part: @@ -137,7 +147,7 @@ class FitProcess: # Drain one final bounded chunk after exit; producer cannot consume a # partially read report merely because the child exited successfully. try: - tail = os.read(child.stdout.fileno(), CHUNK) + tail = os.read(stdout.fileno(), CHUNK) except BlockingIOError: tail = b'' self.output.extend(tail) diff --git a/openpilot/starpilot/flm/global_runtime.py b/openpilot/starpilot/flm/global_runtime.py index bd0c09f753..9939758971 100644 --- a/openpilot/starpilot/flm/global_runtime.py +++ b/openpilot/starpilot/flm/global_runtime.py @@ -500,12 +500,15 @@ class GlobalRuntime: if not current_authority(self._live_sm, self.cp, now_ns=now_ns, required=False)[0]: raise ValueError('live_ordinary_native_permission_unavailable') + descriptor = self.descriptor + if descriptor is None: + raise ValueError('live_controller_unavailable') if not self.live_vehicle_model_generation: raise ValueError('live_vehicle_model_unobserved') expected = LiveTrialBinding( self.identity, - self.descriptor.cp_sha256, - self.descriptor.controller_revision, + descriptor.cp_sha256, + descriptor.controller_revision, self.baseline_revision, source.source_epoch, source.reset, @@ -521,7 +524,7 @@ class GlobalRuntime: validate_response_witness(offer.response_witness, expected, now_ns) if offer.binding != expected: raise ValueError('live_current_source_binding_changed') - if self.descriptor.domain == 'torque_pid': + if descriptor.domain == 'torque_pid': from openpilot.starpilot.flm.pid_stages import SUPPORTED, coordinates_supported if (not restoring and any(name not in SUPPORTED for name in offer.names)) or not coordinates_supported(dict(offer.target)): @@ -530,7 +533,7 @@ class GlobalRuntime: if owner is None or owner.binding != expected: if owner is not None: owner.neutral('live_binding_changed') - owner = TrackingTrialOwner(expected, domain=self.descriptor.domain) + owner = TrackingTrialOwner(expected, domain=descriptor.domain) self.live_trial_owner = owner permission = bool(active and healthy and self.eligible) if restoring: @@ -584,10 +587,13 @@ class GlobalRuntime: from openpilot.starpilot.flm.event_objective import EffectObjective from openpilot.starpilot.flm.selected_effects import EffectOwner + descriptor = self.descriptor + if descriptor is None: + raise ValueError('missing controller descriptor') envelope = profile.effect_envelope if not isinstance(envelope, FullSurfaceEnvelope): raise ValueError('missing typed full30 envelope') - if self.descriptor.domain == 'torque_pid': + if descriptor.domain == 'torque_pid': from openpilot.starpilot.flm.pid_stages import coordinates_supported if not coordinates_supported(dict(envelope.coordinates)): @@ -603,8 +609,8 @@ class GlobalRuntime: # proposal must compare-and-swap the exact previously accepted target. renewing = envelope == self.effect_envelope context = { - 'cp_sha256': self.descriptor.cp_sha256, - 'controller_revision': self.descriptor.controller_revision, + 'cp_sha256': descriptor.cp_sha256, + 'controller_revision': descriptor.controller_revision, 'source_epoch': source.source_epoch, 'reset_generation': source.reset, 'selected_baseline_revision': self.baseline_revision, @@ -635,7 +641,10 @@ class GlobalRuntime: self.controller.automatic_flm_effects = owner def response_parameters(self): - return (Parameter('response', self.descriptor.stage_revision, -0.03, 0.03, 0.03, 0.005, 1e-5 if self.descriptor.domain == 'curvature' else 0.01),) + descriptor = self.descriptor + if descriptor is None: + raise ValueError('missing controller descriptor') + return (Parameter('response', descriptor.stage_revision, -0.03, 0.03, 0.03, 0.005, 1e-5 if descriptor.domain == 'curvature' else 0.01),) def _read_centre_ack(self, event, now_ns): return None @@ -874,7 +883,10 @@ class GlobalRuntime: cs, vm, params, log, desired, curvature_limited, delay, requested, values, p, i, d, raw_command = self.frame if self.descriptor.domain in ('torque', 'torque_pid'): # Exact policy-specific normalized counterfactual trace is mandatory. - trace = self.observation.finish_frame( + observation = self.observation + if observation is None or observation.stage is None: + return None + trace = observation.finish_frame( self.controller, log, selected_command=raw_command, prior_policy_output=self.prior_policy_output, prior_policy_ff=self.prior_policy_ff ) if trace is None: @@ -885,8 +897,15 @@ class GlobalRuntime: coordinates = (0.0, 0.0) if self.centre_raw: stage_values = tuple(stage_values) + self.centre_raw + stage = observation.stage + if stage is None: + return None if self.descriptor.domain == 'torque_pid': - stage_values = tuple(stage_values) + (('actual_delta_ff', self.observation.learned_ff - self.observation.stage.baseline_ff),) + from openpilot.starpilot.flm.pid_stages import PidObservation + + if not isinstance(observation, PidObservation): + return None + stage_values = tuple(stage_values) + (('actual_delta_ff', observation.learned_ff - stage.baseline_ff),) else: stage_values = tuple(stage_values) + ( ('actual_delta_ff', self.torque_result[0]), @@ -900,7 +919,6 @@ class GlobalRuntime: coordinates = (0.0, 0.0) # Raw basis is identified by schema; separate learner actual replay turns # it into normalized same-state command sensitivities before collection. - stage = self.observation.stage from openpilot.starpilot.flm.torque_adapter import gates objective = ( @@ -986,7 +1004,7 @@ class GlobalRuntime: and self.reason == 'qualified' and 0 < self.profile.observed_ns <= control_ns <= self.profile.expires_ns <= self.profile.observed_ns + SOURCE_LEASE_NS ) - if current_profile and self.centre_source is not None: + if current_profile and self.centre_source is not None and self.validation is not None: key = ( self.profile.sequence, self.profile.observed_ns, diff --git a/openpilot/starpilot/flm/learning_wire.py b/openpilot/starpilot/flm/learning_wire.py index b4bd88d68e..e750e714df 100644 --- a/openpilot/starpilot/flm/learning_wire.py +++ b/openpilot/starpilot/flm/learning_wire.py @@ -490,7 +490,7 @@ def result_message(result, session, sequence, now_ns, *, replay_validation=None) for p, coefficient in zip(profile.parameters, profile.coefficients, strict=True) ): raise ValueError('profile parameter bound') - if not replay_accepts(replay_validation, profile): + if replay_validation is None or not replay_accepts(replay_validation, profile): raise ValueError('actual replay validation required') value.status = 'qualifiedFit' if result.status == 'qualified' else 'rejected' value.reason = _string(result.reason) diff --git a/openpilot/starpilot/flm/live.py b/openpilot/starpilot/flm/live.py index 346ec65ef5..f8c2353e6e 100644 --- a/openpilot/starpilot/flm/live.py +++ b/openpilot/starpilot/flm/live.py @@ -70,7 +70,7 @@ class GmLiveSource: return None profiles = parse_document(raw) profile = profiles.get(self.capability['fingerprint']) - if binding_matches(profile, self.capability): + if profile is not None and profile.flm is not None and binding_matches(profile, self.capability): self.surface = profile.flm.selected() except (ValueError, TypeError, UnicodeError, OverflowError, RecursionError): pass diff --git a/openpilot/starpilot/flm/live_tracking_actor.py b/openpilot/starpilot/flm/live_tracking_actor.py index 409d7559df..993efe17c1 100644 --- a/openpilot/starpilot/flm/live_tracking_actor.py +++ b/openpilot/starpilot/flm/live_tracking_actor.py @@ -356,6 +356,9 @@ class LiveTrackingActor: def _submit_probe_queue(self, token, now_ns): from openpilot.starpilot.flm.live_tracking_probe_process import make_probe_batch + process = self.probe_process + if process is None: + return False # The aggregate literal snapshot bound also applies to a batch. Split only # numerical work; four genuine endpoints per episode remain mandatory. for count in range(len(self.probe_queue), 0, -1): @@ -363,7 +366,7 @@ class LiveTrackingActor: batch = make_probe_batch(tuple(item[0] for item in self.probe_queue[:count]), queued_ns=now_ns) except ValueError: continue - if self.probe_process.submit_probe(batch, token=token, now_ns=now_ns): + if process.submit_probe(batch, token=token, now_ns=now_ns): self.probe_token = token del self.probe_queue[:count] if not self.probe_queue: @@ -377,7 +380,8 @@ class LiveTrackingActor: def _probe_tick(self, collector, source, *, now_ns): """Queue optional numerical work; never update a controller in this actor.""" - if self.probe_process is None or self.ingress is None: + certificate = self.certificate + if self.probe_process is None or self.ingress is None or certificate is None: return if self.restore_pending: self.probe_process.poll(token=None, now_ns=now_ns) @@ -391,10 +395,10 @@ class LiveTrackingActor: optimizer = self.ingress.optimizer self.reason = optimizer.reason accepted = tuple((name, optimizer.accepted[name]) for name in NAMES) - profile_hash = full_profile_sha256(self.certificate.binding.baseline_revision, dict(accepted)) - token = (self.token, self.certificate.model_revision, profile_hash) + profile_hash = full_profile_sha256(certificate.binding.baseline_revision, dict(accepted)) + token = (self.token, certificate.model_revision, profile_hash) try: - result = self.probe_process.poll_probe(token=token, binding=self.certificate.binding, now_ns=now_ns) + result = self.probe_process.poll_probe(token=token, binding=certificate.binding, now_ns=now_ns) completed, self.pending_probe_results = self.pending_probe_results, [] if result is not None: completed.append(result) @@ -433,7 +437,7 @@ class LiveTrackingActor: ): raise ValueError('owned inline numerical context or deadline differs') numeric = self.probe_process.decode_report( - prepared['numeric'], expected=(prepared['job_sha256'], expected), prepared_sha=prepared['context_sha256'], binding=self.certificate.binding + prepared['numeric'], expected=(prepared['job_sha256'], expected), prepared_sha=prepared['context_sha256'], binding=certificate.binding ) for row in numeric if type(numeric) is tuple else (numeric,): self.ingress.observe_probe(row, now_ns=now_ns) @@ -458,7 +462,7 @@ class LiveTrackingActor: from openpilot.starpilot.flm.live_tracking_response import verified_clipped_input def known_input(candidate, applied): - return verified_clipped_input(collector.adapter.replay, candidate, applied, self.certificate.binding) + return verified_clipped_input(collector.adapter.replay, candidate, applied, certificate.binding) if output.limited and not known_input(control, output): return # Missing original CAN/limiter proof is never a numerical input. @@ -562,7 +566,7 @@ class LiveTrackingActor: # recomputes the complete controller/native evidence independently. from openpilot.starpilot.flm.live_tracking_probe_process import original_probe_context, prepare_probe_payloads - expected = original_probe_context(selected, accepted, self.certificate.binding, source, group=group, names=names, now_ns=now_ns) + expected = original_probe_context(selected, accepted, certificate.binding, source, group=group, names=names, now_ns=now_ns) def prepare_probe(): import json @@ -593,7 +597,7 @@ class LiveTrackingActor: control=endpoint, output=emission, accepted_full30=accepted, - binding=self.certificate.binding, + binding=certificate.binding, response_witness=witness, source=source, evidence_ns=now_ns, @@ -894,7 +898,10 @@ class LiveTrackingActor: offer = self._current_publication_offer(now_ns) if offer is None: return None - pose = validate_response_witness(offer.response_witness, self.certificate.binding, now_ns).last_pose_ns + certificate = self.certificate + if certificate is None: + return None + pose = validate_response_witness(offer.response_witness, certificate.binding, now_ns).last_pose_ns if pose <= self.last_publication_pose_ns: return None self.last_publication_pose_ns = pose @@ -903,23 +910,26 @@ class LiveTrackingActor: def _current_publication_offer(self, now_ns): from openpilot.starpilot.flm.live_tracking_response import response_witness_value, validate_response_witness - offer = self.ingress.latest_offer + ingress, certificate = self.ingress, self.certificate + if ingress is None or certificate is None: + return None + offer = ingress.latest_offer if offer is None: return None try: # Structural validation of the owned old message is not current permission. offer.validate() old = response_witness_value(offer.response_witness) - optimizer = self.ingress.optimizer + optimizer = ingress.optimizer try: - current = validate_response_witness(optimizer.response_witness, self.certificate.binding, now_ns) + current = validate_response_witness(optimizer.response_witness, certificate.binding, now_ns) except (TypeError, ValueError): - self.ingress.interrupt('expired_response_witness' if optimizer._witness_expired(now_ns) - and offer.binding == self.certificate.binding and old.certificate == self.certificate + ingress.interrupt('expired_response_witness' if optimizer._witness_expired(now_ns) + and offer.binding == certificate.binding and old.certificate == certificate else 'fresh_response_witness_unavailable') return None state = optimizer.offer_state - if offer.binding != self.certificate.binding or old.certificate != self.certificate or state is None: + if offer.binding != certificate.binding or old.certificate != certificate or state is None: raise ValueError('trial publication identity changed') if offer.trial_id != state['trial_id']: prior = state.get('prior_accepted') @@ -942,11 +952,11 @@ class LiveTrackingActor: offer = optimizer.offer(now_ns, publication=False) if offer is None: raise ValueError('current trial publication unavailable') - cast(LiveTrackingIngress, self.ingress).latest_offer = offer - validate_response_witness(offer.response_witness, self.certificate.binding, now_ns) + ingress.latest_offer = offer + validate_response_witness(offer.response_witness, certificate.binding, now_ns) return offer except (AttributeError, TypeError, ValueError): - self.ingress.interrupt('fresh_response_witness_unavailable') + ingress.interrupt('fresh_response_witness_unavailable') return None def mark_publication(self, offer): @@ -962,19 +972,20 @@ class LiveTrackingActor: def observe_restored(self, application, offer, *, now_ns): from openpilot.starpilot.flm.live_trial_owner import LiveTrialApplication - if self.ingress is None or type(application) is not LiveTrialApplication: + certificate = self.certificate + if self.ingress is None or certificate is None or type(application) is not LiveTrialApplication: return False if ( application.status != 'restored' - or application.binding != self.certificate.binding + or application.binding != certificate.binding or application.trial_id != offer.history_trial_id or application.applied != offer.target or application.applied_sha256 != offer.target_sha256 or not 0 < application.control_ns <= now_ns <= application.control_ns + 100_000_000 ): return False - validate_response_witness(offer.response_witness, self.certificate.binding, now_ns) - if full_profile_sha256(self.certificate.binding.baseline_revision, dict(application.applied)) != offer.target_sha256: + validate_response_witness(offer.response_witness, certificate.binding, now_ns) + if full_profile_sha256(certificate.binding.baseline_revision, dict(application.applied)) != offer.target_sha256: return False optimizer = self.ingress.optimizer previous = getattr(self.ingress, 'latest_restore_offer', None) diff --git a/openpilot/starpilot/flm/manual_coordinates.py b/openpilot/starpilot/flm/manual_coordinates.py index 8a4488c4aa..ebf4d768fe 100644 --- a/openpilot/starpilot/flm/manual_coordinates.py +++ b/openpilot/starpilot/flm/manual_coordinates.py @@ -182,7 +182,7 @@ def load(cp, controller, params=None): try: profile = parse_document(raw).get(str(cp.carFingerprint)) manual = None if profile is None else profile.manual_coordinates - if manual is None or not any(v for _, v in manual.values): + if profile is None or manual is None or not any(v for _, v in manual.values): return None, 'not_configured' tune = cp.lateralTuning.torque if (profile.basis != (float(tune.latAccelFactor), float(tune.latAccelOffset), float(tune.friction)) diff --git a/openpilot/starpilot/flm/offroad_observed.py b/openpilot/starpilot/flm/offroad_observed.py index 902c9273f6..6223064473 100644 --- a/openpilot/starpilot/flm/offroad_observed.py +++ b/openpilot/starpilot/flm/offroad_observed.py @@ -57,10 +57,13 @@ def merge_sources(sources): group = groups[key] if {window['identity'] for window in group['windows']} & {window['identity'] for window in source['windows']}: raise ValueError('Original advisory windows cannot be counted twice') - group['windows'].extend(source['windows']) + windows, coordinates = group['windows'], group['coordinate_baselines'] + if not isinstance(windows, list) or not isinstance(coordinates, dict): + raise ValueError('Invalid advisory source group') + windows.extend(source['windows']) group['missing_metadata_rows'] += source['missing_metadata_rows'] group['coordinate_baselines'] = { - name: value for name, value in group['coordinate_baselines'].items() if source['coordinate_baselines'].get(name) == value + name: value for name, value in coordinates.items() if source['coordinate_baselines'].get(name) == value } return list(groups.values()) diff --git a/openpilot/starpilot/flm/offroad_runtime.py b/openpilot/starpilot/flm/offroad_runtime.py index 92669e6cd0..e876c51171 100644 --- a/openpilot/starpilot/flm/offroad_runtime.py +++ b/openpilot/starpilot/flm/offroad_runtime.py @@ -112,8 +112,10 @@ def configuration_data(cp, ci, controller, params, *, manual_status): raise ValueError('Invalid reset generation') # Settings identity only. It does not describe current physical calibration. unit = persistent_unit(cp, raw) - epoch = digest(('persistent_vehicle_source_v1', descriptor.cp_sha256, tuple((k, None if raw[k] is None else raw[k].hex()) for k in keys - if k != 'SteeringDelayPreferences' or raw[k] is not None), str(cp.carVin) if unit is None else unit)) + sources = tuple((key, None if value is None else value.hex()) + for key, value in ((name, raw[name]) for name in keys) + if key != 'SteeringDelayPreferences' or value is not None) + epoch = digest(('persistent_vehicle_source_v1', descriptor.cp_sha256, sources, str(cp.carVin) if unit is None else unit)) numeric = baseline_values(controller) if tuple((key, read_saved(params, key, MAX_DOCUMENT_BYTES)) for key in keys) != snapshots: raise ValueError('Steering settings changed during startup') diff --git a/openpilot/starpilot/flm/offroad_worker.py b/openpilot/starpilot/flm/offroad_worker.py index 7a2b8882b2..35eabc2138 100644 --- a/openpilot/starpilot/flm/offroad_worker.py +++ b/openpilot/starpilot/flm/offroad_worker.py @@ -1474,7 +1474,8 @@ class OffroadWorker: for name, _ in qualification_summary(checked)['refusals']): report['refused_parameters'] = [name for name in NAMES if proposal['values'][name] != current[name]] break - if not saved and offered is not None and offered['parameter'].startswith('stable:'): + parameter = offered['parameter'] if offered is not None else None + if not saved and offered is not None and isinstance(parameter, str) and parameter.startswith('stable:'): profile_suggestions = [ {'parameter': name, 'delta': value - current[name], 'whole_windows': selected_profile_windows, 'qualification': 'controller_native_checks_not_passed'} for name, value in offered['values'].items() diff --git a/openpilot/starpilot/flm/selected_effects.py b/openpilot/starpilot/flm/selected_effects.py index 4c29fde74a..8cbbe9a10d 100644 --- a/openpilot/starpilot/flm/selected_effects.py +++ b/openpilot/starpilot/flm/selected_effects.py @@ -377,7 +377,7 @@ def bounded_profile_on_limited_frame(parent): owner = getattr(parent, 'automatic_flm_effects', None) return ( - type(owner) in (TrackingTrialOwner, EffectReplaySource, EffectReplayRecordedSource) + owner is not None and type(owner) in (TrackingTrialOwner, EffectReplaySource, EffectReplayRecordedSource) and type(owner.source) is CanonicalSurfaceEffects and owner.source.allow_limited_profile ) @@ -570,9 +570,12 @@ class EffectReplayTransition: group = {n: self.applied[n] for n in self.names} self.__source = CanonicalSurfaceEffects(group, self.trial.selected_baseline_revision, accumulated=self.applied, allow_limited_profile=True) self.__source_key = key - source.source = self.__source + effects = self.__source + if effects is None: + raise ValueError("Missing confirmed replay effects") + source.source = effects # The ordinary _run -> begin_frame path still resets ALL call counters and # enforces the real frame clock. No mutable frame state crosses transitions. - source.original_effect_anchor = source.source.original_effect_anchor - source.applied_coordinates = source.source.applied_coordinates + source.original_effect_anchor = effects.original_effect_anchor + source.applied_coordinates = effects.applied_coordinates return source diff --git a/openpilot/starpilot/flm/steerlearnerd.py b/openpilot/starpilot/flm/steerlearnerd.py index 90456528ae..7df6cdd3e3 100644 --- a/openpilot/starpilot/flm/steerlearnerd.py +++ b/openpilot/starpilot/flm/steerlearnerd.py @@ -5,7 +5,7 @@ from received source-bound evidence, never another process's startup preference. """ from collections.abc import Callable -from typing import cast +from typing import TypeGuard, cast from openpilot.starpilot.flm.runtime_adapter_registry import SourceState import os @@ -47,12 +47,14 @@ class _SourceDelivery: # A received pose may still need a genuinely newer consumed state. # Poll existing tapes without consuming/reordering their FIFO heads. sockets = (sm.sock['deviceMotion'], *pending_evidence) - if len(sockets) != len(self.evidence_sockets) or any(a is not b for a, b in zip(sockets, self.evidence_sockets, strict=True)): - self.evidence_poller = messaging.Poller() + poller = self.evidence_poller + if (poller is None or len(sockets) != len(self.evidence_sockets) or + any(a is not b for a, b in zip(sockets, self.evidence_sockets, strict=True))): + poller = self.evidence_poller = messaging.Poller() for socket in sockets: - self.evidence_poller.registerSocket(socket) + poller.registerSocket(socket) self.evidence_sockets = sockets - self.evidence_poller.poll(10) + poller.poll(10) sm.update(0) else: sm.update() @@ -157,9 +159,8 @@ def _source_config_binding(source): source.enabled, source.manual, source.persistent_source_epoch, tuple(source.manual_baseline), source.manual_kp) -def _source_config_known(source, now_ns): +def _source_config_known(source: object, now_ns: int) -> TypeGuard[SourceState]: import math - from openpilot.starpilot.flm.runtime_adapter_registry import SourceState return bool(isinstance(source, SourceState) and type(source.configuration_known) is bool and source.configuration_known and type(source.enabled) is bool and type(source.manual) is bool and type(source.observed_ns) is int and type(source.expires_ns) is int and @@ -502,18 +503,17 @@ def run( source = cast(Callable[[int], SourceState | None], reader)(now) now = clock() known = _source_config_known(source, now) - if known and (not source.enabled or source.manual): + if source is not None and known and (not source.enabled or source.manual): source_rejected = True clear('manual_profile_override' if source.manual else 'learning_disabled') last_accepted_source = None return False, now - valid = bool(known and source.enabled and not source.manual and + if not (source is not None and known and source.enabled and not source.manual and type(source.source_epoch) is str and len(source.source_epoch) == 64 and not source.source_epoch.strip('0123456789abcdef') and - (source_cp_sha256 is None or source.cp_sha256 == source_cp_sha256)) - if not valid: + (source_cp_sha256 is None or source.cp_sha256 == source_cp_sha256)): source_rejected = True - if known and source_cp_sha256 is not None and source.cp_sha256 != source_cp_sha256: + if source is not None and known and source_cp_sha256 is not None and source.cp_sha256 != source_cp_sha256: clear('actual_source_identity_changed') else: uncertain('settings_receipt_expired' if source is not None and type(source.expires_ns) is int and source.expires_ns < now @@ -660,7 +660,7 @@ def run( def control(event, current, stamp): nonlocal collector, raw_context, active_key, unavailable_reason valid_source, received_now = source_current() - if not valid_source: + if not valid_source or source is None: return if event.which() == 'starpilotLateralState' and event.starpilotLateralState.learningEvidence.version == 0: if collector is not None: @@ -848,7 +848,7 @@ def run( pending_key = pending_token = None if fitter.child is None: pending_key = pending_token = None - if collector is not None and current_native and active_key is not None: + if collector is not None and current_native and active_key is not None and source is not None: collector.adapter.select_objective(active_key) if collector.context is not None: scope = (collector.context[0], active_key, source.reset) @@ -1053,7 +1053,8 @@ def run( ): publication_result = cached[1][0] message = result_message(publication_result, collector.session, publication_sequence, now, replay_validation=collector.last_validation) - persistence.save_current(collector, now_ns=now, source_epoch=source.source_epoch, reset=source.reset) + if source is not None: + persistence.save_current(collector, now_ns=now, source_epoch=source.source_epoch, reset=source.reset) else: message = messaging.new_message('autoSteeringLearning') value = message.autoSteeringLearning.learning diff --git a/openpilot/starpilot/flm/tests/test_actual_raw_worker.py b/openpilot/starpilot/flm/tests/test_actual_raw_worker.py index d449e55ffc..a07497c326 100644 --- a/openpilot/starpilot/flm/tests/test_actual_raw_worker.py +++ b/openpilot/starpilot/flm/tests/test_actual_raw_worker.py @@ -19,6 +19,7 @@ from opendbc.car import structs from opendbc.car.car_helpers import interfaces from opendbc.car.steering_projection import install_observer, inspect_projection, normalized_applied_command from opendbc.car.toyota.values import CAR +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.cereal.services import SERVICE_LIST from openpilot.starpilot.flm.controller_replay import SelectedControllerFactory, capture_snapshot, frame_input, final_command @@ -112,6 +113,7 @@ def raw_job(cp, runtime, params_store, *, native_refinements=False): row.latAccelFactorFiltered = float(cp.lateralTuning.torque.latAccelFactor) * (1 + .002 * math.sin((block * 400 + tick) / 100)) row.latAccelOffsetFiltered = 0. row.frictionCoefficientFiltered = float(cp.lateralTuning.torque.friction) * (1 + .002 * math.cos((block * 400 + tick) / 100)) + assert native_health is not None native_health.update_msgs(stamp / 1e9, [packet.as_reader()]) apply_native_refinement(controller, cp, native_health, now_ns=stamp, apply=lambda controller=controller, row=row: controller.update_torque_parameters(row.latAccelFactorFiltered, row.latAccelOffsetFiltered, @@ -160,8 +162,9 @@ def raw_job(cp, runtime, params_store, *, native_refinements=False): identity=runtime.identity, generation=runtime.generation, control_ns=stamp, state_ns=stamp, domain='normalized_torque', stage_revision=runtime.descriptor.stage_revision, response_revision='raw-known-plant-v1', requested=final_command(raw), - features=tuple(observer.stage.baseline_ff * value for value in - gates(Objective('feedforward', 'high', 'steady'), observer.stage.speed, observer.stage.setpoint, observer.stage.jerk)), + features=tuple(require_value(observer.stage).baseline_ff * value for value in + gates(Objective('feedforward', 'high', 'steady'), require_value(observer.stage).speed, + require_value(observer.stage).setpoint, require_value(observer.stage).jerk)), baseline_prediction=final_command(raw), enabled=True, manual=False, active=True, valid=True, override=False, fault=False, saturated=False, limited=False, model_wobble=False, controller_chatter=False, @@ -211,8 +214,10 @@ def raw_job(cp, runtime, params_store, *, native_refinements=False): assert all(min(calibration_responses) <= value <= max(calibration_responses) for value in stage_targets), support cpu, wall = time.thread_time_ns(), time.perf_counter_ns() job_now_ns = applied.apply_ns + 2_000_000 if native_refinements else BASE + 300_000_000 + assert adapter is not None snapshot = adapter.fit_job_snapshot(tuple(blocks), job_now_ns, 1, None, control=last_control, output=last_output, physical_context=CONTEXT) + assert adapter is not None export_cost = {'cpu_ns': time.thread_time_ns() - cpu, 'wall_ns': time.perf_counter_ns() - wall, 'json_bytes': len(json.dumps(snapshot).encode()), 'recorded_frames': len(adapter.replay.records), 'blocks': 16, 'support': support} assert snapshot is not None and export_cost['recorded_frames'] == 3200 diff --git a/openpilot/starpilot/flm/tests/test_event_admission_clock.py b/openpilot/starpilot/flm/tests/test_event_admission_clock.py index 9877354ebf..35a4896a23 100644 --- a/openpilot/starpilot/flm/tests/test_event_admission_clock.py +++ b/openpilot/starpilot/flm/tests/test_event_admission_clock.py @@ -50,12 +50,13 @@ class ClockedBoundaryAdapter(BoundaryAdapter, EventCollectionAdapter): super().__init__(*args, **kwargs) self.original_context_receipts = None - def physical_observable(self, row=None, *, value=None): - return super().physical_observable(row if value is None else value) + @staticmethod + def physical_observable(value): + return EventCollectionAdapter.physical_observable(value) - def current_admission(self, profile, control, output, context, *, now_ns=None): + def current_admission(self, profile, control, output, physical_context, *, now_ns=None): self.decisions = now_ns - return BoundaryAdapter.current_admission(self, profile, control, output, context) + return BoundaryAdapter.current_admission(self, profile, control, output, physical_context) def collector_ready(*, clocked): diff --git a/openpilot/starpilot/flm/tests/test_event_application_success.py b/openpilot/starpilot/flm/tests/test_event_application_success.py index a04481a734..b4e76dcb89 100644 --- a/openpilot/starpilot/flm/tests/test_event_application_success.py +++ b/openpilot/starpilot/flm/tests/test_event_application_success.py @@ -64,8 +64,8 @@ def exercise(*, no_new_pose=False): self.installed = True self.fit_profile = profile return True - def current_admission(self, profile, control, output, context): - result = super().current_admission(profile, control, output, context) + def current_admission(self, profile, control, output, physical_context): + result = super().current_admission(profile, control, output, physical_context) admitted.append((phase[0], result.healthy, self.last_physical_ns)) return result diff --git a/openpilot/starpilot/flm/tests/test_event_replay_cost.py b/openpilot/starpilot/flm/tests/test_event_replay_cost.py index 71e8b5a7c7..53681054d0 100644 --- a/openpilot/starpilot/flm/tests/test_event_replay_cost.py +++ b/openpilot/starpilot/flm/tests/test_event_replay_cost.py @@ -127,6 +127,7 @@ def test_transition_reuses_only_exact_plateau_geometry_but_resets_each_real_fram with pytest.raises(ValueError): current.selected_friction(.1, original_anchor=current.original_effect_anchor) if tick >= 102: + assert last is not None assert current.source is last.source last = current assert constructor.call_count <= 101 # Ramp configs change; plateau configs do not. diff --git a/openpilot/starpilot/flm/tests/test_event_support_qualified_subset.py b/openpilot/starpilot/flm/tests/test_event_support_qualified_subset.py index 7057f5f159..7b3fee48ff 100644 --- a/openpilot/starpilot/flm/tests/test_event_support_qualified_subset.py +++ b/openpilot/starpilot/flm/tests/test_event_support_qualified_subset.py @@ -8,6 +8,7 @@ from types import SimpleNamespace import pytest +from openpilot.common.test import require_value from openpilot.starpilot.flm import event_fit_factory as factory from openpilot.starpilot.flm.canonical_surface_adapter import GROUPS from openpilot.starpilot.flm.event_objective import EffectObjective @@ -167,7 +168,7 @@ def test_actual_encoder_endpoint_repeated_under_new_packet_id_is_rejected_before objective = EffectObjective('deadband.low', envelope.trial_names, envelope.trial_anchor, envelope.context_key) # First packet has40 different genuine encoded endpoints; the next NEW ID # repeats them. Renaming a packet cannot manufacture independent support. - packets = tuple({'identity': engine.identity, 'block_id': 'distinct-packet-' + str(index), + packets = tuple({'identity': require_value(engine).identity, 'block_id': 'distinct-packet-' + str(index), 'samples': tuple(points)} for index in range(8)) payload = {'effect_envelope': asdict(envelope), 'physical_context': context, 'raw_blocks': packets} def no_model(*args, **kwargs): diff --git a/openpilot/starpilot/flm/tests/test_event_target_renewal.py b/openpilot/starpilot/flm/tests/test_event_target_renewal.py index 00c9671db4..427502b7bd 100644 --- a/openpilot/starpilot/flm/tests/test_event_target_renewal.py +++ b/openpilot/starpilot/flm/tests/test_event_target_renewal.py @@ -28,7 +28,7 @@ class BoundaryAdapter(SyntheticAdapter): self.last_physical_ns = physical['response_ns'] return super().cohort(control, physical) - def current_admission(self, profile, control, output, context): + def current_admission(self, profile, control, output, physical_context): healthy = self.current_physical_valid and self.last_physical_ns > control.control_ns return CurrentAdmission(control.identity, 'a' * 64, 'b' * 64, min(control.control_ns, output.apply_ns), healthy, control.enabled, control.manual, healthy) diff --git a/openpilot/starpilot/flm/tests/test_full_effect_trace.py b/openpilot/starpilot/flm/tests/test_full_effect_trace.py index 1624135738..f2ba5ca05d 100644 --- a/openpilot/starpilot/flm/tests/test_full_effect_trace.py +++ b/openpilot/starpilot/flm/tests/test_full_effect_trace.py @@ -55,6 +55,7 @@ def test_exact_prior_centered_transition_matches_real_owner_with_jitter_and_with assert ordered(source.source.values)==owner.trace.applied owner.prepare(Admission(p,NOW+40_000_000,True,False,False,v),active=True,current_context=context) replay.source_for_frame(NOW+40_000_000,None) + assert replay.applied is not None assert not any(replay.applied.values()) owner.prepare(Admission(p,NOW+50_000_000,True,False,True,v),active=True,current_context=context) source=replay.source_for_frame(NOW+50_000_000,owner.trace) diff --git a/openpilot/starpilot/flm/tests/test_full_surface_reporting.py b/openpilot/starpilot/flm/tests/test_full_surface_reporting.py index 853ef630b5..3e480c2f03 100644 --- a/openpilot/starpilot/flm/tests/test_full_surface_reporting.py +++ b/openpilot/starpilot/flm/tests/test_full_surface_reporting.py @@ -140,6 +140,9 @@ def test_actual_controller_changed_outside_group_sets_global_applied_status(): output, _, log = controller.update(True, cs, vm, params, False, 0.00001, False, 0.15) assert owner.used and owner.changed runtime._finish_frame(cs, vm, params, log, desired_curvature=0.00001, curvature_limited=False, lat_delay=0.15, requested=output, selected_command=output) + assert runtime.outcome is not None assert runtime.outcome.status == 'applied' + assert runtime.outcome is not None assert runtime.outcome.actual_coordinates == (0.0,) + assert runtime.outcome is not None assert runtime.outcome.effect_applied_profile_sha256 == owner.trace.applied_full_profile_sha256 diff --git a/openpilot/starpilot/flm/tests/test_global_event_capture_floor.py b/openpilot/starpilot/flm/tests/test_global_event_capture_floor.py index 8d4801c0e1..143bd89081 100644 --- a/openpilot/starpilot/flm/tests/test_global_event_capture_floor.py +++ b/openpilot/starpilot/flm/tests/test_global_event_capture_floor.py @@ -20,7 +20,7 @@ class RawEventFixture: envelope = object() identity = IDENTITY source_epoch = '2' * 64 - physical_observable = EventCollectionAdapter.physical_observable + physical_observable = staticmethod(EventCollectionAdapter.physical_observable) cohort = EventCollectionAdapter.cohort raw_maneuver_complete = EventCollectionAdapter.raw_maneuver_complete diff --git a/openpilot/starpilot/flm/tests/test_healthy_maneuver_completion.py b/openpilot/starpilot/flm/tests/test_healthy_maneuver_completion.py index 654906a405..53588b2ac3 100644 --- a/openpilot/starpilot/flm/tests/test_healthy_maneuver_completion.py +++ b/openpilot/starpilot/flm/tests/test_healthy_maneuver_completion.py @@ -8,6 +8,7 @@ from opendbc.car import structs from opendbc.car.car_helpers import interfaces from opendbc.car.steering_projection import install_observer, inspect_projection, normalized_applied_command from opendbc.car.toyota.values import CAR +from openpilot.common.test import require_value from openpilot.cereal import messaging from openpilot.cereal.services import SERVICE_LIST from openpilot.starpilot.flm.controller_replay import SelectedControllerFactory, capture_snapshot, frame_input, final_command @@ -131,8 +132,9 @@ def actual_completion_trace(cp, runtime, params_store, failure): identity=runtime.identity, generation=runtime.generation, control_ns=stamp, state_ns=stamp, domain='normalized_torque', stage_revision=runtime.descriptor.stage_revision, response_revision='raw-known-plant-v1', requested=final_command(raw), - features=tuple(observer.stage.baseline_ff * value for value in - gates(Objective('feedforward', 'high', 'steady'), observer.stage.speed, observer.stage.setpoint, observer.stage.jerk)), + features=tuple(require_value(observer.stage).baseline_ff * value for value in + gates(Objective('feedforward', 'high', 'steady'), require_value(observer.stage).speed, + require_value(observer.stage).setpoint, require_value(observer.stage).jerk)), baseline_prediction=final_command(raw), enabled=True, manual=False, active=True, valid=True, override=False, fault=False, saturated=False, limited=False, model_wobble=False, controller_chatter=False, diff --git a/openpilot/starpilot/flm/tests/test_history_restore.py b/openpilot/starpilot/flm/tests/test_history_restore.py index b132bd53b0..c95d51b5ba 100644 --- a/openpilot/starpilot/flm/tests/test_history_restore.py +++ b/openpilot/starpilot/flm/tests/test_history_restore.py @@ -3,6 +3,7 @@ from dataclasses import replace from types import SimpleNamespace import pytest +from openpilot.common.test import require_value from openpilot.starpilot.flm.full_surface_profile import FullSurfaceEnvelope, RESTORE_POLICY, neutral_coordinates from openpilot.starpilot.flm.full_surface_store import remember_full, load_prior from openpilot.starpilot.flm.tests.test_full_surface_profile import base, profile, wire_profile @@ -12,7 +13,7 @@ def history(): raw = None proposed = None for value in (0.005, 0.010, 0.015, 0.020): - current = base() if raw is None else load_prior(raw, binding=proposed.source_binding()).envelope + current = base() if raw is None else load_prior(raw, binding=require_value(proposed).source_binding()).envelope proposed = current.for_trial(('ff_gain_left',)).with_proposal({'ff_gain_left': value}) raw = remember_full(raw, profile(proposed), validation_sha256='3' * 64) return raw, proposed diff --git a/openpilot/starpilot/flm/tests/test_live_tracking_probe_process.py b/openpilot/starpilot/flm/tests/test_live_tracking_probe_process.py index e5d4e4c862..165b19b501 100644 --- a/openpilot/starpilot/flm/tests/test_live_tracking_probe_process.py +++ b/openpilot/starpilot/flm/tests/test_live_tracking_probe_process.py @@ -225,6 +225,7 @@ def test_actual_optional_child_cancellation_reaps_without_blocking_publication(r now = time.monotonic_ns() try: assert process.submit({'stall': True}, token=('original',), now_ns=now) + assert process.child is not None pid = process.child.pid deadline = time.monotonic()+5. while process.child is not None and time.monotonic() < deadline: diff --git a/openpilot/starpilot/flm/tests/test_live_trial_actual_controller.py b/openpilot/starpilot/flm/tests/test_live_trial_actual_controller.py index a455150b0f..8c4ac985ef 100644 --- a/openpilot/starpilot/flm/tests/test_live_trial_actual_controller.py +++ b/openpilot/starpilot/flm/tests/test_live_trial_actual_controller.py @@ -4,6 +4,7 @@ from dataclasses import replace from types import SimpleNamespace import math import pytest +from openpilot.common.test import require_value from openpilot.starpilot.flm.live_trial_owner import TrackingTrialOwner from openpilot.starpilot.flm.tests.test_live_trial_owner import offer @@ -51,13 +52,15 @@ def test_actual_controller_hooks_and_native_packet_are_preserved(domain, curvatu controller.automatic_flm_effects = owner result, _, _ = controller.update(True, ci.CS.out, vm, SimpleNamespace(angleOffsetDeg=0.0, roll=0.0), False, curvature, False, 0.2) assert math.isfinite(float(result)) and abs(float(result)) <= 1.0 - assert owner.used and owner.source.stage_calls == 1 + assert owner.used and require_value(owner.source).stage_calls == 1 assert owner.frame_complete(owner.domain) ack = owner.acknowledge_frame(True) assert ack is not None and ack.status == 'applied' if domain == 'pid': + assert owner.source is not None assert owner.source.pid_error_calls == 1 else: + assert owner.source is not None assert owner.source.friction_calls == 1 _, packets, witness = apply(ci, control(float(result))) if witness is not None: diff --git a/openpilot/starpilot/flm/tests/test_live_trial_global_runtime.py b/openpilot/starpilot/flm/tests/test_live_trial_global_runtime.py index 6b7e5c2d59..9a2c263241 100644 --- a/openpilot/starpilot/flm/tests/test_live_trial_global_runtime.py +++ b/openpilot/starpilot/flm/tests/test_live_trial_global_runtime.py @@ -164,6 +164,7 @@ class LiveControls: assert type(runtime.outcome) is LiveTrialApplication assert runtime.outcome.status == 'applied' assert runtime.outcome.control_ns == BASE + self.tick * DT + assert self.latest is not None assert runtime.outcome.sequence == self.latest.sequence assert runtime.profile is None and runtime.validation is None assert owner.confirmed_full == self.latest.baseline or owner.offer.phase == 'confirmed' diff --git a/openpilot/starpilot/flm/tests/test_live_trial_owner.py b/openpilot/starpilot/flm/tests/test_live_trial_owner.py index 3a05b0a7e9..e8421d281d 100644 --- a/openpilot/starpilot/flm/tests/test_live_trial_owner.py +++ b/openpilot/starpilot/flm/tests/test_live_trial_owner.py @@ -57,6 +57,7 @@ def test_pending_trial_is_distinct_from_replay_and_small_slewed(): assert owner.prepare(o, now_ns=o.observed_ns, permission=True, binding=o.binding) assert 0 < owner.applied_full['ff_gain_left'] <= 0.00005 assert owner.confirmed_full == o.baseline + assert owner.application is not None assert owner.application.confirmed_target_sha256 == '' assert owner.trace is None diff --git a/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py b/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py index 7758357a75..14f0d644ee 100644 --- a/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py +++ b/openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py @@ -290,7 +290,7 @@ assert 'opendbc.car.car_helpers' not in sys.modules process = PythonProcess('steerlearnerd', 'openpilot.starpilot.flm.offroad_daemon', lambda *args: True, restart_on_exit=True) process.start() child = process.proc - self.assertIsNotNone(child) + assert child is not None assert child is not None pid = child.pid try: @@ -308,6 +308,7 @@ assert 'opendbc.car.car_helpers' not in sys.modules self.fail('Manager-launched driving image did not become ready') self.assertTrue(process.recover()) self.assertIs(process.proc, child) + assert process.proc is not None self.assertEqual(process.proc.pid, pid) self.assertIsNone(child.exitcode) self.assertEqual(params.get(KEY), b'declared-preserved-manager-store') @@ -356,6 +357,7 @@ with patch.object(daemon.messaging,'SubMaster',return_value=sm), patch.object(da deadline = time.monotonic() + 20 while time.monotonic() < deadline: if child.poll() is not None: + assert child.stderr is not None self.fail('Lifecycle child exited early: ' + child.stderr.read()[-2000:]) try: state = json.loads(report.read_text()) diff --git a/openpilot/starpilot/flm/tests/test_selected_effect_owner.py b/openpilot/starpilot/flm/tests/test_selected_effect_owner.py index 9dff9f9333..daa101c640 100644 --- a/openpilot/starpilot/flm/tests/test_selected_effect_owner.py +++ b/openpilot/starpilot/flm/tests/test_selected_effect_owner.py @@ -159,6 +159,7 @@ def test_trial_group_switch_preserves_full30_state_and_cas_without_step_jump(): ) context2 = dict(context, current_full_profile_sha256=old.full_profile_sha256) next_owner.prepare(Admission(p2, NOW + 10_000_000, True, False, True, v2), active=True, current_context=context2) + assert next_owner.trace is not None assert next_owner.trace.before == tuple(before.items()) assert next_owner.applied_full['ff_gain_left'] >= before['ff_gain_left'] assert 0 < next_owner.applied_full['turn_in_threshold_reduction_left'] <= 0.005 * 0.01 diff --git a/openpilot/starpilot/flm/tests/test_source_baseline_recheck.py b/openpilot/starpilot/flm/tests/test_source_baseline_recheck.py index 20088c5992..52a8de2e83 100644 --- a/openpilot/starpilot/flm/tests/test_source_baseline_recheck.py +++ b/openpilot/starpilot/flm/tests/test_source_baseline_recheck.py @@ -4,6 +4,7 @@ import hashlib import math import pytest +from openpilot.common.test import require_value from openpilot.starpilot.flm.canonical_surface_adapter import NAMES from openpilot.starpilot.flm.live_tracking import LiveTrackingOptimizer from openpilot.starpilot.flm.tests.test_live_tracking import episode @@ -176,11 +177,13 @@ def test_repeated_baseline_ack_does_not_move_first_boundary_or_erase_new_baselin return_phase(d) o = d.owner assert d.ack() + assert o.source_recheck is not None first = o.source_recheck.first_ack_ns row,_ = d.row(error=.045) assert [v.episode_id for v in o.source_recheck.baseline] == [row.episode_id] for _ in range(10): assert d.ack() + assert o.source_recheck is not None assert o.source_recheck.first_ack_ns == first assert [v.episode_id for v in o.source_recheck.baseline] == [row.episode_id] @@ -266,10 +269,10 @@ def test_return_baseline_requires_its_own_current_exact_ack(bad): 'wrong_hash': {'target_sha256': first.target_sha256}, 'stale': {'control_ns': d.now-100_000_001}}[bad] assert not d.ack(offer, **changes) - assert o.source_recheck.first_ack_ns == 0 and not offer_state(o)['accepted'] + assert require_value(o.source_recheck).first_ack_ns == 0 and not offer_state(o)['accepted'] row, admitted = d.row(error=.045, renew=False) - assert not admitted and not o.source_recheck.baseline - assert row.episode_id not in {v.episode_id for v in o.source_recheck.before} + assert not admitted and not require_value(o.source_recheck).baseline + assert row.episode_id not in {v.episode_id for v in require_value(o.source_recheck).before} def test_return_baseline_excludes_pre_ack_partial_duplicate_and_unmatched_windows(): @@ -277,11 +280,14 @@ def test_return_baseline_excludes_pre_ack_partial_duplicate_and_unmatched_window return_phase(d) o = d.owner assert d.ack() + assert o.source_recheck is not None boundary = o.source_recheck.first_ack_ns row,_ = d.row(error=.045) + assert o.source_recheck is not None assert len(o.source_recheck.baseline) == 1 refresh(o,d.now) assert not o.observe_episode(row,now_ns=d.now) + assert o.source_recheck is not None assert len(o.source_recheck.baseline) == 1 unmatched, admitted = d.row(error=0.,goal=.4,kind='large') assert not admitted and len(o.source_recheck.baseline) == 1 @@ -290,6 +296,7 @@ def test_return_baseline_excludes_pre_ack_partial_duplicate_and_unmatched_window crossing = replace(row,episode_id='e'*64,start_ns=boundary-100_000_000,end_ns=boundary+1_000_000_000) refresh(o,d.now) assert not o.observe_episode(crossing,now_ns=d.now) + assert o.source_recheck is not None assert len(o.source_recheck.baseline) == 1 diff --git a/openpilot/starpilot/flm/torque_adapter.py b/openpilot/starpilot/flm/torque_adapter.py index 23fbcddc6f..ccbddbd204 100644 --- a/openpilot/starpilot/flm/torque_adapter.py +++ b/openpilot/starpilot/flm/torque_adapter.py @@ -104,6 +104,8 @@ class TorqueStageOwner: def _tick(self, active): a = self.admission + if a is None: + raise ValueError("Missing torque learning admission") v = a.replay_validation exact = isinstance(v, ReplayValidation) and v.baseline_revision == self.baseline_revision and v.physical_model_revision == self.physical_model_revision return self.owner.tick( diff --git a/openpilot/starpilot/galaxy/companion_uplink_daemon.py b/openpilot/starpilot/galaxy/companion_uplink_daemon.py index f0f15c46d5..9168c17248 100644 --- a/openpilot/starpilot/galaxy/companion_uplink_daemon.py +++ b/openpilot/starpilot/galaxy/companion_uplink_daemon.py @@ -48,8 +48,11 @@ def main(): sys.executable, '-u', '-m', 'openpilot.starpilot.galaxy.companion_uplink_worker'], cwd=BASEDIR, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, bufsize=0) if child is not None: - child.stdin.write(json.dumps({'lease': lease, 'updated': time.monotonic()}).encode() + b'\n') - child.stdin.flush() + stdin = child.stdin + if stdin is None: + raise OSError("Phone uplink lease pipe unavailable") + stdin.write(json.dumps({'lease': lease, 'updated': time.monotonic()}).encode() + b'\n') + stdin.flush() except (OSError, ValueError, KeyError, subprocess.SubprocessError): if child is not None: stop_worker(child) diff --git a/openpilot/starpilot/galaxy/companion_uplink_worker.py b/openpilot/starpilot/galaxy/companion_uplink_worker.py index f0e9bc6202..9299425d57 100644 --- a/openpilot/starpilot/galaxy/companion_uplink_worker.py +++ b/openpilot/starpilot/galaxy/companion_uplink_worker.py @@ -188,7 +188,7 @@ def main(): raw, buffer = buffer.split(b'\n', 1) message = json.loads(raw) last_input = time.monotonic() - if not fresh(message, time.monotonic()): + if message is None or not fresh(message, time.monotonic()): break lease = message.get('lease') raw_routes = command(['ip', '-j', '-4', 'route', 'show', 'table', 'main']).stdout diff --git a/openpilot/starpilot/galaxy/defaults_recovery.py b/openpilot/starpilot/galaxy/defaults_recovery.py index 642badd5d1..69284c2449 100644 --- a/openpilot/starpilot/galaxy/defaults_recovery.py +++ b/openpilot/starpilot/galaxy/defaults_recovery.py @@ -99,8 +99,9 @@ class DefaultsRecovery: state = self.gateway.page(page, token, generation) with self.gateway.lock: fresh = self.gateway.views[state['view']].rows - candidates = [(i, row) for i, row in enumerate(fresh) if row_default(row, allow_inactive=True) is not None and - row_default(row, allow_inactive=True).key == row_default(original, allow_inactive=True).key] + default = row_default(original, allow_inactive=True) + candidates = [(i, row) for i, row in enumerate(fresh) + if default is not None and (current := row_default(row, allow_inactive=True)) is not None and current.key == default.key] if len(candidates) != 1: return {'saved': False, 'applied': applied, 'reason': 'Settings became unavailable', 'refresh': True} index, row = candidates[0] diff --git a/openpilot/starpilot/galaxy/flm_diagnostics.py b/openpilot/starpilot/galaxy/flm_diagnostics.py index 500c6fc85e..bce30125fc 100644 --- a/openpilot/starpilot/galaxy/flm_diagnostics.py +++ b/openpilot/starpilot/galaxy/flm_diagnostics.py @@ -8,7 +8,7 @@ import re import stat from typing import Any -from capnp import KjException +from capnp.lib.capnp import KjException from openpilot.starpilot.connect.provider import cloudlog_root from openpilot.starpilot.flm.offroad_cache import AssessmentCache, directory_for_params diff --git a/openpilot/starpilot/galaxy/flm_saved_settings.py b/openpilot/starpilot/galaxy/flm_saved_settings.py index 013de45ff1..2e3bf24ea4 100644 --- a/openpilot/starpilot/galaxy/flm_saved_settings.py +++ b/openpilot/starpilot/galaxy/flm_saved_settings.py @@ -1,6 +1,6 @@ """Read-only saved settings for the current vehicle, never startup authority.""" -from capnp import KjException +from capnp.lib.capnp import KjException from opendbc.car.structs import car from openpilot.starpilot.flm.learned_lifecycle import decode from openpilot.starpilot.flm.offroad_store import KEY, MAX_BYTES, NAMESPACE diff --git a/openpilot/starpilot/galaxy/flm_training_results.py b/openpilot/starpilot/galaxy/flm_training_results.py index 43f5851775..20cc9ad0ff 100644 --- a/openpilot/starpilot/galaxy/flm_training_results.py +++ b/openpilot/starpilot/galaxy/flm_training_results.py @@ -24,7 +24,7 @@ class FlmTrainingResults: return result def preference(self): - from capnp import KjException + from capnp.lib.capnp import KjException from opendbc.car.structs import car from openpilot.starpilot.lateral.learning_preferences import KEY, MAX_BYTES, LEGACY_KEY, read_preference from openpilot.starpilot.saved_source import read_saved diff --git a/openpilot/starpilot/galaxy/recording_library.py b/openpilot/starpilot/galaxy/recording_library.py index d692dae6d9..b7a169eaa3 100644 --- a/openpilot/starpilot/galaxy/recording_library.py +++ b/openpilot/starpilot/galaxy/recording_library.py @@ -185,6 +185,8 @@ class RecordingLibrary: not _same_directory(fd, root, segment_name) or any(n.endswith('.lock') for n in os.listdir(fd))): raise PermissionError('Recording action is no longer available') if action == 'rename': + if name is None: + raise ValueError('Missing recording name') os.setxattr(fd, NAME_ATTR, name.encode()) elif action == 'preserve': if payload['preserved']: diff --git a/openpilot/starpilot/galaxy/settings.py b/openpilot/starpilot/galaxy/settings.py index a4fcb2255f..43db72a97a 100644 --- a/openpilot/starpilot/galaxy/settings.py +++ b/openpilot/starpilot/galaxy/settings.py @@ -319,11 +319,14 @@ class LiveContextSource: return False try: self._messages() - if not self.borrowed_messages and not hasattr(self.messages, 'snapshot'): - self.messages.update(0) + messages = self.messages + if messages is None: + return False + if not self.borrowed_messages and not hasattr(messages, 'snapshot'): + messages.update(0) if self.physical is None: from openpilot.starpilot.drive_state.evidence import PhysicalSource - self.physical = PhysicalSource(self.messages, mono=self.mono_clock, boot=self.boot_clock) + self.physical = PhysicalSource(messages, mono=self.mono_clock, boot=self.boot_clock) return self.physical.allowed() except (OSError, RuntimeError, AttributeError, KeyError, TypeError, ValueError): return False @@ -672,7 +675,7 @@ class SettingsGateway: if page == "power": state = self._power_owner(ctx).snapshot() rows = tuple(replace(row, value=row.value.removesuffix(" h").removesuffix(" V"), choices=(), - default_value=row.default_value.removesuffix(" h").removesuffix(" V"), + default_value=None if row.default_value is None else row.default_value.removesuffix(" h").removesuffix(" V"), minimum=1 if row.key == HOURS else 11.8, maximum=30 if row.key == HOURS else 12.5, step=1 if row.key == HOURS else 0.1, unit="h" if row.key == HOURS else "V") if row.key in (HOURS, VOLTS) else row for row in state.rows) @@ -777,11 +780,12 @@ class SettingsGateway: visible[name] = found return found if page == "hub": - result["sections"] = [] + sections = [] for section_id, title, names in CAR_CONTROL_SECTIONS: pages = [{"id": name, "title": page_state(name).title} for name in names if has_car_control(name)] if pages: - result["sections"].append({"id": section_id, "title": title, "pages": pages}) + sections.append({"id": section_id, "title": title, "pages": pages}) + result["sections"] = sections else: for source, projected in zip(state.rows, result["rows"], strict=False): if source.page: diff --git a/openpilot/starpilot/galaxy/test_projection_phone_window_http.py b/openpilot/starpilot/galaxy/test_projection_phone_window_http.py index c661a13c78..32d14f05a5 100644 --- a/openpilot/starpilot/galaxy/test_projection_phone_window_http.py +++ b/openpilot/starpilot/galaxy/test_projection_phone_window_http.py @@ -39,7 +39,7 @@ class AA: def call(self, command, **kwargs): assert command == 'phone_window' self.calls.append(kwargs) - code, data, _ = self.http('/api/starport/source/' + kwargs['source']) # ty: ignore[call-non-callable] # set by the test + code, data, _ = self.http('/api/starport/source/' + kwargs['source']) # ty: ignore[not-callable] # set by the test assert code == 200 and data == {'valid': True}, 'Source proof was not live' if not self.window: return {'handled': False} diff --git a/openpilot/starpilot/galaxy/test_starport_http.py b/openpilot/starpilot/galaxy/test_starport_http.py index 4b1601ecee..d06dcb5f9d 100644 --- a/openpilot/starpilot/galaxy/test_starport_http.py +++ b/openpilot/starpilot/galaxy/test_starport_http.py @@ -79,7 +79,7 @@ def api(tmp_path): self.stop_error = False self.stop_completes = True def call(self, command, **kwargs): - assert command in ('status', 'stop') or self.verifier.valid(kwargs['source']) + assert command in ('status', 'stop') or (self.verifier is not None and self.verifier.valid(kwargs['source'])) self.calls.append((command, dict(kwargs))) if command == 'status': return {'status': {'receiver_address': self.receiver, 'receiver_name': 'My car', 'state': 'streaming' if self.running else 'idle', diff --git a/openpilot/starpilot/galaxy/tests/test_auth_runtime.py b/openpilot/starpilot/galaxy/tests/test_auth_runtime.py index d172e3d5a0..6db0aa1912 100644 --- a/openpilot/starpilot/galaxy/tests/test_auth_runtime.py +++ b/openpilot/starpilot/galaxy/tests/test_auth_runtime.py @@ -10,6 +10,7 @@ import threading import unittest from unittest import mock +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.access import GalaxyAccessOwner from openpilot.starpilot.galaxy.http_server import ReverseProxy from openpilot.starpilot.galaxy.server import _LocalHTTPServer, allowed_authority, direct_local_connection, make_server @@ -104,6 +105,7 @@ class AuthRuntimeTest(unittest.TestCase): self.server = None def request(self, path, *, method='GET', body=None, headers=None, local=False): + assert self.server is not None connection = http.client.HTTPConnection('127.0.0.1', self.server.server_port, timeout=2) try: request_headers = {} if local else {'Forwarded': 'for=203.0.113.8'} @@ -115,6 +117,7 @@ class AuthRuntimeTest(unittest.TestCase): connection.close() def post(self, path, payload, *, headers=None, local=False): + assert self.server is not None merged = {'Content-Type': 'application/json', 'Origin': f'http://127.0.0.1:{self.server.server_port}'} merged.update(headers or {}) return self.request(path, method='POST', body=json.dumps(payload), headers=merged, local=local) @@ -267,10 +270,10 @@ class AuthRuntimeTest(unittest.TestCase): def test_idle_connection_and_incomplete_body_do_not_block_other_requests(self): for pending in (b'', ('POST /api/auth/login HTTP/1.1\r\n' + - f'Host: 127.0.0.1:{self.server.server_port}\r\n' + - f'Origin: http://127.0.0.1:{self.server.server_port}\r\n' + + f'Host: 127.0.0.1:{require_value(self.server).server_port}\r\n' + + f'Origin: http://127.0.0.1:{require_value(self.server).server_port}\r\n' + 'Content-Type: application/json\r\nContent-Length: 100\r\n\r\n{').encode()): - with self.subTest(pending=bool(pending)), socket.create_connection(('127.0.0.1', self.server.server_port), timeout=2) as held: + with self.subTest(pending=bool(pending)), socket.create_connection(('127.0.0.1', require_value(self.server).server_port), timeout=2) as held: if pending: held.sendall(pending) self.assertEqual(self.request('/api/auth/session')[0], 200) @@ -282,7 +285,9 @@ class AuthRuntimeTest(unittest.TestCase): condition = threading.Condition() accepted = 0 finished = 0 + assert self.server is not None setup = self.server.RequestHandlerClass.setup + assert self.server is not None finish = self.server.RequestHandlerClass.finish def observed_setup(handler): @@ -307,10 +312,12 @@ class AuthRuntimeTest(unittest.TestCase): mock.patch.object(self.server, 'loopback', return_value=False): try: for _ in range(self.server.MAX_CONNECTIONS): + assert self.server is not None held.append(socket.create_connection(('127.0.0.1', self.server.server_port), timeout=2)) with condition: - self.assertTrue(condition.wait_for(lambda: accepted == self.server.MAX_CONNECTIONS, timeout=2)) + self.assertTrue(condition.wait_for(lambda: accepted == require_value(self.server).MAX_CONNECTIONS, timeout=2)) admission_started = threading.Event() + assert self.server is not None process_request = self.server.process_request def waiting_request(request, address): @@ -330,7 +337,7 @@ class AuthRuntimeTest(unittest.TestCase): for connection in held: connection.close() with condition: - self.assertTrue(condition.wait_for(lambda: finished >= self.server.MAX_CONNECTIONS, timeout=2)) + self.assertTrue(condition.wait_for(lambda: finished >= require_value(self.server).MAX_CONNECTIONS, timeout=2)) self.assertEqual(self.request('/api/auth/session')[0], 200) with mock.patch.object(_LocalHTTPServer, 'REQUEST_TIMEOUT', 0.05): with socket.create_connection(('127.0.0.1', self.server.server_port), timeout=2) as idle: diff --git a/openpilot/starpilot/galaxy/tests/test_companion_http.py b/openpilot/starpilot/galaxy/tests/test_companion_http.py index e301ee017b..fdc4cc5d89 100644 --- a/openpilot/starpilot/galaxy/tests/test_companion_http.py +++ b/openpilot/starpilot/galaxy/tests/test_companion_http.py @@ -7,6 +7,7 @@ from unittest.mock import Mock, patch import pytest +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.access import GalaxyAccessOwner from openpilot.starpilot.galaxy.companion import CompanionRegistry from openpilot.starpilot.galaxy.server import make_server @@ -186,7 +187,7 @@ def test_phone_location_needs_local_session(tmp_path): with patch('openpilot.starpilot.galaxy.server.direct_local_connection', return_value=True): connection = http.client.HTTPConnection('127.0.0.1', server.server_port, timeout=3) connection.request('GET', '/api/auth/session') - cookie = connection.getresponse().getheader('Set-Cookie').split(';', 1)[0] + cookie = require_value(connection.getresponse().getheader('Set-Cookie')).split(';', 1)[0] connection.close() assert post(fix, cookie) == (200, {'ok': True}) assert post({**fix, 'ageMs': 5000}, cookie) == (400, {'error': 'Location is too old'}) diff --git a/openpilot/starpilot/galaxy/tests/test_device_state.py b/openpilot/starpilot/galaxy/tests/test_device_state.py index 907ae92c75..b89318385c 100644 --- a/openpilot/starpilot/galaxy/tests/test_device_state.py +++ b/openpilot/starpilot/galaxy/tests/test_device_state.py @@ -214,10 +214,13 @@ class SharedDeviceStateTest(unittest.TestCase): factory.assert_called_once_with() self.assertIs(local.device_state_source.messages, self.shared) self.assertIs(local.evidence_source, self.shared) + assert self.shared.thread is not None self.assertTrue(self.shared.thread.is_alive()) remote.server_close() + assert self.shared.thread is not None self.assertTrue(self.shared.thread.is_alive()) local.server_close() + assert self.shared.thread is not None self.assertFalse(self.shared.thread.is_alive()) self.assertIsNone(local.device_state_source.sample()['state']) diff --git a/openpilot/starpilot/galaxy/tests/test_drive_stats_background.py b/openpilot/starpilot/galaxy/tests/test_drive_stats_background.py index 963449a530..5bf7c177ef 100644 --- a/openpilot/starpilot/galaxy/tests/test_drive_stats_background.py +++ b/openpilot/starpilot/galaxy/tests/test_drive_stats_background.py @@ -7,6 +7,7 @@ import time from pathlib import Path from unittest import TestCase +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.drive_stats import DriveStatsOwner @@ -71,7 +72,7 @@ class BackgroundHistoryTest(TestCase): allowed.set() self.assertTrue(complete.wait(2), 'offroad must resume without requests') deadline = time.monotonic() + 2 - while owner._worker.is_alive() and time.monotonic() < deadline: + while require_value(owner._worker).is_alive() and time.monotonic() < deadline: time.sleep(0.01) self.assertEqual(owner.snapshot()['totals']['drives'], 1) finally: @@ -82,10 +83,13 @@ class BackgroundHistoryTest(TestCase): deadline = time.monotonic() + 2 while restored._worker is None and time.monotonic() < deadline: time.sleep(0.01) + assert restored._worker is not None restored._worker.join(2) self.assertEqual(calls, ['example', 'example']) self.assertEqual(restored.snapshot()['totals']['drives'], 1) finally: restored.close() + assert owner._scheduler is not None self.assertFalse(owner._scheduler.is_alive()) + assert restored._scheduler is not None self.assertFalse(restored._scheduler.is_alive()) diff --git a/openpilot/starpilot/galaxy/tests/test_drive_stats_http.py b/openpilot/starpilot/galaxy/tests/test_drive_stats_http.py index bed34081f1..fc25ddaccc 100644 --- a/openpilot/starpilot/galaxy/tests/test_drive_stats_http.py +++ b/openpilot/starpilot/galaxy/tests/test_drive_stats_http.py @@ -5,6 +5,7 @@ import tempfile import threading import unittest +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.access import GalaxyAccessOwner from openpilot.starpilot.galaxy.server import make_server @@ -45,7 +46,7 @@ class DriveStatsHTTPTest(unittest.TestCase): conn.request('GET' if payload is None else 'POST', path, None if payload is None else json.dumps(payload), headers) response = conn.getresponse() if response.getheader('Set-Cookie'): - cookie[0] = response.getheader('Set-Cookie').split(';', 1)[0] + cookie[0] = require_value(response.getheader('Set-Cookie')).split(';', 1)[0] return response.status, json.loads(response.read()) finally: conn.close() diff --git a/openpilot/starpilot/galaxy/tests/test_flm_backup.py b/openpilot/starpilot/galaxy/tests/test_flm_backup.py index 0b3365251a..0433883051 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_backup.py +++ b/openpilot/starpilot/galaxy/tests/test_flm_backup.py @@ -257,7 +257,7 @@ class FlmBackupTest(unittest.TestCase): cp = self.fixture.context.value.cp effect, status = load(cp, self.scope.controller_mode, self.params) self.assertEqual(status, 'configured') - self.assertIsNotNone(effect) + assert effect is not None self.assertEqual(dict(effect.profile.values), self.row['values']) frame = StageFrame(25., .3, 0., .3, .3, True, False, False) effect.begin_frame() @@ -291,7 +291,9 @@ class FlmBackupTest(unittest.TestCase): intent = self.gateway.preview(page['view'], index, 0, *self.identity, value=.5) self.assertTrue(self.gateway.confirm(intent['intent'], *self.identity)) profile = parse_document(Path(self.params.get_param_path(DOCUMENT_KEY)).read_bytes())[str(self.fixture.context.value.cp.carFingerprint)] + assert profile.manual_coordinates is not None self.assertEqual(dict(profile.manual_coordinates.values)['friction_threshold_mid'], .0036) + assert profile.manual_coordinates is not None self.assertEqual(dict(profile.manual_coordinates.values)['ff_gain_left'], .005) self.assertEqual(decode(self.stored()).get(NAMESPACE, {}), {}) diff --git a/openpilot/starpilot/galaxy/tests/test_local_hostname_runtime.py b/openpilot/starpilot/galaxy/tests/test_local_hostname_runtime.py index fb29be731e..fa5e6f9d2a 100644 --- a/openpilot/starpilot/galaxy/tests/test_local_hostname_runtime.py +++ b/openpilot/starpilot/galaxy/tests/test_local_hostname_runtime.py @@ -8,6 +8,7 @@ from types import SimpleNamespace import unittest from unittest.mock import patch +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.http_server import ReverseProxy from openpilot.starpilot.galaxy.server import make_remote_server, make_server from openpilot.starpilot.galaxy.tests import test_auth_runtime @@ -45,6 +46,7 @@ class HostnameRuntimeTest(unittest.TestCase): def test_rebinding_matching_origin_and_forwarded_local_cookie_are_denied(self): cookie = self.runtime.request('/api/auth/session', local=True, headers={'Host': self.host})[2]['Set-Cookie'].split(';', 1)[0] for host in ('evil.example', 'comma.evil.example', 'anything.home.example'): + assert self.runtime.server is not None authority = f'{host}:{self.runtime.server.server_port}' headers = {'Host': authority, 'Origin': 'http://' + authority, 'Cookie': cookie} self.assertEqual(self.runtime.request('/api/auth/session', local=True, headers=headers)[0], 403) @@ -68,6 +70,7 @@ class HostnameRuntimeTest(unittest.TestCase): self.assertEqual(self.runtime.post('/api/auth/logout', {}, local=True, headers={'Host': host, 'Origin': 'http://' + host})[0], 403) def test_arbitrary_a_only_alias_only_redirects_landing_to_socket_address(self): + assert self.runtime.server is not None port = self.runtime.server.server_port target = f'http://127.0.0.1:{port}/' for host in ('custom.home.example', f'custom.home.example:{port}', f'evil.example:{port}'): @@ -96,7 +99,7 @@ class HostnameRuntimeTest(unittest.TestCase): def test_duplicate_host_or_origin_is_not_an_allowlist_bypass(self): for extra in ('Host: evil.example\r\n', f'Origin: http://evil.example\r\nOrigin: http://{self.host}\r\n'): - with socket.create_connection(('127.0.0.1', self.runtime.server.server_port), timeout=2) as connection: + with socket.create_connection(('127.0.0.1', require_value(self.runtime.server).server_port), timeout=2) as connection: connection.sendall(f'GET /api/auth/session HTTP/1.1\r\nHost: {self.host}\r\n{extra}Connection: close\r\n\r\n'.encode()) response = http.client.HTTPResponse(connection) response.begin() diff --git a/openpilot/starpilot/galaxy/tests/test_local_hostnames.py b/openpilot/starpilot/galaxy/tests/test_local_hostnames.py index b036857e98..864b55b3f9 100644 --- a/openpilot/starpilot/galaxy/tests/test_local_hostnames.py +++ b/openpilot/starpilot/galaxy/tests/test_local_hostnames.py @@ -91,10 +91,11 @@ class LocalHostnameTest(unittest.TestCase): def test_bad_child_results_and_concurrent_lookup_fail_closed(self): for stdout in (b'bad JSON', b'{}', b'[null]', b'["evil.example:8082"]', b'["10.0.2.244"]', b'x' * 8193): self.assertEqual(LocalHostnames(run=Mock(return_value=SimpleNamespace(stdout=stdout))).names(DESTINATION), ()) - source = LocalHostnames(run=Mock()) + run = Mock() + source = LocalHostnames(run=run) with source.lock: self.assertEqual(source.names(DESTINATION), ()) - source.run.assert_not_called() + run.assert_not_called() def test_slow_ptr_keeps_names_already_independently_confirmed(self): published = [] diff --git a/openpilot/starpilot/galaxy/tests/test_managed.py b/openpilot/starpilot/galaxy/tests/test_managed.py index 3d3294dad9..694c3778e8 100644 --- a/openpilot/starpilot/galaxy/tests/test_managed.py +++ b/openpilot/starpilot/galaxy/tests/test_managed.py @@ -78,7 +78,7 @@ managed.main() class ManagedGalaxyTest(unittest.TestCase): def test_manager_runs_offroad_and_onroad_until_explicitly_disabled(self): proc = managed_processes['galaxy'] - self.assertIsInstance(proc, PythonProcess) + assert isinstance(proc, PythonProcess) self.assertEqual(proc.module, 'openpilot.starpilot.galaxy.managed') with tempfile.TemporaryDirectory() as directory, \ mock.patch.object(proc, 'start') as start, mock.patch.object(proc, 'stop') as stop: diff --git a/openpilot/starpilot/galaxy/tests/test_model_recording.py b/openpilot/starpilot/galaxy/tests/test_model_recording.py index 325101530b..6629fdab1b 100644 --- a/openpilot/starpilot/galaxy/tests/test_model_recording.py +++ b/openpilot/starpilot/galaxy/tests/test_model_recording.py @@ -61,6 +61,6 @@ class ModelRecordingTest(unittest.TestCase): time.sleep(0.05) self.assertTrue(owner.publish(publisher, BASE + 5_000_000_000)) received = messaging.recv_one(subscriber) - self.assertIsNotNone(received) + assert received is not None self.assertEqual(received.which(), 'logMessage') self.assertEqual(logged_model_load(str(received.logMessage)), load) diff --git a/openpilot/starpilot/galaxy/tests/test_models.py b/openpilot/starpilot/galaxy/tests/test_models.py index fab494db8a..23234f0822 100644 --- a/openpilot/starpilot/galaxy/tests/test_models.py +++ b/openpilot/starpilot/galaxy/tests/test_models.py @@ -7,6 +7,7 @@ import tempfile import threading import unittest +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.access import GalaxyAccessOwner from openpilot.starpilot.galaxy.server import make_server from openpilot.starpilot.models.manager import ModelManager, preferences @@ -126,7 +127,7 @@ class LocalModelManagerHttpTest(unittest.TestCase): body=None if payload is None else json.dumps(payload), headers=headers) response = connection.getresponse() if response.getheader('Set-Cookie'): - cookie[0] = response.getheader('Set-Cookie').split(';', 1)[0] + cookie[0] = require_value(response.getheader('Set-Cookie')).split(';', 1)[0] return response.status, json.loads(response.read()) finally: connection.close() @@ -152,7 +153,9 @@ class LocalModelManagerHttpTest(unittest.TestCase): self.assertEqual(request('/api/models/laboratory', pair)[0], 200) self.assertEqual(request('/api/models/laboratory', {**pair, 'enabled': True})[0], 409) self.assertEqual(request('/api/models/laboratory/download', {'model': 'gwm8223'})[0], 200) + assert manager.worker is not None manager.worker.join(3) + assert manager.worker is not None self.assertFalse(manager.worker.is_alive()) self.assertEqual(manager.snapshot()['progress'], 'HTTP fixture disables network') self.assertEqual(request('/api/models/laboratory/delete', {'model': 'gwm8223'})[0], 200) diff --git a/openpilot/starpilot/galaxy/tests/test_recording_library.py b/openpilot/starpilot/galaxy/tests/test_recording_library.py index dbe1625c06..e084ad37ee 100644 --- a/openpilot/starpilot/galaxy/tests/test_recording_library.py +++ b/openpilot/starpilot/galaxy/tests/test_recording_library.py @@ -10,6 +10,7 @@ import tempfile import unittest from unittest.mock import patch +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.drive_history import DriveHistory from openpilot.starpilot.galaxy.recording_library import RecordingLibrary, attribute from openpilot.starpilot.galaxy.recording_media import RecordingMediaChanged, VerifiedRoute @@ -184,7 +185,7 @@ class RecordingLibraryTest(unittest.TestCase): try: with tarfile.open(fileobj=io.BytesIO(os.pread(lease.video_fd, lease.size, 0))) as archive: self.assertEqual(archive.getnames(), [ROUTE + '--0/rlog.zst']) - self.assertEqual(archive.extractfile(archive.getnames()[0]).read(), b'log') + self.assertEqual(require_value(archive.extractfile(archive.getnames()[0])).read(), b'log') self.assertTrue(lease.source.current()) (self.segment / 'rlog.lock').touch() self.assertFalse(lease.source.current()) @@ -239,7 +240,7 @@ class RecordingLibraryTest(unittest.TestCase): status, body, _ = request(f'/api/recordings/logs/{ROUTE}', cookie=cookie) self.assertEqual(status, 200) with tarfile.open(fileobj=io.BytesIO(body)) as archive: - self.assertEqual(archive.extractfile(ROUTE + '--0/rlog.zst').read(), b'log') + self.assertEqual(require_value(archive.extractfile(ROUTE + '--0/rlog.zst')).read(), b'log') parked = False self.assertEqual(request('/api/recordings/action', {'action': 'delete', 'routeId': ROUTE, 'confirmed': True}, cookie)[0], 409) self.assertTrue(self.segment.exists()) diff --git a/openpilot/starpilot/galaxy/tests/test_reverse_proxy.py b/openpilot/starpilot/galaxy/tests/test_reverse_proxy.py index 77a74a74a1..c206930a09 100644 --- a/openpilot/starpilot/galaxy/tests/test_reverse_proxy.py +++ b/openpilot/starpilot/galaxy/tests/test_reverse_proxy.py @@ -3,6 +3,7 @@ import unittest from tempfile import TemporaryDirectory +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.http_server import ReverseProxy, allowed_authority from openpilot.starpilot.galaxy.reverse_proxy import ReverseProxySettings @@ -26,13 +27,13 @@ class ReverseProxyTest(unittest.TestCase): with self.assertRaises(PermissionError): owner.save(payload, lambda: False) saved = owner.save(payload, lambda: True) - self.assertEqual(ReverseProxySettings(root).current.origin, payload['origin']) + self.assertEqual(require_value(ReverseProxySettings(root).current).origin, payload['origin']) with self.assertRaises(ValueError): owner.save(payload, lambda: True) calls = iter((True, False)) with self.assertRaises(PermissionError): owner.save({**saved, 'enabled': False, 'confirmed': True}, lambda: next(calls)) - self.assertIsNotNone(owner.current) + assert owner.current is not None owner.save({**saved, 'enabled': False, 'confirmed': True}, lambda: True) self.assertIsNone(ReverseProxySettings(root).current) diff --git a/openpilot/starpilot/galaxy/tests/test_sentry_notifications_http.py b/openpilot/starpilot/galaxy/tests/test_sentry_notifications_http.py index 292d795f83..516925067d 100644 --- a/openpilot/starpilot/galaxy/tests/test_sentry_notifications_http.py +++ b/openpilot/starpilot/galaxy/tests/test_sentry_notifications_http.py @@ -156,6 +156,7 @@ class NotificationHTTPTests(unittest.TestCase): worker.join(2) server.server_close() self.assertIsNone(owner.lock_fd) + assert owner.thread is not None self.assertFalse(owner.thread.is_alive()) def test_remote_listener_shares_sender_and_bind_failure_closes_owner(self): diff --git a/openpilot/starpilot/galaxy/tests/test_settings_live_context.py b/openpilot/starpilot/galaxy/tests/test_settings_live_context.py index 0edbdd88e3..be6f8c5547 100644 --- a/openpilot/starpilot/galaxy/tests/test_settings_live_context.py +++ b/openpilot/starpilot/galaxy/tests/test_settings_live_context.py @@ -221,7 +221,9 @@ class LiveContextTest(unittest.TestCase): self.assertTrue(snapshot.parked) self.assertEqual(snapshot.cp.carFingerprint, "TOYOTA COROLLA TSS2") path = Path(self.params.get_param_path("CarParamsPersistent")) + assert snapshot.cp_raw is not None self.assertTrue(snapshot.cp_raw.endswith(path.read_bytes())) + assert snapshot.cp_raw is not None self.assertTrue(snapshot.cp_raw.startswith(b"settings-configuration:")) path.write_bytes(b"not a versioned cache") self.assertIsNone(self.source.sample().cp) diff --git a/openpilot/starpilot/galaxy/tests/test_sound_downloads.py b/openpilot/starpilot/galaxy/tests/test_sound_downloads.py index c59372714b..38030bebf9 100644 --- a/openpilot/starpilot/galaxy/tests/test_sound_downloads.py +++ b/openpilot/starpilot/galaxy/tests/test_sound_downloads.py @@ -13,6 +13,7 @@ from unittest.mock import patch import wave import zipfile +from openpilot.common.test import require_value from openpilot.starpilot.audio.downloads import SoundDownloads from openpilot.common.params import Params from openpilot.starpilot.galaxy.access import GalaxyAccessOwner @@ -62,7 +63,7 @@ class SoundDownloadsHttpTest(unittest.TestCase): body=None if payload is None else json.dumps(payload), headers=headers) response = connection.getresponse() if response.getheader('Set-Cookie'): - cookie[0] = response.getheader('Set-Cookie').split(';', 1)[0] + cookie[0] = require_value(response.getheader('Set-Cookie')).split(';', 1)[0] return response.status, json.loads(response.read()) finally: connection.close() diff --git a/openpilot/starpilot/galaxy/tests/test_spotify_setup.py b/openpilot/starpilot/galaxy/tests/test_spotify_setup.py index aeda176465..6c5746ccf5 100644 --- a/openpilot/starpilot/galaxy/tests/test_spotify_setup.py +++ b/openpilot/starpilot/galaxy/tests/test_spotify_setup.py @@ -5,6 +5,7 @@ import threading import pytest +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.access import GalaxyAccessOwner from openpilot.starpilot.galaxy.http_server import install_origin_allowed from openpilot.starpilot.galaxy.server import make_server @@ -136,7 +137,7 @@ def api(tmp_path, owner): headers={'Content-Type': 'application/json', 'Origin': f'http://127.0.0.1:{server.server_port}'}) response = conn.getresponse() response.read() - cookie = response.getheader('Set-Cookie').split(';', 1)[0] + cookie = require_value(response.getheader('Set-Cookie')).split(';', 1)[0] conn.close() yield request, cookie, setup, layout server.shutdown() diff --git a/openpilot/starpilot/galaxy/tests/test_starport_send.py b/openpilot/starpilot/galaxy/tests/test_starport_send.py index 77bade5aa1..7216a5e1ad 100644 --- a/openpilot/starpilot/galaxy/tests/test_starport_send.py +++ b/openpilot/starpilot/galaxy/tests/test_starport_send.py @@ -301,6 +301,7 @@ class DiscordFollowUpTest(unittest.TestCase): self.assertEqual(job.status()["fork"], True) self.assertEqual(job.status()["available"], True) job.start("hi") + assert job._thread is not None job._thread.join(2) self.assertEqual(job.status()["state"], "sent") sender.assert_called_once() diff --git a/openpilot/starpilot/galaxy/tests/test_vasm_settings.py b/openpilot/starpilot/galaxy/tests/test_vasm_settings.py index fb7a335e4a..fcb3521640 100644 --- a/openpilot/starpilot/galaxy/tests/test_vasm_settings.py +++ b/openpilot/starpilot/galaxy/tests/test_vasm_settings.py @@ -10,6 +10,7 @@ import threading import unittest from unittest import mock +from openpilot.common.test import require_value from openpilot.common.params import Params from openpilot.starpilot.galaxy.access import GalaxyAccessOwner from openpilot.starpilot.galaxy.server import make_server @@ -62,6 +63,7 @@ class VasmSavedSettingsTest(unittest.TestCase): saved = read_preferences(self.params) self.assertTrue(saved.valid) self.assertFalse(saved.preferences.enabled) + assert saved.preferences.annotation is not None self.assertEqual(saved.preferences.annotation.configured_sides, ("right",)) page = self.gateway.page("vasm", "session", b"generation") self.assertEqual(page["editor"]["cameraRight"], DRAFT["poly_right"]) @@ -202,7 +204,7 @@ class VasmHttpTest(unittest.TestCase): payload={**payload, "view": page["view"]})[1] self.assertEqual(self.request("/api/settings/confirm", cookie=cookie, payload={"intent": preview["intent"], "confirmed": True})[0], 200) - self.assertEqual(read_preferences(self.params).preferences.annotation.configured_sides, ("right",)) + self.assertEqual(require_value(read_preferences(self.params).preferences.annotation).configured_sides, ("right",)) page = self.request("/api/settings/pages/vasm", cookie=cookie)[1] preview = self.request("/api/settings/preview", cookie=cookie, payload={"view": page["view"], "row": 0, "direction": 1})[1] diff --git a/openpilot/starpilot/galaxy_bluetooth/phone_ui.py b/openpilot/starpilot/galaxy_bluetooth/phone_ui.py index 675fd11085..9489925e39 100644 --- a/openpilot/starpilot/galaxy_bluetooth/phone_ui.py +++ b/openpilot/starpilot/galaxy_bluetooth/phone_ui.py @@ -150,8 +150,10 @@ class PhoneWindow: status, data = 0, {} if status == 200: self.adapter = str(data.get('adapterName') or self.adapter)[:80] - pairing = data.get('pairing') if isinstance(data.get('pairing'), dict) else {} - prompt = pairing.get('prompt') if isinstance(pairing.get('prompt'), dict) else {} + pairing = data.get('pairing') + pairing = pairing if isinstance(pairing, dict) else {} + prompt = pairing.get('prompt') + prompt = prompt if isinstance(prompt, dict) else {} self.code = str(prompt.get('value') or '') if prompt.get('kind') == 'confirmation' and prompt.get('displayOnly') else '' if pairing.get('incoming') and pairing.get('state') == 'paired': self.music = str(pairing.get('name') or 'Phone')[:40] diff --git a/openpilot/starpilot/galaxy_bluetooth/tests/test_bridge.py b/openpilot/starpilot/galaxy_bluetooth/tests/test_bridge.py index ff05c323f5..5631125ae7 100644 --- a/openpilot/starpilot/galaxy_bluetooth/tests/test_bridge.py +++ b/openpilot/starpilot/galaxy_bluetooth/tests/test_bridge.py @@ -163,7 +163,7 @@ class GatewayTests(unittest.IsolatedAsyncioTestCase): body = json.dumps([{ "repeated_setting": n, "label": "Galaxy ✨" } for n in range(1000)]).encode() def response(request): return {"id": request["id"], "status": 200, "headers": {}, "body": base64.b64encode(body).decode()} - self.proxy.handle = response # ty: ignore[invalid-assignment] + self.proxy.handle = response await self.submit() self.assertTrue(all(len(p) <= 180 for p in self.state.response)) legacy_count = len(self.state.response) @@ -181,7 +181,7 @@ class GatewayTests(unittest.IsolatedAsyncioTestCase): body = json.dumps([{ "repeated_setting": n } for n in range(1000)]).encode() def response(request): return {"id": request["id"], "status": 200, "headers": {}, "body": base64.b64encode(body).decode()} - self.proxy.handle = response # ty: ignore[invalid-assignment] + self.proxy.handle = response await self.submit(response_codec=2, response_flow="read-stream") count = len(self.state.response) self.assertGreater(count, 1) @@ -223,7 +223,7 @@ class GatewayTests(unittest.IsolatedAsyncioTestCase): def response(request): self.proxy.calls += 1 return {"id": request["id"], "status": 200, "headers": {}, "body": base64.b64encode(body).decode()} - self.proxy.handle = response # ty: ignore[invalid-assignment] + self.proxy.handle = response return body async def test_notifications_are_bounded_and_verified_before_final_ack(self): diff --git a/openpilot/starpilot/lateral/gm_geometry_runtime.py b/openpilot/starpilot/lateral/gm_geometry_runtime.py index 2b66224a1f..34868860ff 100644 --- a/openpilot/starpilot/lateral/gm_geometry_runtime.py +++ b/openpilot/starpilot/lateral/gm_geometry_runtime.py @@ -82,8 +82,9 @@ class GeometryPublicationOwner: if self.delay_read_ns is None or not 0 <= now - self.delay_read_ns < 1_000_000_000: self.delay_selected = read_delay(self.params, self.CP) self.delay_read_ns = now - if self.delay_selected.value is not None: + delay = self.delay_selected + if delay is not None and delay.value is not None: message = original.as_reader().as_builder() - message.lateralDelay.lateralDelay = self.delay_selected.value + message.lateralDelay.lateralDelay = delay.value return message return original diff --git a/openpilot/starpilot/lateral/ioniq6_policy.py b/openpilot/starpilot/lateral/ioniq6_policy.py index 56ed3d56ad..b953ccded7 100644 --- a/openpilot/starpilot/lateral/ioniq6_policy.py +++ b/openpilot/starpilot/lateral/ioniq6_policy.py @@ -811,6 +811,7 @@ class Ioniq6TorquePolicy: def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay): parent = self.parent + surface, surface_math = self.surface, self.surface_math pid_log = log.ControlsState.LateralTorqueState.new_message() pid_log.version = 2 measured_curvature = -VM.calc_curvature(math.radians(CS.steeringAngleDeg - params.angleOffsetDeg), CS.vEgo, params.roll) @@ -834,8 +835,8 @@ class Ioniq6TorquePolicy: roll_offset_fade = float(np.interp(CS.vEgo, FF_ROLL_OFFSET_FADE_BP, FF_ROLL_OFFSET_FADE_V)) roll_compensation = params.roll * ACCELERATION_DUE_TO_GRAVITY * roll_offset_fade effective_deadzone_deg = parent.steering_angle_deadzone_deg - if self.surface is not None: - effective_deadzone_deg += self.surface_math.center_deadband(self.surface, CS.vEgo) + if surface is not None and surface_math is not None: + effective_deadzone_deg += surface_math.center_deadband(surface, CS.vEgo) curvature_deadzone = abs(VM.calc_curvature(math.radians(effective_deadzone_deg), CS.vEgo, 0.0)) lateral_accel_deadzone = curvature_deadzone * CS.vEgo ** 2 lateral_accel_deadzone = auto_stages.apply_selected_deadzone(parent, CS, VM, float(lateral_accel_deadzone), desired_curvature, @@ -870,27 +871,27 @@ class Ioniq6TorquePolicy: error_with_lsf *= get_ioniq_6_2025_low_speed_center_error_scale(setpoint, desired_lateral_jerk, CS.vEgo) pid_log.error = float(error_with_lsf) ff = gravity_adjusted_future_lateral_accel - parent.torque_params.latAccelOffset * roll_offset_fade - if self.surface is None: + if (surface is None or surface_math is None): center_taper = get_ioniq_6_center_taper_scale(setpoint, CS.vEgo) directional_target = get_ioniq_6_directional_taper_scale(setpoint, desired_lateral_jerk, CS.vEgo) else: - center_taper = self.surface_math.center_taper(self.surface, CS.vEgo, setpoint) - directional_target = self.surface_math.directional_taper_target(self.surface, CS.vEgo, setpoint, desired_lateral_jerk) + center_taper = surface_math.center_taper(surface, CS.vEgo, setpoint) + directional_target = surface_math.directional_taper_target(surface, CS.vEgo, setpoint, desired_lateral_jerk) directional_taper = self.directional_taper_filter.update(directional_target) - if self.surface is None: + if (surface is None or surface_math is None): ff *= get_ioniq_6_ff_scale(setpoint, desired_lateral_jerk, CS.vEgo, directional_taper_scale=directional_taper) * center_taper else: - ff *= self.surface_math.feedforward_scale(self.surface, CS.vEgo, setpoint, desired_lateral_jerk, directional_taper) * center_taper + ff *= surface_math.feedforward_scale(surface, CS.vEgo, setpoint, desired_lateral_jerk, directional_taper) * center_taper if not self.is_2025: ff *= get_ioniq_6_2023_unwind_ff_scale(setpoint, measurement, desired_lateral_jerk, CS.vEgo) - if self.surface is None: + if (surface is None or surface_math is None): friction_threshold = get_ioniq_6_friction_threshold(CS.vEgo, setpoint, desired_lateral_jerk) / max(center_taper, 1e-3) else: - friction_threshold = self.surface_math.friction_threshold(self.surface, CS.vEgo, setpoint, desired_lateral_jerk) / max(center_taper, 1e-3) + friction_threshold = surface_math.friction_threshold(surface, CS.vEgo, setpoint, desired_lateral_jerk) / max(center_taper, 1e-3) if not self.is_2025 and not CS.steeringPressed and not self.prev_steering_pressed: friction_threshold *= 1.0 + IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE * float(np.interp(CS.vEgo, [3.0, 12.0], [0.0, 1.0])) friction_threshold *= 1.0 + IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE * float(np.interp(CS.vEgo, [20.0, 27.0], [0.0, 1.0])) - if self.surface is None and not self.is_2025 and not CS.steeringPressed and not self.prev_steering_pressed: + if (surface is None or surface_math is None) and not self.is_2025 and not CS.steeringPressed and not self.prev_steering_pressed: friction_threshold += get_ioniq_6_2023_center_friction_increment( CS.vEgo, setpoint, measurement, desired_lateral_jerk, future_desired_lateral_accel) / max(center_taper, 1e-3) if self.is_2025 and not CS.steeringPressed: @@ -924,10 +925,10 @@ class Ioniq6TorquePolicy: desired_angle = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)) actual_angle = CS.steeringAngleDeg - params.angleOffsetDeg if math.isfinite(desired_angle) and math.isfinite(actual_angle) and math.isfinite(output_torque): - if self.surface is None: + if (surface is None or surface_math is None): output_torque = get_ioniq_6_low_speed_angle_assist_torque(desired_angle, actual_angle, output_torque, CS.vEgo) else: - output_torque = self.surface_math.low_speed_output(self.surface, self.surface_math.SurfaceInput( + output_torque = surface_math.low_speed_output(surface, surface_math.SurfaceInput( CS.vEgo, setpoint, desired_lateral_jerk, desired_angle, actual_angle, output_torque, False, directional_taper)) output_torque *= get_ioniq_6_highway_output_taper_scale(setpoint, CS.vEgo) output_torque *= get_ioniq_6_highway_transition_output_taper_scale( diff --git a/openpilot/starpilot/lateral/lane_centering.py b/openpilot/starpilot/lateral/lane_centering.py index 3f25db06c3..9e3673f012 100644 --- a/openpilot/starpilot/lateral/lane_centering.py +++ b/openpilot/starpilot/lateral/lane_centering.py @@ -310,7 +310,7 @@ class LaneCenteringController: source = self._clearance_observation measured = _finite_number(source.measured_curvature) if source is not None else None delay = _finite_number(source.lateral_delay_s) if source is not None else None - guarded = (0. if measured is None or delay is None else + guarded = (0. if source is None or measured is None or delay is None else limit_correction(source.model, base, self._correction, measured, source.speed_mps, delay, self._body)) if guarded != self._correction: self._position_trim *= abs(guarded / self._correction) diff --git a/openpilot/starpilot/lateral/tests/test_automatic_learning_source.py b/openpilot/starpilot/lateral/tests/test_automatic_learning_source.py index 4296605d2e..3bde53dd23 100644 --- a/openpilot/starpilot/lateral/tests/test_automatic_learning_source.py +++ b/openpilot/starpilot/lateral/tests/test_automatic_learning_source.py @@ -9,6 +9,7 @@ import unittest from opendbc.car.car_helpers import interfaces from opendbc.car.structs import car from openpilot.starpilot.lateral.learning_preferences import KEY as LEARNING_KEY, LEGACY_KEY as LEARNING_LEGACY_KEY, replace_preference +from openpilot.system.manager.process import PythonProcess from openpilot.system.manager.process_config import managed_processes from opendbc.car.gm.values import CAR as GM from opendbc.car.hyundai.values import CAR as HKG @@ -97,7 +98,7 @@ class TestAutomaticLearningSource(unittest.TestCase): for frame in range(20): now = NOW + frame * 10_000_000 tune = source.sample(sm, now_ns=now, lat_active=True) - self.assertIsNotNone(tune) + assert tune is not None host.apply(controller, host.sample(sm, now_ns=now, lat_active=True, automatic=tune)) self.assertGreater(controller.torque_params.latAccelFactor, cp.lateralTuning.torque.latAccelFactor) self.assertLess(controller.torque_from_lateral_accel(1., controller.torque_params), previous) @@ -248,7 +249,9 @@ class TestDisabledLearnerProcess(unittest.TestCase): self.addCleanup(self.prefix.__exit__, None, None, None) self.params = Params() self.cp = car.CarParams.new_message(brand='hyundai', carFingerprint='HYUNDAI_IONIQ_6') - self.process = managed_processes['steerlearnerd'] + process = managed_processes['steerlearnerd'] + assert isinstance(process, PythonProcess) + self.process = process def test_default_still_runs_onroad_and_parked_analysis(self): assert self.process.should_run(True, self.params, self.cp) diff --git a/openpilot/starpilot/lateral/tests/test_bolt_lane_runtime.py b/openpilot/starpilot/lateral/tests/test_bolt_lane_runtime.py index 3104f8ce66..f36d7b2558 100644 --- a/openpilot/starpilot/lateral/tests/test_bolt_lane_runtime.py +++ b/openpilot/starpilot/lateral/tests/test_bolt_lane_runtime.py @@ -28,7 +28,7 @@ class TestBoltLaneRuntime(unittest.TestCase): settings = Params() settings.put('CarParams', cp.to_bytes(), block=True) selected, reference = Controls(), Controls() - self.assertIsNotNone(selected.lane_centering_host) + assert selected.lane_centering_host is not None reference.lane_centering_host = None for tick in range(20): now = 1_000_000_000 + tick * 10_000_000 @@ -64,6 +64,7 @@ class TestBoltLaneRuntime(unittest.TestCase): command, _ = controls.state_control() if gate.get('signal'): self.assertLess(abs(controls.lane_centering_applied), warm_correction) + assert controls.last_lane_centering_result is not None self.assertEqual(controls.last_lane_centering_result.reason, 'signal_release') else: self.assertEqual(controls.lane_centering_applied, 0.) @@ -77,4 +78,4 @@ class TestBoltLaneRuntime(unittest.TestCase): owner = FeatureSettingsOwner(Params(), lambda _: True, vehicle_fingerprint=lambda: None, vehicle_params=lambda: None) state = owner.snapshot('lane', parked=True, system_long=False, lateral_context=False, metric=False) - self.assertIsNotNone(state) + assert state is not None diff --git a/openpilot/starpilot/lateral/tests/test_bolt_manual_friction.py b/openpilot/starpilot/lateral/tests/test_bolt_manual_friction.py index a8b54dccd8..1e2f5a309e 100644 --- a/openpilot/starpilot/lateral/tests/test_bolt_manual_friction.py +++ b/openpilot/starpilot/lateral/tests/test_bolt_manual_friction.py @@ -73,6 +73,7 @@ class TestBoltManualFriction(unittest.TestCase): command, _ = selected.state_control() self.assertFalse(command.latActive) self.assertEqual(command.actuators.torque, 0.) + assert selected.torque_host is not None self.assertEqual(selected.torque_host.selected, selected.torque_host.vehicle) def test_estimator_default_cache_path_and_optin_fresh_session_without_gm_learning(self): @@ -164,10 +165,13 @@ class TestBoltManualFriction(unittest.TestCase): for tick in range(300): stamp = now + tick * 10_000_000 learned.logMonoTime['lateralTorqueParameters'] = stamp + assert host is not None host.apply(controls.LaC, host.sample(learned, now_ns=stamp, lat_active=True)) self.assertAlmostEqual(controls.LaC.torque_params.friction, friction, places=6) self.assertAlmostEqual(controls.LaC.torque_params.latAccelOffset, basis[1], places=6) + assert host is not None self.assertFalse(host.allow_learning) + assert host is not None self.assertEqual(host.selected.source.value, 'user') if mode == ControllerMode.STARPILOT: self.assertEqual(controls.LaC.torque_from_lateral_accel(1., controls.LaC.torque_params), diff --git a/openpilot/starpilot/lateral/tests/test_bolt_manual_gain.py b/openpilot/starpilot/lateral/tests/test_bolt_manual_gain.py index f36276d18a..9b282cd5d7 100644 --- a/openpilot/starpilot/lateral/tests/test_bolt_manual_gain.py +++ b/openpilot/starpilot/lateral/tests/test_bolt_manual_gain.py @@ -64,14 +64,17 @@ class TestBoltManualGain(unittest.TestCase): saved.put(DOCUMENT_KEY, json.loads(serialize_document(document)), block=True) owner = create_gain_owner(saved, cp, controls.LaC) controls.LaC.pid.i = .123 + assert owner is not None owner.refresh(now_ns=1_000_000_000) for value in (.6, .9): document = replace_gain(document, str(cp.carFingerprint), basis, "custom", value) saved.put(DOCUMENT_KEY, json.loads(serialize_document(document)), block=True) + assert owner is not None owner.refresh(now_ns=int(value * 10_000_000_000)) self.assertEqual(controls.LaC.pid._k_p, [[0.], [value]]) self.assertEqual(controls.LaC.pid.i, .123) saved.put_bool("AdvancedLateralTune", False, block=True) + assert owner is not None owner.refresh(now_ns=10_000_000_000) self.assertEqual(tuple(tuple(row) for row in controls.LaC.pid._k_p), basis.source_table) self.assertEqual(controls.LaC.pid.i, .123) diff --git a/openpilot/starpilot/lateral/tests/test_controller_selection.py b/openpilot/starpilot/lateral/tests/test_controller_selection.py index c497b21cd2..97e563efb5 100644 --- a/openpilot/starpilot/lateral/tests/test_controller_selection.py +++ b/openpilot/starpilot/lateral/tests/test_controller_selection.py @@ -190,7 +190,7 @@ class TestControllerSelection(unittest.TestCase): first = Controls() self.assertEqual(first.lateral_controller_selection.mode, ControllerMode.STANDARD) self.assertIsNone(selected_policy(first.LaC)) - self.assertIsNotNone(first.torque_host) + assert first.torque_host is not None source = replace(first.torque_host.vehicle, source=TorqueSource.USER, lat_accel_factor=3.3, friction=0.12) self.assertTrue(first.torque_host.apply(first.LaC, source)) self.assertEqual(first.LaC.torque_params.latAccelFactor, struct.unpack('f', struct.pack('f', 3.3))[0]) @@ -199,7 +199,7 @@ class TestControllerSelection(unittest.TestCase): second = Controls() self.assertEqual(second.lateral_controller_selection.mode, ControllerMode.STARPILOT) self.assertIsNotNone(selected_policy(second.LaC)) - self.assertIsNotNone(second.torque_host) + assert second.torque_host is not None self.assertTrue(second.torque_host.apply(second.LaC, source)) self.assertEqual(second.LaC.torque_params.latAccelFactor, struct.unpack('f', struct.pack('f', 3.3 * 1.22))[0]) diff --git a/openpilot/starpilot/lateral/tests/test_global_lane_runtime.py b/openpilot/starpilot/lateral/tests/test_global_lane_runtime.py index d94e320689..14fb203deb 100644 --- a/openpilot/starpilot/lateral/tests/test_global_lane_runtime.py +++ b/openpilot/starpilot/lateral/tests/test_global_lane_runtime.py @@ -85,6 +85,7 @@ def test_actual_controller_paths_apply_generic_lane_curvature_then_withdraw_for_ feed(controls, now, tick) command, _ = controls.state_control() assert command.latActive + assert controls.last_lane_centering_result is not None assert controls.last_lane_centering_result.correction > 0. assert controls.lane_centering_applied > 0. for tick in range(60, 65): @@ -128,6 +129,7 @@ def test_actual_controller_paths_track_one_current_line_and_withdraw_for_fault(i feed(controls, 2_000_000_000 + tick * 10_000_000, tick) command, _ = controls.state_control() assert command.latActive + assert controls.last_lane_centering_result is not None assert controls.last_lane_centering_result.correction > 0. assert controls.lane_centering_applied > 0. feed(controls, 2_900_000_000, 90, fault=True) diff --git a/openpilot/starpilot/lateral/tests/test_gm_geometry_runtime.py b/openpilot/starpilot/lateral/tests/test_gm_geometry_runtime.py index 91a6aea90d..9d986f53be 100644 --- a/openpilot/starpilot/lateral/tests/test_gm_geometry_runtime.py +++ b/openpilot/starpilot/lateral/tests/test_gm_geometry_runtime.py @@ -82,7 +82,7 @@ class TestGmGeometryRuntime(unittest.TestCase): controls = Controls() self.assertEqual(controls.lateral_controller_selection.mode, mode) self.assertTrue(controls.torque_learning_allowed) - self.assertIsNotNone(controls.torque_host) + assert controls.torque_host is not None estimator = TorqueEstimator(cp.as_reader(), allow_learning=learning_allowed(saved, cp)) self.assertTrue(estimator.learning_allowed) self.assertFalse(estimator.use_params, 'brand eligibility semantics remain unchanged') @@ -250,8 +250,11 @@ class TestGmGeometryRuntime(unittest.TestCase): apply_value('torque:ratio:value', str(ratio)) apply_value('steering_delay', '.7') stored_profile = parse_document(Path(saved.get_param_path(DOCUMENT_KEY)).read_bytes())[identity] + assert stored_profile.geometry is not None self.assertEqual(stored_profile.geometry.ratio, FieldChoice('custom', ratio)) + assert stored_profile.geometry is not None self.assertEqual(stored_profile.geometry.full_delay, FieldChoice()) + assert stored_profile.geometry is not None self.assertTrue(stored_profile.geometry.automatic_delay) parameters = messaging.new_message('vehicleParameters', valid=True) parameters.vehicleParameters.steerRatio = cp.steerRatio @@ -271,8 +274,11 @@ class TestGmGeometryRuntime(unittest.TestCase): self.assertIs(publisher.parameters(parameters), parameters, 'source ratio withdraws custom projection') self.assertIs(publisher.delay(delay), delay, 'reset restores the actual learned publication') source = parse_document(Path(saved.get_param_path(DOCUMENT_KEY)).read_bytes())[identity] + assert source.geometry is not None self.assertEqual(source.geometry.ratio, FieldChoice('source', ratio)) + assert source.geometry is not None self.assertEqual(source.geometry.full_delay, FieldChoice()) + assert source.geometry is not None self.assertTrue(source.geometry.automatic_delay) apply_value('torque:ratio:value', str(ratio)) apply_value('steering_delay', '.7') diff --git a/openpilot/starpilot/lateral/tests/test_gm_manual_torque.py b/openpilot/starpilot/lateral/tests/test_gm_manual_torque.py index c7708cd0ef..61a3c3ad49 100644 --- a/openpilot/starpilot/lateral/tests/test_gm_manual_torque.py +++ b/openpilot/starpilot/lateral/tests/test_gm_manual_torque.py @@ -161,7 +161,7 @@ class TestGmManualTorque(unittest.TestCase): self.assertTrue(settings.valid) self.assertEqual(settings.user_friction,.8) owner=create_gain_owner(saved,cp,lateral) - self.assertIsNotNone(owner) + assert owner is not None self.assertEqual(lateral.pid._k_p,[[0.],[.7]]) self.assertEqual(cp.as_reader().as_builder().to_bytes(),native_cp) raw=serialize_document(profiles) @@ -189,7 +189,7 @@ class TestGmManualTorque(unittest.TestCase): saved.put_bool('AdvancedLateralTune', False, block=True) stored(saved, replace_gain({}, str(cp.carFingerprint), basis, 'custom', custom)) selected = Controls() - self.assertIsNotNone(selected.lateral_gain_owner) + assert selected.lateral_gain_owner is not None self.assertIsNone(selected.torque_host) self.assertEqual(selected.torque_learning_allowed, baseline.torque_learning_allowed) self.assertEqual(selected.lateral_controller_selection.mode, mode) @@ -232,8 +232,8 @@ class TestGmManualTorque(unittest.TestCase): saved.put_bool('AdvancedLateralTune', False, block=True) stored(saved, profiles) selected = Controls() - self.assertIsNotNone(selected.torque_host) - self.assertIsNotNone(selected.lateral_gain_owner) + assert selected.torque_host is not None + assert selected.lateral_gain_owner is not None values=[] for tick in range(120): now=1_000_000_000+tick*10_000_000 diff --git a/openpilot/starpilot/lateral/tests/test_ioniq6_torque_source.py b/openpilot/starpilot/lateral/tests/test_ioniq6_torque_source.py index 70b05ce2de..173a744e15 100644 --- a/openpilot/starpilot/lateral/tests/test_ioniq6_torque_source.py +++ b/openpilot/starpilot/lateral/tests/test_ioniq6_torque_source.py @@ -100,7 +100,7 @@ class Ioniq6TorqueSourceTests(unittest.TestCase): with self.subTest(long=cp.openpilotLongitudinalControl): params.put('CarParams', cp.as_reader().as_builder().to_bytes(), block=True) selected = Controls() - self.assertIsNotNone(selected.torque_host) + assert selected.torque_host is not None learner = LearnedFrame(1_000_000_000, factor=3.15, offset=0.03, friction=0.10) tune = selected.torque_host.sample(learner, now_ns=1_000_000_000, lat_active=True) self.assertEqual(selected.torque_host.selected.source, TorqueSource.USER) diff --git a/openpilot/starpilot/lateral/tests/test_lane_change_cruise.py b/openpilot/starpilot/lateral/tests/test_lane_change_cruise.py index 8fce27785b..935d005b21 100644 --- a/openpilot/starpilot/lateral/tests/test_lane_change_cruise.py +++ b/openpilot/starpilot/lateral/tests/test_lane_change_cruise.py @@ -6,6 +6,7 @@ from dataclasses import replace import unittest from opendbc.car import structs +from openpilot.common.test import require_value from openpilot.cereal import log from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper from openpilot.starpilot.lateral.auto_lane_change import auto_trigger_engaged @@ -111,7 +112,7 @@ class CruiseGateTests(unittest.TestCase): self.assertEqual(decode(json.dumps(current).encode()), self.policy) old = {k: v for k, v in current.items() if k != 'autoRequiresCruise'} old['version'] = 5 - self.assertFalse(decode(json.dumps(old).encode()).auto_requires_cruise) + self.assertFalse(require_value(decode(json.dumps(old).encode())).auto_requires_cruise) for bad in (1, 'true', None, [], {}): self.assertIsNone(decode(json.dumps({**current, 'autoRequiresCruise': bad}).encode())) with self.assertRaises(ValueError): diff --git a/openpilot/starpilot/lateral/tests/test_lane_runtime.py b/openpilot/starpilot/lateral/tests/test_lane_runtime.py index 919a34173c..24d5db6c61 100644 --- a/openpilot/starpilot/lateral/tests/test_lane_runtime.py +++ b/openpilot/starpilot/lateral/tests/test_lane_runtime.py @@ -161,7 +161,7 @@ class LaneRuntimeTests(unittest.TestCase): for tick in range(100): feed(controls, 1_000_000_000 + tick * 10_000_000, tick) controls.state_control() - self.assertIsNotNone(controls.last_lane_centering_result) + assert controls.last_lane_centering_result is not None assert controls.last_lane_centering_result is not None self.assertEqual(controls.last_lane_centering_result.correction, 0.) self.assertEqual(controls.lane_centering_applied, 0.) @@ -197,7 +197,7 @@ class LaneRuntimeTests(unittest.TestCase): command, _ = controls.state_control() refresh.assert_called_once_with(0) if queued == 'fresh': - self.assertIsNotNone(controls.last_lane_centering_result) + assert controls.last_lane_centering_result is not None self.assertGreater(controls.lane_centering_applied, 0.) else: self.assertEqual(controls.lane_centering_applied, 0.) @@ -285,7 +285,7 @@ class LaneRuntimeTests(unittest.TestCase): baseline, candidate = Controls(), Controls(predict_lane_clearance=True) baseline.lane_centering_host = None body = candidate.lane_centering_controller._body - self.assertIsNotNone(body) + assert body is not None self.assertEqual((body.width, body.length, body.height), (1.88, 4.855, 1.495)) self.assertEqual(candidate.CP.to_dict(), before) original_model = model @@ -323,6 +323,7 @@ class LaneRuntimeTests(unittest.TestCase): recovered += abs(candidate.lane_centering_applied) > 1e-6 self.assertGreater(added, 0) self.assertGreater(recovered, 0) + assert candidate.last_lane_centering_result is not None self.assertEqual(candidate.last_lane_centering_result.reason, 'driver_override') def test_unqualified_body_through_actual_controls_preserves_nominal_native_output(self): @@ -360,7 +361,9 @@ class LaneRuntimeTests(unittest.TestCase): self.assertNotEqual(candidate.desired_curvature, 0.) self.assertTrue(candidate.lane_centering_controller._body_required) self.assertIsNone(candidate.lane_centering_controller._body) + assert candidate.last_lane_centering_result is not None self.assertEqual(candidate.last_lane_centering_result.reason, 'unqualified_body') + assert candidate.last_lane_centering_result is not None self.assertEqual(candidate.last_lane_centering_result.correction, 0.) self.assertIsNone(candidate.lane_centering_controller._tracker.path) @@ -428,12 +431,14 @@ class LaneRuntimeTests(unittest.TestCase): feed(controls, 2_000_000_000 + tick * 10_000_000, tick) command, _ = controls.state_control() self.assertTrue(command.latActive) + assert controls.last_lane_centering_result is not None self.assertGreater(controls.last_lane_centering_result.correction, 0.) for tick in range(35, 45): feed(controls, 2_000_000_000 + tick * 10_000_000, tick, delay_fast=True) command, _ = controls.state_control() self.assertTrue(command.latActive) self.assertFalse(controls.sm.all_checks(['lateralDelay'])) + assert controls.last_lane_centering_result is not None self.assertEqual(controls.last_lane_centering_result.correction, 0.) self.assertEqual(controls.lane_centering_applied, 0.) @@ -612,14 +617,18 @@ class LaneRuntimeTests(unittest.TestCase): host = LaneCenteringHost(params) now = 10_000_000_000 first = host.sample(Frame(now), now_ns=now, lateral_active=True, longitudinal_active=False) + assert first is not None self.assertEqual(first.settings.strength, 1.5) (root / 'LaneCenteringStrength').write_bytes(b'3.0') now += host.REFRESH_NS updated = host.sample(Frame(now), now_ns=now, lateral_active=True, longitudinal_active=False) + assert updated is not None self.assertEqual(updated.settings.strength, 3.0) restarted = LaneCenteringHost(params).sample(Frame(now), now_ns=now, lateral_active=True, longitudinal_active=False) + assert restarted is not None self.assertEqual(restarted.settings.strength, 3.0) self.assertEqual((root / 'LaneCenteringStrength').read_bytes(), b'3.0') + assert updated is not None self.assertTrue(updated.time_discontinuity) for invalid in (b'nan', b'0.49', b'3.001', b'true'): (root / 'LaneCenteringStrength').write_bytes(invalid) @@ -660,21 +669,23 @@ class LaneRuntimeTests(unittest.TestCase): params.put('LaneCenteringE2EAuthority', 0.0, block=True) params.put('CarParams', tagged.to_bytes(), block=True) disabled = Controls(predict_lane_clearance=True) - self.assertIsNotNone(disabled.lane_centering_host) + assert disabled.lane_centering_host is not None frame = Frame(1_000_000_000) self.assertIsNone(disabled.lane_centering_host.sample(frame, now_ns=1_000_000_000, lateral_active=True, longitudinal_active=False)) params.put_bool('LaneCentering', True, block=True) controls = disabled + assert controls.lane_centering_controller._body is not None self.assertEqual(controls.lane_centering_controller._body.width, 1.88) + assert controls.lane_centering_controller._body is not None self.assertEqual(controls.lane_centering_controller._body.length, 4.855) - self.assertIsNotNone(controls.lane_centering_host) + assert controls.lane_centering_host is not None for tick in range(35): now = 2_000_000_000 + tick * 10_000_000 feed(controls, now, tick) command, _ = controls.state_control() self.assertTrue(command.latActive) - self.assertIsNotNone(controls.last_lane_centering_result) + assert controls.last_lane_centering_result is not None self.assertGreater(controls.last_lane_centering_result.correction, 0.0) feed(controls, now + 10_000_000, 35, model_age=200_000_000) controls.state_control() @@ -701,7 +712,7 @@ class LaneRuntimeTests(unittest.TestCase): initial = messaging.new_message('lateralDelay', valid=True, logMonoTime=750_000_000) initial.lateralDelay.lateralDelay = .1 controls.sm.update_msgs(.75, [initial.as_reader()]) - self.assertIsNotNone(controls.lane_centering_host) + assert controls.lane_centering_host is not None # Inject already-qualified independent-axis results at the consumer seam; # AOL's native/session checks are covered by its own wire tests. controls.aol_replay = True @@ -719,7 +730,7 @@ class LaneRuntimeTests(unittest.TestCase): command, _ = controls.state_control() tick += 1 self.assertEqual((command.latActive, command.longActive), (lat, lon)) - self.assertIsNotNone(controls.last_lane_centering_result) + assert controls.last_lane_centering_result is not None self.assertEqual(controls.last_lane_centering_result.correction > 0.0, lat) with mock.patch('openpilot.selfdrive.controls.controlsd.current_axis', return_value=SimpleNamespace( sessionId='test-session', nativeAcknowledged=True, lateralActive=True, desiredLateral=True, @@ -836,7 +847,7 @@ class LaneRuntimeTests(unittest.TestCase): tick += 1 feed(controls, 1_000_000_000 + tick * 10_000_000, tick) command, lateral_log = controls.state_control() - self.assertIsNotNone(controls.last_lane_centering_result) + assert controls.last_lane_centering_result is not None self.assertEqual(controls.lane_centering_inactive_reason, 'inactive') controls.pm.send.reset_mock() controls.publish(command, lateral_log) @@ -863,6 +874,7 @@ class LaneRuntimeTests(unittest.TestCase): for controls in (reference, candidate): feed(controls, now, tick) controls.state_control() + assert candidate.last_lane_centering_result is not None self.assertGreater(candidate.last_lane_centering_result.correction, 0.) self.assertEqual(candidate.desired_curvature, reference.desired_curvature) # Both native controllers have the same complete centering history. @@ -878,7 +890,9 @@ class LaneRuntimeTests(unittest.TestCase): command, _ = candidate.state_control() self.assertEqual(command.to_dict(), nominal.to_dict()) self.assertEqual(candidate.desired_curvature, reference.desired_curvature) + assert candidate.last_lane_centering_result is not None self.assertEqual(candidate.last_lane_centering_result.reason, 'lane_change') + assert candidate.last_lane_centering_result is not None self.assertEqual(candidate.last_lane_centering_result.correction, 0.) self.assertEqual(candidate.lane_centering_applied, 0.) self.assertEqual(candidate.lane_centering_controller._correction, 0.) @@ -903,7 +917,7 @@ class LaneRuntimeTests(unittest.TestCase): command, _ = candidate.state_control() self.assertEqual(command.to_dict(), nominal.to_dict()) if tick >= 30: - self.assertIsNotNone(candidate.last_lane_centering_result) + assert candidate.last_lane_centering_result is not None self.assertGreater(candidate.lane_centering_applied, 0.) for age in (25_000_001, -1): tick += 1 @@ -942,6 +956,7 @@ class LaneRuntimeTests(unittest.TestCase): for tick in range(100): feed(candidate, 1_000_000_000 + tick * 10_000_000, tick) candidate.state_control() + assert candidate.last_lane_centering_result is not None self.assertGreater(sign * candidate.last_lane_centering_result.correction, 0.) self.assertGreater(sign * candidate.lane_centering_applied, 0.) self.assertIsNone(candidate.lane_centering_controller._tracker.width) @@ -950,6 +965,7 @@ class LaneRuntimeTests(unittest.TestCase): m.meta.laneChangeState = 'laneChangeStarting' feed(candidate, 2_000_000_000, 100) candidate.state_control() + assert candidate.last_lane_centering_result is not None self.assertEqual(candidate.last_lane_centering_result.reason, 'lane_change') self.assertEqual(candidate.lane_centering_applied, 0.) self.assertEqual(candidate.lane_centering_controller._correction, 0.) @@ -981,11 +997,12 @@ class LaneRuntimeTests(unittest.TestCase): self.assertGreater(ordinary.lane_centering_applied, 0.) self.assertIsNone(ordinary.lane_centering_controller._body) predicted = Controls(predict_lane_clearance=True) - self.assertIsNotNone(predicted.lane_centering_controller._body) + assert predicted.lane_centering_controller._body is not None with mock.patch(f'{__name__}.model', return_value=m): for tick in range(80): feed(predicted, 1_000_000_000 + tick * 10_000_000, tick) predicted.state_control() + assert predicted.last_lane_centering_result is not None self.assertEqual(predicted.last_lane_centering_result.reason, 'clearance_limited') self.assertEqual(predicted.lane_centering_applied, 0.) self.assertEqual(predicted.CP.to_dict(), ordinary.CP.to_dict()) @@ -1046,7 +1063,7 @@ class LaneRuntimeTests(unittest.TestCase): (True, False, ControlMode.LATERAL_ONLY), (True, True, ControlMode.COMBINED))): now = 1_000_000_000 + tick * 10_000_000 request = host.sample(Frame(now), now_ns=now, lateral_active=lat, longitudinal_active=lon) - self.assertIsNotNone(request) + assert request is not None self.assertEqual(request.mode, mode) def test_stale_future_invalid_input_and_clock_gap(self): @@ -1105,7 +1122,7 @@ class LaneRuntimeTests(unittest.TestCase): baseline = Controls() with mock.patch.dict(os.environ, {'LANE_CENTERING_REPLAY_RUNTIME': '1'}): candidate = Controls() - self.assertIsNotNone(baseline.lane_centering_host) + assert baseline.lane_centering_host is not None baseline.lane_centering_host = None # Explicit no-feature reference; Toyota now uses the normal host. previous = 0.0 for tick in range(120): @@ -1126,13 +1143,16 @@ class LaneRuntimeTests(unittest.TestCase): if scenario == 'disabled_setting': self.assertEqual(command.to_dict(), reference.to_dict()) elif phase in ('off', 'long_only', 'fault', 'override'): + assert result is not None self.assertEqual(result.correction, 0.0) elif phase in ('stale', 'invalid_can', 'can_timeout'): self.assertIsNone(result) elif phase == 'signal': + assert result is not None self.assertLess(result.correction, previous) elif tick >= 30: # Wait for two delay packets; guarded correction may then settle. + assert result is not None self.assertGreater(result.correction, 0.) self.assertGreater(command.actuators.curvature, reference.actuators.curvature) previous = result.correction if result is not None else 0.0 @@ -1148,7 +1168,7 @@ class LaneRuntimeTests(unittest.TestCase): params.put('CarParams', cp.to_bytes(), block=True) controls = Controls() self.assertTrue(controls.aol_replay) - self.assertIsNotNone(controls.lane_centering_host) + assert controls.lane_centering_host is not None for tick in range(40): now = 1_000_000_000 + tick * 10_000_000 feed(controls, now, tick, active=False, enabled=False, aol_lat_only=True) diff --git a/openpilot/starpilot/lateral/tests/test_torque_learning.py b/openpilot/starpilot/lateral/tests/test_torque_learning.py index 721c0f75fa..2795eb5a48 100644 --- a/openpilot/starpilot/lateral/tests/test_torque_learning.py +++ b/openpilot/starpilot/lateral/tests/test_torque_learning.py @@ -277,18 +277,23 @@ class TestTorqueLearning(unittest.TestCase): controls = Controls() self.assertFalse(controls.torque_learning_allowed) params.remove('SteerFriction') + assert controls.torque_host is not None host, base = controls.torque_host, controls.torque_host.vehicle now = 1_000_000_000 learned = LearnedFrame(now, factor=base.lat_accel_factor * 1.2, offset=0.03, friction=base.friction * 1.1) + assert host is not None host.sample(learned, now_ns=now, lat_active=True) + assert host is not None self.assertEqual(host.selected.source, TorqueSource.VEHICLE) select(params, cp, ControllerMode.STARPILOT) params.put_bool(LEARNING_OFF_KEY, True, block=True) for tick in range(1, 102): stamp = now + tick * 10_000_000 learned.logMonoTime['lateralTorqueParameters'] = stamp + assert host is not None host.sample(learned, now_ns=stamp, lat_active=True) self.assertEqual(controls.LaC.controller_mode, ControllerMode.STANDARD) + assert host is not None self.assertEqual(host.selected.source, TorqueSource.VEHICLE) params.put('SteerLatAccel', base.lat_accel_factor * 1.1, block=True) assert host is not None @@ -300,12 +305,16 @@ class TestTorqueLearning(unittest.TestCase): next_drive = Controls() disabled = next_drive.torque_host + assert disabled is not None self.assertFalse(disabled.allow_learning) select(params, cp, ControllerMode.STANDARD) params.put_bool(LEARNING_OFF_KEY, False, block=True) + assert disabled is not None disabled.sample(learned, now_ns=stamp + 20_000_000, lat_active=True) self.assertEqual(next_drive.LaC.controller_mode, ControllerMode.STARPILOT) + assert disabled is not None self.assertEqual(disabled.selected.source, TorqueSource.USER) + assert disabled is not None self.assertEqual(disabled.selected.friction, base.friction) def test_unrelated_manual_host_preserves_master_off_behavior(self): diff --git a/openpilot/starpilot/lateral/tests/test_torque_runtime.py b/openpilot/starpilot/lateral/tests/test_torque_runtime.py index 95a35fc9a5..30da6771a7 100644 --- a/openpilot/starpilot/lateral/tests/test_torque_runtime.py +++ b/openpilot/starpilot/lateral/tests/test_torque_runtime.py @@ -213,7 +213,7 @@ class TorqueRuntimeTests(unittest.TestCase): with mock.patch.dict(os.environ, {'TORQUE_REPLAY_RUNTIME': '1'}): selected = Controls() self.assertIsNone(baseline.torque_host) - self.assertIsNotNone(selected.torque_host) + assert selected.torque_host is not None for tick in range(110): now = 1_000_000_000 + tick * 10_000_000 for controls in (baseline, selected): @@ -270,6 +270,7 @@ class TorqueRuntimeTests(unittest.TestCase): cp = publish_corolla_params(params) Path(params.get_param_path(CONTROLLER_KEY)).write_bytes(replace_mode(None, cp, ControllerMode.STANDARD)) controls = Controls() + assert controls.torque_host is not None base = controls.torque_host.vehicle target = base.lat_accel_factor * 1.1 for tick in range(120): @@ -285,7 +286,9 @@ class TorqueRuntimeTests(unittest.TestCase): state.frictionCoefficientFiltered = base.friction controls.sm.update_msgs(now / 1e9, [event.as_reader()]) controls.state_control() + assert controls.torque_host is not None self.assertEqual(controls.torque_host.selected.source, TorqueSource.LEARNED) + assert controls.torque_host is not None self.assertGreater(controls.torque_host.applied.lat_accel_factor, base.lat_accel_factor) params.put_bool('AdvancedLateralTune', True, block=True) params.put('SteerLatAccel', base.lat_accel_factor * 1.2, block=True) @@ -293,8 +296,11 @@ class TorqueRuntimeTests(unittest.TestCase): now = 1_000_000_000 + tick * 10_000_000 feed(controls, now, tick) controls.state_control() + assert controls.torque_host is not None self.assertEqual(controls.torque_host.selected.source, TorqueSource.USER) + assert controls.torque_host is not None self.assertEqual(controls.torque_host.selected.lat_accel_offset, base.lat_accel_offset) + assert controls.torque_host is not None self.assertGreater(controls.torque_host.applied.lat_accel_factor, target) params.put_bool('AdvancedLateralTune', False, block=True) params.put('SteerLatAccel', base.lat_accel_factor, block=True) @@ -302,7 +308,9 @@ class TorqueRuntimeTests(unittest.TestCase): now = 1_000_000_000 + tick * 10_000_000 feed(controls, now, tick) controls.state_control() + assert controls.torque_host is not None self.assertEqual(controls.torque_host.selected, base) + assert controls.torque_host is not None self.assertAlmostEqual(controls.torque_host.applied.lat_accel_factor, base.lat_accel_factor) diff --git a/openpilot/starpilot/lateral/tests/test_volt_lane_runtime.py b/openpilot/starpilot/lateral/tests/test_volt_lane_runtime.py index f4a315c4e7..de508899ea 100644 --- a/openpilot/starpilot/lateral/tests/test_volt_lane_runtime.py +++ b/openpilot/starpilot/lateral/tests/test_volt_lane_runtime.py @@ -88,6 +88,7 @@ class TestVoltLaneRuntime(unittest.TestCase): command, _ = controls.state_control() if gate.get('signal'): self.assertLess(abs(controls.lane_centering_applied), warm_correction) + assert controls.last_lane_centering_result is not None self.assertEqual(controls.last_lane_centering_result.reason, 'signal_release') else: self.assertEqual(controls.lane_centering_applied, 0.) diff --git a/openpilot/starpilot/longitudinal/extension.py b/openpilot/starpilot/longitudinal/extension.py index fda9df26ec..e918c07e98 100644 --- a/openpilot/starpilot/longitudinal/extension.py +++ b/openpilot/starpilot/longitudinal/extension.py @@ -99,7 +99,7 @@ class LongitudinalExtension: if self.stopping_policy is not None: state = self.stopping_policy.transition(state, previous_state, active, CS, a_target, should_stop, has_lead=context.has_lead) - if (self.toyota_pcm_resume and active and + if (self.toyota_pcm_resume and self.toyota_output is not None and active and CS.standstill and CS.cruiseState.standstill): # The PCM clears its hold after the controller sends a positive request. can_resume = (context.toyota_resume_fresh and CS.canValid and not CS.canTimeout and not CS.accFaulted and @@ -107,7 +107,7 @@ class LongitudinalExtension: not should_stop and not context.force_stop_braking and math.isfinite(a_target) and a_target >= 0.1 and self.toyota_output.moving_lead_for_resume(context.leads)) return LongCtrlState.pid if can_resume else LongCtrlState.stopping - if (self.toyota_stopped_lead and active and previous_state == LongCtrlState.stopping and + if (self.toyota_stopped_lead and self.toyota_output is not None and active and previous_state == LongCtrlState.stopping and state != LongCtrlState.off and not should_stop and not CS.brakePressed and self.toyota_output.hold_stopped_lead(CS.vEgo, context.leads)): state = LongCtrlState.stopping @@ -130,6 +130,8 @@ class LongitudinalExtension: return self.ioniq6_start.starting_output(a_target, accel_limits) if hasattr(self.vehicle_stop, "starting_output"): return self.vehicle_stop.starting_output(a_target, accel_limits, context) + if self.gm_start is None: + raise RuntimeError("Starting controller unavailable") self.vehicle_policy.reset() return self.gm_start.output(a_target, context.gm_start_evidence) diff --git a/openpilot/starpilot/longitudinal/tests/test_cruise_delay.py b/openpilot/starpilot/longitudinal/tests/test_cruise_delay.py index 4f5ab49d75..9c7d01263c 100644 --- a/openpilot/starpilot/longitudinal/tests/test_cruise_delay.py +++ b/openpilot/starpilot/longitudinal/tests/test_cruise_delay.py @@ -102,7 +102,7 @@ class NativeCruiseDelayTests(unittest.TestCase): expected_state = (20., -.35) if case == 'stock' else (20., -.2) np.testing.assert_allclose(current.mpc.x0[1:], expected_state) if case == 'profile': - self.assertIsNotNone(current.last_profile) + assert current.last_profile is not None # A valid ordinary profile fades from native 1.45 by dt=.05. self.assertAlmostEqual(current.last_profile.follow_seconds, 1.5) self.assertAlmostEqual(float(current.mpc.params[0, 4]), current.last_profile.follow_seconds) diff --git a/openpilot/starpilot/longitudinal/tests/test_experimental_release.py b/openpilot/starpilot/longitudinal/tests/test_experimental_release.py index 346a220186..84ce537502 100644 --- a/openpilot/starpilot/longitudinal/tests/test_experimental_release.py +++ b/openpilot/starpilot/longitudinal/tests/test_experimental_release.py @@ -8,6 +8,7 @@ from typing import Any, cast import numpy as np +from openpilot.common.test import require_value from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner from openpilot.starpilot.longitudinal.experimental_release import ( ExperimentalRelease, ReleaseFrame, ReleaseLead, SOURCES, MAX_FRAME_GAP_NS, MAX_SOURCE_AGE_NS, project, @@ -133,12 +134,13 @@ class ExperimentalReleaseTests(unittest.TestCase): def test_projection_preserves_mpc_lead_selection_and_rejects_unavailable_sources(self): cp = SimpleNamespace(openpilotLongitudinalControl=True) sm, now = native_frame(0) - self.assertIsNotNone(project(sm, cp, now, lead_index=0, conditional_handoff=KEY).lead) - self.assertIsNone(project(sm, cp, now, lead_index=1, conditional_handoff=KEY).lead) - self.assertEqual(project(sm, cp, now, lead_index=None, conditional_handoff=KEY).lead, project(sm, cp, now, lead_index=0, conditional_handoff=KEY).lead) + self.assertIsNotNone(require_value(project(sm, cp, now, lead_index=0, conditional_handoff=KEY)).lead) + self.assertIsNone(require_value(project(sm, cp, now, lead_index=1, conditional_handoff=KEY)).lead) + self.assertEqual(require_value(project(sm, cp, now, lead_index=None, conditional_handoff=KEY)).lead, + require_value(project(sm, cp, now, lead_index=0, conditional_handoff=KEY)).lead) sm['radarState'].leadTwo = sm['radarState'].leadOne sm['radarState'].leadTwo.dRel = 30. - self.assertEqual(project(sm, cp, now, lead_index=1, conditional_handoff=KEY).lead.distance, 30.) + self.assertEqual(require_value(require_value(project(sm, cp, now, lead_index=1, conditional_handoff=KEY)).lead).distance, 30.) for name in SOURCES: for defect in ('invalid', 'dead', 'stale', 'future'): value, now = native_frame(0) diff --git a/openpilot/starpilot/longitudinal/tests/test_follow_jerk.py b/openpilot/starpilot/longitudinal/tests/test_follow_jerk.py index dd523634cf..bb745f2eae 100644 --- a/openpilot/starpilot/longitudinal/tests/test_follow_jerk.py +++ b/openpilot/starpilot/longitudinal/tests/test_follow_jerk.py @@ -97,6 +97,7 @@ class FollowJerkTests(unittest.TestCase): force_stop_provider=lambda headway: (headways.append(headway) or StopPlan(model_ns=1, forcing=True))) self.assertFalse(planner.force_stop_plan.forcing) self.assertEqual(recorded[-1], 1.75) + assert planner.last_profile is not None self.assertEqual(headways, [planner.last_profile.follow_seconds]) self.assertEqual(detected.call_args.kwargs['t_follow_s'], headways[0]) self.assertEqual(planner.mpc.solution_status, 0) diff --git a/openpilot/starpilot/longitudinal/tests/test_force_stop_runtime.py b/openpilot/starpilot/longitudinal/tests/test_force_stop_runtime.py index 11cec531f2..f02285efcf 100644 --- a/openpilot/starpilot/longitudinal/tests/test_force_stop_runtime.py +++ b/openpilot/starpilot/longitudinal/tests/test_force_stop_runtime.py @@ -40,7 +40,7 @@ class Frame(dict): model.velocity.x = [10.] * 33 -class ForceStopRuntimeTests(unittest.TestCase): +class ForceStopRuntimeFixture(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) @@ -62,6 +62,8 @@ class ForceStopRuntimeTests(unittest.TestCase): self.assertTrue(output.forcing) return output + +class ForceStopRuntimeTests(ForceStopRuntimeFixture): def test_always_hold_selection_is_next_drive_and_preserves_hold(self): from openpilot.starpilot.longitudinal.enhanced_stop_hold import KEY self.params.put_bool(KEY, True, block=True) @@ -169,6 +171,7 @@ class ForceStopRuntimeTests(unittest.TestCase): self.assertFalse(step.call_args.args[0].sign) self.sample(vision_frame(33, first, published=BASE + 1_200_000_000)) self.assertFalse(step.call_args.args[0].sign) + assert self.owner.vision_stop.previous is not None self.assertEqual(self.owner.vision_stop.previous.observed_ns, first.observed_ns) self.assertIsNone(self.owner.vision_stop.distance_m) self.sample(vision_frame(34, second)) @@ -200,7 +203,7 @@ class ForceStopRuntimeTests(unittest.TestCase): self.owner.reset() self.owner.plan = self.owner.policy.step(stop_frame(0), tune) self.assertFalse(self.owner.policy.can_commit_next_frame) - self.assertIsNotNone(self.owner.plan.speed_ceiling_mps) + assert self.owner.plan.speed_ceiling_mps is not None self.assertTrue(wheel_override_blocked(self.owner, None)) def test_distance_braking_requires_exact_ioniq_control_profile(self): from unittest.mock import patch diff --git a/openpilot/starpilot/longitudinal/tests/test_gm_volt_stop.py b/openpilot/starpilot/longitudinal/tests/test_gm_volt_stop.py index c4d3840af7..1d2f9570f4 100644 --- a/openpilot/starpilot/longitudinal/tests/test_gm_volt_stop.py +++ b/openpilot/starpilot/longitudinal/tests/test_gm_volt_stop.py @@ -94,6 +94,7 @@ class TestVoltStop(unittest.TestCase): owner = volt_policy_for(cp) self.assertEqual(owner is not None, selected) if selected: + assert owner is not None self.assertEqual((owner.stopping_decel_rate, owner.starting_speed, cp.stopAccel), (1., .25, -.25) if sascm else (3., .75, -1.5)) captured = {} diff --git a/openpilot/starpilot/longitudinal/tests/test_lane_change_gap.py b/openpilot/starpilot/longitudinal/tests/test_lane_change_gap.py index 9ca46dd061..6969452287 100644 --- a/openpilot/starpilot/longitudinal/tests/test_lane_change_gap.py +++ b/openpilot/starpilot/longitudinal/tests/test_lane_change_gap.py @@ -43,7 +43,7 @@ class SavedLaneGapTests(unittest.TestCase): {'version': 2, 'enabled': True, 'minimumSpeedMps': 8.9408, 'onePerSignal': False, 'autoLaneChange': False, 'autoDelayS': 1.0, 'minimumLaneWidthM': 0.0}): restored = decode(json.dumps(document).encode()) - self.assertIsNotNone(restored) + assert restored is not None self.assertFalse(restored.close_gap) self.assertEqual(restored.close_gap_seconds, 0.75) self.assertEqual(decode(json.dumps(to_value(POLICY)).encode()), POLICY) diff --git a/openpilot/starpilot/longitudinal/tests/test_lead_approach.py b/openpilot/starpilot/longitudinal/tests/test_lead_approach.py index 8202cf2d17..e475c107a8 100644 --- a/openpilot/starpilot/longitudinal/tests/test_lead_approach.py +++ b/openpilot/starpilot/longitudinal/tests/test_lead_approach.py @@ -3,6 +3,7 @@ from types import SimpleNamespace as NS import pytest +from openpilot.common.test import require_value from openpilot.starpilot.longitudinal.lead_approach import (ApproachFrame, ApproachLead, LeadApproach, LeadApproachKey, project) @@ -62,7 +63,7 @@ def test_project_only_fresh_active_lead_one_after_drive(): assert projected is not None and projected.lead == NEAR assert projected.model_ns == NOW - 2_000_000 messages['radarState'].leadOne.present = False - assert project(sm, cp, NOW, KEY).lead is None + assert require_value(project(sm, cp, NOW, KEY)).lead is None messages['radarState'].leadOne.present = True sm.logMonoTime['radarState'] = DRIVE assert project(sm, cp, NOW, KEY) is None diff --git a/openpilot/starpilot/longitudinal/tests/test_lead_approach_planner.py b/openpilot/starpilot/longitudinal/tests/test_lead_approach_planner.py index 58169960b1..c0a3fd81f3 100644 --- a/openpilot/starpilot/longitudinal/tests/test_lead_approach_planner.py +++ b/openpilot/starpilot/longitudinal/tests/test_lead_approach_planner.py @@ -151,7 +151,7 @@ class NativeLeadApproachTests(unittest.TestCase): params.put_bool('LeadApproachBuffer', True, block=True) sm = Frame(20).with_drive() key = lead_approach_for_frame(preferences, sm, self.cp, sm.now_ns) - self.assertIsNotNone(key) + assert key is not None self.assertEqual(key.drive_id, DRIVE_NS) for defect in ('invalid', 'dead', 'future', 'stale', 'not_started', 'unknown_drive'): bad = Frame(20).with_drive() diff --git a/openpilot/starpilot/longitudinal/tests/test_lead_approach_runtime.py b/openpilot/starpilot/longitudinal/tests/test_lead_approach_runtime.py index d29131005e..1fbba649a0 100644 --- a/openpilot/starpilot/longitudinal/tests/test_lead_approach_runtime.py +++ b/openpilot/starpilot/longitudinal/tests/test_lead_approach_runtime.py @@ -48,7 +48,7 @@ class TestLeadApproachPreferences(unittest.TestCase): self.now += self.owner.REFRESH_NS self.write(KEY, b"1") key = self.sample() - self.assertIsNotNone(key) + assert key is not None self.assertEqual(key.drive_id, 1_000_000_000) for safe in (b"1", b"invalid", b"", b"1" * 20): with self.subTest(safe=safe): @@ -88,7 +88,7 @@ class TestLeadApproachPreferences(unittest.TestCase): def test_backwards_clock_and_read_failure_clear_cached_positive(self): self.write(KEY, b"1") first = self.sample() - self.assertIsNotNone(first) + assert first is not None self.write(KEY, b"0") self.assertEqual(self.sample(now=self.now + 100_000_000), first) self.now -= 1 @@ -111,7 +111,7 @@ class TestLeadApproachPreferences(unittest.TestCase): def test_current_drive_and_cp_capability_are_required(self): self.write(KEY, b"1") key = self.sample() - self.assertIsNotNone(key) + assert key is not None next_drive = self.sample(drive=1_100_000_000) self.assertNotEqual(next_drive, key) self.assertNotEqual(next_drive.settings_fingerprint, key.settings_fingerprint) @@ -132,7 +132,7 @@ class TestLeadApproachPreferences(unittest.TestCase): toyota = ToyotaCarInterface.get_non_essential_params(TOYOTA_CAR.TOYOTA_COROLLA_TSS2) self.assertTrue(toyota.openpilotLongitudinalControl) other = self.owner.sample(toyota, 2_000_000_000, 1_000_000_000) - self.assertIsNotNone(other) + assert other is not None self.assertNotEqual(other.settings_fingerprint, honda.settings_fingerprint) def test_unreadable_saved_source_is_inert(self): diff --git a/openpilot/starpilot/longitudinal/tests/test_mpc_cost_cache.py b/openpilot/starpilot/longitudinal/tests/test_mpc_cost_cache.py index f0719d61a8..3225753c23 100644 --- a/openpilot/starpilot/longitudinal/tests/test_mpc_cost_cache.py +++ b/openpilot/starpilot/longitudinal/tests/test_mpc_cost_cache.py @@ -32,6 +32,7 @@ class SolverRecorder: def reset(self): self.resets += 1 self.costs.clear() + assert self.native is not None return self.native.reset() def cost_set(self, stage, field, data): diff --git a/openpilot/starpilot/longitudinal/tests/test_mpc_terminal_constraints.py b/openpilot/starpilot/longitudinal/tests/test_mpc_terminal_constraints.py index 89480641ce..d3356f1c11 100644 --- a/openpilot/starpilot/longitudinal/tests/test_mpc_terminal_constraints.py +++ b/openpilot/starpilot/longitudinal/tests/test_mpc_terminal_constraints.py @@ -51,8 +51,11 @@ def test_native_reverse_terminal_plan_recovers_for_both_planners(mode, personali for _ in range(20): mpc.set_weights(personality=personality) mpc.set_cur_state(20.65, 1.05) - mpc.update(radar, personality=personality, **({'stop_line_m': 70., 'acceleration_max': 1.05} - if mode == 'stop_line' else {})) + if mode == 'stop_line': + assert isinstance(mpc, long_mpc.LongitudinalMpc) + mpc.update(radar, personality=personality, stop_line_m=70., acceleration_max=1.05) + else: + mpc.update(radar, personality=personality) assert mpc.solution_status == 0 assert_bounded_terminal(mpc) assert np.interp(.2, long_mpc.T_IDXS, mpc.a_solution) < 0. diff --git a/openpilot/starpilot/longitudinal/tests/test_profile_runtime.py b/openpilot/starpilot/longitudinal/tests/test_profile_runtime.py index be7425df5e..a105cdd647 100644 --- a/openpilot/starpilot/longitudinal/tests/test_profile_runtime.py +++ b/openpilot/starpilot/longitudinal/tests/test_profile_runtime.py @@ -7,6 +7,7 @@ import unittest from pathlib import Path from unittest import mock +from openpilot.common.test import require_value from openpilot.starpilot.audio.departure_alert import DepartureNotifications from openpilot.cereal import log from openpilot.common.params import Params @@ -78,10 +79,11 @@ class ProfileRuntimeTests(unittest.TestCase): (15.0, 0.53), (20.0, 0.44), (25.0, 0.34), (40.0, 0.23)): with self.subTest(acceleration_speed=speed): tuning = resolve(settings, log.LongitudinalPersonality.aggressive, speed, self.cp, traffic_mode=True) + assert tuning is not None self.assertAlmostEqual(required_float(tuning.acceleration_max), expected) host = ProfileHost(self.params) - self.assertAlmostEqual(host.sample(1_000_000_000, log.LongitudinalPersonality.aggressive, - 12.5, self.cp, traffic_mode=True).follow_seconds, 1.175) + self.assertAlmostEqual(require_value(host.sample(1_000_000_000, log.LongitudinalPersonality.aggressive, + 12.5, self.cp, traffic_mode=True)).follow_seconds, 1.175) self.assertIsNone(host.sample(1_010_000_000, log.LongitudinalPersonality.aggressive, 12.5, self.cp, traffic_mode=None)) self.assertIsNone(ProfileSmoother().sample(None, log.LongitudinalPersonality.standard, 0.05, traffic_mode=None)) @@ -169,22 +171,31 @@ class ProfileRuntimeTests(unittest.TestCase): self.params.put('LongitudinalPersonalityProfiles', legacy_document(profiles, enabled=False), block=True) disabled_document = resolve(read_traffic_settings(self.params), log.LongitudinalPersonality.standard, 12.5, self.cp, traffic_mode=True) + assert disabled_document is not None self.assertAlmostEqual(required_float(disabled_document.acceleration_max), 0.60) + assert disabled_document is not None self.assertAlmostEqual(required_float(disabled_document.cruise_brake_magnitude), 0.42) + assert disabled_document is not None self.assertFalse(disabled_document.traffic_braking_custom) self.params.put('LongitudinalPersonalityProfiles', legacy_document(profiles, enabled=True), block=True) self.params.put_bool('TrafficPersonalityProfile', False, block=True) retained_profile = resolve(read_traffic_settings(self.params), log.LongitudinalPersonality.standard, 12.5, self.cp, traffic_mode=True) + assert retained_profile is not None self.assertAlmostEqual(required_float(retained_profile.cruise_brake_magnitude), 0.35) + assert retained_profile is not None self.assertTrue(retained_profile.traffic_braking_custom) + assert retained_profile is not None self.assertAlmostEqual(required_float(retained_profile.acceleration_max), 1.4) self.params.put_bool('CustomPersonalities', False, block=True) disabled_master = resolve(read_traffic_settings(self.params), log.LongitudinalPersonality.standard, 12.5, self.cp, traffic_mode=True) + assert disabled_master is not None self.assertAlmostEqual(required_float(disabled_master.cruise_brake_magnitude), 0.42) + assert disabled_master is not None self.assertFalse(disabled_master.traffic_braking_custom) + assert disabled_master is not None self.assertNotAlmostEqual(required_float(disabled_master.acceleration_max), 1.4) self.assertIsNone(read_settings(self.params)) diff --git a/openpilot/starpilot/longitudinal/tests/test_takeoffs.py b/openpilot/starpilot/longitudinal/tests/test_takeoffs.py index 5d0e358fb8..e78d453aa4 100644 --- a/openpilot/starpilot/longitudinal/tests/test_takeoffs.py +++ b/openpilot/starpilot/longitudinal/tests/test_takeoffs.py @@ -153,6 +153,7 @@ def test_galaxy_single_toggle_roundtrip_global_and_both_runtime_readers(tmp_path assert gateway.confirm(intent['intent'], 'session', b'generation') assert params.get_bool('FasterLeadTakeoff') inputs = LongitudinalInputs(cp, params, lambda: None) + assert inputs.takeoff_preferences is not None assert inputs.takeoff_preferences.sample(1_000_000_000) from openpilot.starpilot.longitudinal.lead_takeoff_preferences import TakeoffPreferences assert TakeoffPreferences(params).sample(1_000_000_000) diff --git a/openpilot/starpilot/longitudinal/tests/test_traffic_acceleration.py b/openpilot/starpilot/longitudinal/tests/test_traffic_acceleration.py index e3cd8def2a..d9f4b493d9 100644 --- a/openpilot/starpilot/longitudinal/tests/test_traffic_acceleration.py +++ b/openpilot/starpilot/longitudinal/tests/test_traffic_acceleration.py @@ -38,7 +38,7 @@ class TrafficAccelerationPlannerTests(unittest.TestCase): self.params.put('LongitudinalPersonalityProfiles', profile_document(profiles, enabled=True, global_braking_response='standard'), block=True) target = resolve(read_traffic_settings(self.params), log.LongitudinalPersonality.standard, V_EGO, self.cp, traffic_mode=True) - self.assertIsNotNone(target) + assert target is not None return target def test_default_traffic_reaches_native_solver_without_mutating_messages(self): @@ -55,6 +55,7 @@ class TrafficAccelerationPlannerTests(unittest.TestCase): traffic.update(sm, profile_tuning=target, traffic_mode=True) self.assertEqual(message_bytes(envelopes), before) self.assertEqual(traffic.mpc.solution_status, 0) + assert traffic.last_profile is not None self.assertAlmostEqual(traffic.last_profile.acceleration_max, 0.44) self.assertLessEqual(traffic.mpc.params[0, 1], 0.44 + 1e-8) self.assertLessEqual(traffic.output_a_target, 0.44 + 1e-8) @@ -79,7 +80,7 @@ class TrafficAccelerationPlannerTests(unittest.TestCase): if force: # cap inactive, so cruise matches SET exactly; an applied cap eases its braking in self.assertLessEqual(traffic.a_cruise, baseline.a_cruise + 1e-8) self.assertEqual(traffic.last_cruise_ceiling_status, 'force_decel' if force else 'applied') - self.assertIsNotNone(traffic.last_profile) + assert traffic.last_profile is not None self.assertAlmostEqual(traffic.last_profile.cruise_brake_magnitude, 0.35) self.assertLessEqual(traffic.a_cruise, (-0.5 if force else -0.35) + 1e-8) @@ -108,6 +109,7 @@ class TrafficAccelerationPlannerTests(unittest.TestCase): sm, _ = messages() sm['carControl'].longActive = True traffic.update(sm, profile_tuning=target, traffic_mode=True) + assert traffic.last_profile is not None self.assertAlmostEqual(traffic.last_profile.acceleration_max, 0.44) sm, _ = messages() sm['carControl'].longActive = long_active @@ -126,6 +128,7 @@ class TrafficAccelerationPlannerTests(unittest.TestCase): sm['carControl'].longActive = True sm['carState'].vCruise = 50.0 no_lead.update(sm, profile_tuning=target, traffic_mode=True) + assert no_lead.last_profile is not None self.assertAlmostEqual(no_lead.last_profile.cruise_brake_magnitude, magnitude) self.assertAlmostEqual(no_lead.a_cruise, -magnitude) for hazard in ('leadOne', 'leadTwo', 'standstill'): @@ -146,6 +149,7 @@ class TrafficAccelerationPlannerTests(unittest.TestCase): planner.update(sm, profile_tuning=target, traffic_mode=True) baseline.update(sm, profile_tuning=baseline_target, traffic_mode=True) self.assertEqual(planner.mpc.solution_status, 0) + assert planner.last_profile is not None self.assertAlmostEqual(planner.last_profile.cruise_brake_magnitude, 0.42) self.assertAlmostEqual(planner.a_cruise, baseline.a_cruise, places=5) self.assertAlmostEqual(planner.output_a_target, baseline.output_a_target, places=5) @@ -160,11 +164,13 @@ class TrafficAccelerationPlannerTests(unittest.TestCase): sm['carControl'].longActive = True sm['carState'].vCruise = 50.0 planner.update(sm, profile_tuning=target, traffic_mode=True) + assert planner.last_profile is not None self.assertAlmostEqual(planner.last_profile.cruise_brake_magnitude, 2.0) sm, _ = messages(lead=True) sm['carControl'].longActive = True sm['carState'].vCruise = 50.0 planner.update(sm, profile_tuning=target, traffic_mode=True) + assert planner.last_profile is not None self.assertAlmostEqual(planner.last_profile.cruise_brake_magnitude, 0.42) recovered = [] for _ in range(16): @@ -172,6 +178,7 @@ class TrafficAccelerationPlannerTests(unittest.TestCase): sm['carControl'].longActive = True sm['carState'].vCruise = 50.0 planner.update(sm, profile_tuning=target, traffic_mode=True) + assert planner.last_profile is not None recovered.append(planner.last_profile.cruise_brake_magnitude) self.assertAlmostEqual(recovered[0], 0.42 + 2.0 * planner.dt) self.assertTrue(all(a <= b for a, b in zip(recovered, recovered[1:], strict=False))) @@ -179,15 +186,19 @@ class TrafficAccelerationPlannerTests(unittest.TestCase): sm, _ = messages(lead=True) sm['carControl'].longActive = True planner.update(sm, profile_tuning=target, traffic_mode=True) + assert planner.last_profile is not None self.assertAlmostEqual(planner.last_profile.cruise_brake_magnitude, 0.42) sm, _ = messages(lead=True) sm['carControl'].longActive = True planner.update(sm, traffic_mode=False) + assert planner.last_profile is not None self.assertGreater(planner.last_profile.cruise_brake_magnitude, 0.42) + assert planner.last_profile is not None self.assertAlmostEqual(planner.last_profile.cruise_brake_magnitude, 0.42 + 2.0 * planner.dt) sm, _ = messages(lead=True) sm['carControl'].longActive = True planner.update(sm, profile_tuning=target, traffic_mode=True) + assert planner.last_profile is not None self.assertAlmostEqual(planner.last_profile.cruise_brake_magnitude, 0.42) sm, _ = messages() sm['carControl'].longActive = True diff --git a/openpilot/starpilot/longitudinal/tests/test_vision_stop.py b/openpilot/starpilot/longitudinal/tests/test_vision_stop.py index dee4827c1d..9d393867d7 100644 --- a/openpilot/starpilot/longitudinal/tests/test_vision_stop.py +++ b/openpilot/starpilot/longitudinal/tests/test_vision_stop.py @@ -1,12 +1,8 @@ -import unittest - -from openpilot.starpilot.longitudinal.tests.test_force_stop_runtime import ForceStopRuntimeTests, Frame, BASE +from openpilot.starpilot.longitudinal.tests.test_force_stop_runtime import ForceStopRuntimeFixture, Frame, BASE from openpilot.starpilot.speed_limits.vision.tests.test_stop_observation import evidence, message, BOX -class TestVisionForceStop(unittest.TestCase): - setUp = ForceStopRuntimeTests.setUp - sample = ForceStopRuntimeTests.sample +class TestVisionForceStop(ForceStopRuntimeFixture): def frame(self, tick, *, positive=True, **changes): sm = Frame(tick, horizon=45.) diff --git a/openpilot/starpilot/maps/tests/test_shadow_lifecycle.py b/openpilot/starpilot/maps/tests/test_shadow_lifecycle.py index d192dec766..d9a6b8ee5a 100644 --- a/openpilot/starpilot/maps/tests/test_shadow_lifecycle.py +++ b/openpilot/starpilot/maps/tests/test_shadow_lifecycle.py @@ -216,7 +216,7 @@ class TestShadowLifecycle(unittest.TestCase): def test_registered_manager_uses_fixed_shadow_child(self): from openpilot.system.manager.process_config import managed_processes process = managed_processes['mapd_shadow'] - self.assertIsInstance(process, shadow.MapdShadowProcess) + assert isinstance(process, shadow.MapdShadowProcess) self.assertEqual(process.cmdline, [str(shadow.PROVIDER_BINARY), '--shadow', '--offline-root', str(shadow.OFFLINE_ROOT)]) def test_child_alone_runs_below_normal_priority_with_bounded_go_processors(self): @@ -282,7 +282,9 @@ class TestShadowLifecycle(unittest.TestCase): def fake_build(args, **kwargs): command.extend(args) result = Path(args[args.index('-o') + 1]) - result.write_bytes(fake_static_elf() + b'fixture-revision' + self.contents['upstreamRevision'].encode() + b'fixture-digest') + revision = self.contents['upstreamRevision'] + assert isinstance(revision, str) + result.write_bytes(fake_static_elf() + b'fixture-revision' + revision.encode() + b'fixture-digest') with mock.patch.object(package_shadow.shutil, 'which', return_value='/pinned/go'), \ mock.patch.object(package_shadow.subprocess, 'check_output', side_effect=fake_output), \ mock.patch.object(package_shadow.subprocess, 'run', side_effect=fake_build), \ diff --git a/openpilot/starpilot/models/runner.py b/openpilot/starpilot/models/runner.py index eb249c19b3..55fbb41c6d 100644 --- a/openpilot/starpilot/models/runner.py +++ b/openpilot/starpilot/models/runner.py @@ -156,6 +156,7 @@ class CatalogModelState: lat_delay: float frame_drop_ratio: float + model_id: str vision_input_names = ("img", "big_img") def __init__(self, cam_w: int, cam_h: int, artifact_path: Path, behavior_version: str, chestnut: bool): diff --git a/openpilot/starpilot/models/runtime.py b/openpilot/starpilot/models/runtime.py index aaffda3585..796c1adb11 100644 --- a/openpilot/starpilot/models/runtime.py +++ b/openpilot/starpilot/models/runtime.py @@ -72,12 +72,17 @@ class ModelStatusSource: if sm is None: from openpilot.cereal import messaging sm = messaging.SubMaster(list(MODEL_SERVICES)) + if sm is None: + raise RuntimeError("Model runtime subscription unavailable") self.sm = sm self.params = params self.clock = clock def snapshot(self) -> ModelStatus: - self.sm.update(0) + sm = self.sm + if sm is None: + raise RuntimeError("Model runtime subscription unavailable") + sm.update(0) from openpilot.selfdrive.modeld.helpers import chestnut_present from openpilot.starpilot.models.manager import requested_runtime_id return snapshot(self.sm, self.params, self.clock(), requested_id=requested_runtime_id(chestnut_present())) @@ -105,7 +110,10 @@ class ModelStatusSource: return home_model_label(status, commit, config if config["enabled"] else self.laboratory_json(config)) def laboratory_json(self, config: dict) -> dict: - self.sm.update(0) + sm = self.sm + if sm is None: + raise RuntimeError("Model runtime subscription unavailable") + sm.update(0) now = self.clock() process = _process(self.sm, now, process_start_ticks) output = _output(self.sm, self.params, now) if process is not None else None @@ -113,7 +121,7 @@ class ModelStatusSource: status = project_laboratory_status(config, process, load, output, now) if load is None and config['enabled']: normal = read_receipt() if process is not None else None - if (normal is not None and (normal.pid, normal.process_start_ticks) == (process.pid, process.start_ticks) and + if (process is not None and normal is not None and (normal.pid, normal.process_start_ticks) == (process.pid, process.start_ticks) and output is not None and output.model_v2_valid and output.driving_data_valid and all(normal.loaded_mono_ns <= stamp <= now and now - stamp <= 250_000_000 for stamp in (output.model_v2_mono_ns, output.driving_data_mono_ns))): diff --git a/openpilot/starpilot/models/runtime_bridge/guard-policy.json b/openpilot/starpilot/models/runtime_bridge/guard-policy.json index 46d3fa798d..b1f066b7bf 100644 --- a/openpilot/starpilot/models/runtime_bridge/guard-policy.json +++ b/openpilot/starpilot/models/runtime_bridge/guard-policy.json @@ -12,7 +12,7 @@ "libusb_guards.so": "66a3dfe48ac17899862ab80160cf6dac2c9b9707234527ba0d808f3b68404114", "ops-mapping.json": "8acf8d759ffd597684fce9e0879b488cf2b32c3f05a5ca355a77ba0026c6bb95", "qcom.py": "da93aa4b1929fbb881056669a78e765d113a2ace2d766e1cf7cce40ddba8ab95", - "usb.py": "3de547d0b92b75333593fca8f985406894e3be2c4e02b34a5fd52205ddecd890", + "usb.py": "d9a0d17397b04d026b5065764426d43b2fc2f4129261521949f40b62d475eee4", "usb_guards.c": "8b3c207de74f92b74980da35428cff6f4a198ce97f9f8b6e64aded74e0110316" }, "native_abi": "linux-aarch64-64bit", diff --git a/openpilot/starpilot/models/runtime_bridge/runtime.py b/openpilot/starpilot/models/runtime_bridge/runtime.py index 099ed8a4c2..905769c152 100644 --- a/openpilot/starpilot/models/runtime_bridge/runtime.py +++ b/openpilot/starpilot/models/runtime_bridge/runtime.py @@ -17,7 +17,7 @@ _GUARD_HASHES = { 'libbounded_wait.so': '24ed559861c8636c1026cad9a244854bb2236b5ee8b91bf21c5efbf688fa4a69', 'libusb_guards.so': '66a3dfe48ac17899862ab80160cf6dac2c9b9707234527ba0d808f3b68404114', } -_POLICY_SHA256 = 'ac50b9e31a211de9d28e97058384da5d415483ad499c2f084a6e36412be4a6a4' +_POLICY_SHA256 = 'd65e9f8303210f003d11772bb30d46ed9a8657195ce99023a05df8bf08fff9fc' _selection = None _protection = None _laboratory_request_json = None diff --git a/openpilot/starpilot/models/runtime_bridge/usb.py b/openpilot/starpilot/models/runtime_bridge/usb.py index bc7e875f18..c86341df86 100644 --- a/openpilot/starpilot/models/runtime_bridge/usb.py +++ b/openpilot/starpilot/models/runtime_bridge/usb.py @@ -34,11 +34,14 @@ class USBProtection(Protection): if ctypes.sizeof(ctypes.c_ulong) != 8 or ctypes.sizeof(ctypes.c_void_p) != 8: raise ValueError('Only the qualified 64-bit CPU host ABI is supported') self.names = [*self.ffi_names.values(), 'sp_loop_touch', 'sp_loop_check'] - addresses = [ctypes.cast(getattr(self.usb_library, name), ctypes.c_void_p).value for name in self.names] - if any(address is None for address in addresses): - raise ValueError('Missing native submission guard') + addresses = [] + for name in self.names: + address = ctypes.cast(getattr(self.usb_library, name), ctypes.c_void_p).value + if address is None: + raise ValueError('Missing native submission guard') + addresses.append(address.to_bytes(8, 'little')) self.usb_pointer = cast("LegacyBufferFactory", Buffer)(cast(str, HCQ_RUNTIME_DEV.value), len(addresses), dtypes.uint64, - initial_value=b''.join(address.to_bytes(8, 'little') for address in addresses)) + initial_value=b''.join(addresses)) self.fresh_records = [] def protect_call(self, call, *, fresh_source=False): diff --git a/openpilot/starpilot/models/tests/test_laboratory.py b/openpilot/starpilot/models/tests/test_laboratory.py index 6e8786b380..d6aaad667d 100644 --- a/openpilot/starpilot/models/tests/test_laboratory.py +++ b/openpilot/starpilot/models/tests/test_laboratory.py @@ -52,7 +52,9 @@ class LaboratoryTest(unittest.TestCase): self.lab.action('download', {'model': mid}) else: self.manager.action('download', {'model': mid}) + assert self.manager.worker is not None self.manager.worker.join(3) + assert self.manager.worker is not None self.assertFalse(self.manager.worker.is_alive()) self.assertEqual(self.manager.snapshot()['progress'], 'Downloaded!') @@ -114,7 +116,7 @@ class LaboratoryTest(unittest.TestCase): self.manager.refresh_catalog = True self.lab.snapshot() worker = self.manager.worker - self.assertIsNotNone(worker) + assert worker is not None worker.join(3) self.assertFalse(worker.is_alive()) self.assertEqual(self.manager.snapshot()['progress'], 'Catalog updated') @@ -160,6 +162,7 @@ class LaboratoryTest(unittest.TestCase): filename = artifact_path('gwm8223', self.root, 'amd').name self.payloads[filename] = b'corrupt' self.lab.action('download', {'model': 'gwm8223'}) + assert self.manager.worker is not None self.manager.worker.join(3) self.assertIn('checksum', self.manager.snapshot()['progress']) self.assertFalse(artifact_path('gwm8223', self.root, 'amd').exists()) diff --git a/openpilot/starpilot/models/tests/test_laboratory_coherent.py b/openpilot/starpilot/models/tests/test_laboratory_coherent.py index 4e791fb859..83eac7c543 100644 --- a/openpilot/starpilot/models/tests/test_laboratory_coherent.py +++ b/openpilot/starpilot/models/tests/test_laboratory_coherent.py @@ -75,9 +75,7 @@ class TestCoherentOutput(unittest.TestCase): self.assertEqual(model.warp_copied, 'a NPY buffer') -class TestCoherentFactory(unittest.TestCase): - setUp = load_fixture.TestLaboratoryLoad.setUp - factory = load_fixture.TestLaboratoryLoad.factory +class TestCoherentFactory(load_fixture.LaboratoryLoadFixture): def test_all_supported_versions_apply_after_verification_before_warmup(self): original = laboratory.freeze_request(self.root) diff --git a/openpilot/starpilot/models/tests/test_laboratory_layout.py b/openpilot/starpilot/models/tests/test_laboratory_layout.py index 567c1648e0..5bbe40d203 100644 --- a/openpilot/starpilot/models/tests/test_laboratory_layout.py +++ b/openpilot/starpilot/models/tests/test_laboratory_layout.py @@ -8,6 +8,7 @@ import weakref import numpy as np from tinygrad import Tensor +from tinygrad.device import Buffer from tinygrad.uop.ops import UOp from openpilot.starpilot.models.laboratory_layout import WeakLayoutMemo @@ -46,12 +47,17 @@ class TestWeakLayout(unittest.TestCase): base = Tensor(np.arange(16, dtype=np.float32), device='NPY').realize() view = base[2:8] with installed(cache): - first = view.uop.buffer.ensure_allocated() + buffer = view.uop.buffer + assert isinstance(buffer, Buffer) + first = buffer.ensure_allocated() np.testing.assert_array_equal(np.frombuffer(first.as_memoryview(), dtype=np.float32), np.arange(2, 8, dtype=np.float32)) storage = base.uop.base.buffer + assert isinstance(storage, Buffer) storage.deallocate() storage.allocate(opaque=np.arange(16, dtype=np.float32) + 100) - second = view.uop.buffer.ensure_allocated() + buffer = view.uop.buffer + assert isinstance(buffer, Buffer) + second = buffer.ensure_allocated() self.assertIsNot(first, second) np.testing.assert_array_equal(np.frombuffer(second.as_memoryview(), dtype=np.float32), np.arange(2, 8, dtype=np.float32) + 100) diff --git a/openpilot/starpilot/models/tests/test_laboratory_runner.py b/openpilot/starpilot/models/tests/test_laboratory_runner.py index 6cf597cd29..34bfc04f4d 100644 --- a/openpilot/starpilot/models/tests/test_laboratory_runner.py +++ b/openpilot/starpilot/models/tests/test_laboratory_runner.py @@ -202,7 +202,7 @@ class TestLaboratoryFrame(unittest.TestCase): LaboratoryPair(pair.lateral, pair.longitudinal, prepared, prepared) -class TestLaboratoryLoad(unittest.TestCase): +class LaboratoryLoadFixture(unittest.TestCase): def setUp(self): directory = tempfile.TemporaryDirectory() self.addCleanup(directory.cleanup) @@ -239,6 +239,8 @@ class TestLaboratoryLoad(unittest.TestCase): model.warmup = Mock() return model + +class TestLaboratoryLoad(LaboratoryLoadFixture): def test_separate_verified_loads_preserve_both_identities_and_warmup(self): with patch("openpilot.starpilot.models.runner.CatalogModelState", side_effect=self.factory) as loader: pair = load_laboratory_pair(8, 8, self.config, root=self.root) diff --git a/openpilot/starpilot/models/tests/test_manager.py b/openpilot/starpilot/models/tests/test_manager.py index d09e2178b2..7979b81038 100644 --- a/openpilot/starpilot/models/tests/test_manager.py +++ b/openpilot/starpilot/models/tests/test_manager.py @@ -10,6 +10,7 @@ from types import SimpleNamespace import unittest from unittest.mock import patch +from openpilot.common.test import require_value from openpilot.starpilot.models.catalog import ARTIFACT_ABI, BUNDLED_CURRENT, CATALOG_PATH, DEFAULT_SMALL from openpilot.starpilot.models.manager import ( ModelError, ModelManager, atomic_json, catalog, preferences, randomize_next_start, resolve_runtime, validate_manifest, @@ -35,6 +36,7 @@ def run_download_owner(root, manifest, data, entered, release, result): with patch('openpilot.starpilot.models.manager.shutil.disk_usage', return_value=SimpleNamespace(free=1024**3)): try: manager.action('download', {'model': 'gwm8223'}) + assert manager.worker is not None manager.worker.join(6) result.put(manager.snapshot()) finally: @@ -86,7 +88,9 @@ class ModelManagerTest(unittest.TestCase): def download(self): self.manager.action('download', {'model': 'gwm8223'}) + assert self.manager.worker is not None self.manager.worker.join(3) + assert self.manager.worker is not None self.assertFalse(self.manager.worker.is_alive()) def model_status(self): @@ -169,6 +173,7 @@ class ModelManagerTest(unittest.TestCase): self.manager.action('active', {'profile': 'small', 'model': 'gwm8223'}) selected = resolve_runtime(True, root=self.root) self.assertEqual(selected.small_id, 'gwm8223') + assert selected.small_path is not None self.assertEqual(selected.small_path.read_bytes(), self.data) self.assertTrue(all('/v26/' in u or 'model_names_v26.json' in u for u in self.urls)) @@ -285,13 +290,15 @@ class ModelManagerTest(unittest.TestCase): self.urls.clear() self.disk_usage.return_value = SimpleNamespace(free=256 * 1024 * 1024 + len(self.data) - 1) self.manager.action('download', {'model': 'pop223'}) + assert self.manager.worker is not None self.manager.worker.join(3) + assert self.manager.worker is not None self.assertFalse(self.manager.worker.is_alive()) self.assertEqual(self.manager.progress, 'Not enough storage for this model') self.assertTrue(self.urls) self.assertTrue(all('/manifests/' in url for url in self.urls)) self.assertEqual(preferences(self.root)['small'], 'gwm8223') - self.assertEqual(resolve_runtime(True, root=self.root).small_path.read_bytes(), self.data) + self.assertEqual(require_value(resolve_runtime(True, root=self.root).small_path).read_bytes(), self.data) self.assertFalse(list((self.root / 'pop223').glob('.download-*'))) def test_changed_installed_bytes_fall_back_and_ui_rechecks(self): @@ -541,7 +548,9 @@ class ModelManagerTest(unittest.TestCase): self.assertTrue(observer.snapshot()['cancelRequested']) finally: release.set() + assert self.manager.worker is not None self.manager.worker.join(3) + assert self.manager.worker is not None self.assertFalse(self.manager.worker.is_alive()) self.assertEqual(observer.snapshot()['progress'], 'Download cancelled') self.assertFalse(observer.snapshot()['downloading']) @@ -651,6 +660,7 @@ class ModelManagerTest(unittest.TestCase): self.assertFalse(self.manager.cancelled.is_set()) finally: release.set() + assert self.manager.worker is not None self.manager.worker.join(3) self.assertEqual(self.manager.progress, 'Downloaded!') self.assertTrue(self.wait_for_check()['installed']) @@ -722,6 +732,7 @@ class ModelManagerTest(unittest.TestCase): self.assertEqual(preferences(self.root)['big'], 'cinquev3') selected = resolve_runtime(True, root=self.root, randomize=True) self.assertEqual(selected.big_id, 'cinquev3') + assert selected.big_path is not None self.assertEqual(selected.big_path.read_bytes(), self.data) self.assertTrue(selected.allow_big) @@ -772,14 +783,20 @@ class ModelManagerTest(unittest.TestCase): small_row = dict(row, id="new_remote_small", name="Remote Small", uses_external_gpu=False) self.manifest["models"].extend((row, small_row)) self.manager.action("refresh_manifest", {}) + assert self.manager.worker is not None self.manager.worker.join(3) + assert self.manager.worker is not None self.assertFalse(self.manager.worker.is_alive()) self.assertNotIn(row["id"], BY_ID) self.manager.action("download", {"model": row["id"]}) + assert self.manager.worker is not None self.manager.worker.join(3) + assert self.manager.worker is not None self.assertFalse(self.manager.worker.is_alive()) self.manager.action("download", {"model": small_row["id"]}) + assert self.manager.worker is not None self.manager.worker.join(3) + assert self.manager.worker is not None self.assertFalse(self.manager.worker.is_alive()) self.manager.action("active", {"profile": "small", "model": small_row["id"]}) with self.assertRaises(ModelError): @@ -794,6 +811,7 @@ class ModelManagerTest(unittest.TestCase): self.assertEqual((selection.small_id, selection.small_version), (small_row["id"], "v16")) self.assertEqual((selection.big_id, selection.big_version, selection.big_sha256), (row["id"], "v16", row["artifact_sha256"])) + assert selection.big_path is not None self.assertTrue(selection.big_path.is_file()) with patch("openpilot.starpilot.models.manager.ROOT", self.root): self.assertEqual(resolve_selection(row["id"]).name, row["name"]) @@ -885,9 +903,11 @@ class ModelManagerTest(unittest.TestCase): self.parked = True self.manager.snapshot() self.assertTrue(entered.wait(1)) + assert self.manager.worker is not None self.assertTrue(self.manager.worker.is_alive()) self.assertFalse(any("/models/" in url for url in self.urls)) release.set() + assert self.manager.worker is not None self.manager.worker.join(3) self.assertIn(row["id"], catalog(self.root)) previous = self.manager.worker @@ -942,6 +962,7 @@ class ModelManagerTest(unittest.TestCase): for profile, mid in (('small', 'gwm8223'), ('big', 'cinquev3')): observer.action('active', {'profile': profile, 'model': mid}) self.assertEqual(preferences(self.root)[profile], mid) + assert self.manager.worker is not None self.assertTrue(self.manager.worker.is_alive()) self.assertTrue(observer.snapshot()['refreshing']) self.assertFalse(observer.snapshot()['gpuAvailable']) @@ -954,9 +975,11 @@ class ModelManagerTest(unittest.TestCase): (self.root / 'cinquev3/cinquev3_driving_tinygrad.pkl').write_bytes(b'corrupt') with self.assertRaisesRegex(ModelError, 'verify'): observer.action('active', {'profile': 'big', 'model': 'cinquev3'}) + assert self.manager.worker is not None self.assertTrue(self.manager.worker.is_alive()) finally: release.set() + assert self.manager.worker is not None self.manager.worker.join(3) observer.action('active', {'profile': 'small', 'model': 'gwm8223'}) @@ -983,6 +1006,7 @@ class ModelManagerTest(unittest.TestCase): self.manager.action('active', {'profile': 'big', 'model': 'cinquev3'}) finally: release.set() + assert self.manager.worker is not None self.manager.worker.join(3) @@ -1031,7 +1055,7 @@ class ModelManagerTest(unittest.TestCase): for mid in ('gwm8223', 'pop223'): self.manager._snapshot_installed(mid, catalog(self.root)[mid]) worker = self.manager.verify_worker - self.assertIsNotNone(worker) + assert worker is not None worker.join(3) self.assertFalse(worker.is_alive()) self.assertEqual(self.manager._snapshot_installed('gwm8223', catalog(self.root)['gwm8223']), (False, False)) diff --git a/openpilot/starpilot/models/tests/test_receipt.py b/openpilot/starpilot/models/tests/test_receipt.py index e5c2d29353..ade74c799f 100644 --- a/openpilot/starpilot/models/tests/test_receipt.py +++ b/openpilot/starpilot/models/tests/test_receipt.py @@ -6,6 +6,7 @@ import tempfile import unittest from unittest import mock +from openpilot.common.test import require_value from openpilot.starpilot.models.catalog import BUNDLED_CURRENT from openpilot.starpilot.models.receipt import (ModelReceiptOwner, ReceiptUnavailable, artifact_digest, artifact_identity, clear_receipt, prepare_artifact, process_start_ticks, read_receipt, @@ -108,20 +109,20 @@ class TestModelReceipt(unittest.TestCase): owner = ModelReceiptOwner(self.path, reasons.append, record=recorded.append) owner.start() identity = owner.capture(artifact) - self.assertIsNotNone(identity) + assert identity is not None if identity is None: self.fail("regular fixture artifact had no identity") # A diagnostic identity failure leaves model operation available. self.assertIsNone(owner.prepare(artifact, None)) self.assertEqual(reasons, ["artifact-identity-unavailable"]) prepared = owner.prepare(artifact, identity) - self.assertIsNotNone(prepared) + assert prepared is not None # Runtime fallback only emits a tiny receipt: even a broken hash/open path # cannot be reached from loaded() after startup preparation. with mock.patch('openpilot.starpilot.models.receipt.artifact_digest', side_effect=AssertionError('bulk I/O')): with mock.patch('openpilot.starpilot.models.receipt.process_start_ticks', return_value=12345): self.assertTrue(owner.loaded(prepared, ModelVariant.SMALL, "chestnut-load-failed")) - self.assertEqual(read_receipt(self.path).fallback_reason, "chestnut-load-failed") + self.assertEqual(require_value(read_receipt(self.path)).fallback_reason, "chestnut-load-failed") self.assertEqual(recorded, [read_receipt(self.path)]) owner.start() self.assertIsNone(read_receipt(self.path)) diff --git a/openpilot/starpilot/models/tests/test_shipped_default.py b/openpilot/starpilot/models/tests/test_shipped_default.py index a8ef7c5aba..f5003fba86 100644 --- a/openpilot/starpilot/models/tests/test_shipped_default.py +++ b/openpilot/starpilot/models/tests/test_shipped_default.py @@ -2,6 +2,7 @@ import hashlib import pytest +from openpilot.common.test import require_value from openpilot.common.file_chunker import package_file from openpilot.starpilot.models import manager from openpilot.starpilot.models.catalog import BUNDLED_CURRENT, DEFAULT_SMALL, DEFAULT_SMALL_SHA256 @@ -95,6 +96,6 @@ def test_shipped_default_is_verified_asynchronously_in_menu(tmp_path, monkeypatc assert row["installed"] and row["selectable"] and not row["checking"] owner.action("active", {"profile": "small", "model": DEFAULT_SMALL}) selected = manager.resolve_runtime(False, root=owner.root) - assert selected.small_id == DEFAULT_SMALL and selected.small_path.read_bytes() == data + assert selected.small_id == DEFAULT_SMALL and require_value(selected.small_path).read_bytes() == data finally: owner.close() diff --git a/openpilot/starpilot/models/tests/test_usb_source_modes.py b/openpilot/starpilot/models/tests/test_usb_source_modes.py index a65da2d800..951a34cd47 100644 --- a/openpilot/starpilot/models/tests/test_usb_source_modes.py +++ b/openpilot/starpilot/models/tests/test_usb_source_modes.py @@ -42,6 +42,7 @@ def test_dom_guard_preserves_qualified_qcom_dispatch(fresh_source, qualified): guard_type = namespace['DomUSBProtection'] assert isinstance(guard_type, type) guard = guard_type.__new__(guard_type) + assert isinstance(guard, Protection) call = SimpleNamespace(arg=SimpleNamespace(aux=HCQInfo() if qualified else object()), body=SimpleNamespace(op=sink)) if qualified: assert guard.protect_call(call, fresh_source=fresh_source) is call diff --git a/openpilot/starpilot/navigation/offline_owner.py b/openpilot/starpilot/navigation/offline_owner.py index e715c27ec2..d87bbfa420 100644 --- a/openpilot/starpilot/navigation/offline_owner.py +++ b/openpilot/starpilot/navigation/offline_owner.py @@ -29,7 +29,8 @@ class OfflineMapsOwner: heartbeat = status.get("heartbeat") running = (isinstance(heartbeat, (int, float)) and type(heartbeat) in (int, float) and math.isfinite(heartbeat) and 0 <= self.wall() - heartbeat < STATUS_STALE_SECONDS) - progress = status.get("areas") if isinstance(status.get("areas"), dict) else {} + progress = status.get("areas") + progress = progress if isinstance(progress, dict) else {} areas = [] for area in self.state.areas(): row = progress.get(area["id"]) if running else None diff --git a/openpilot/starpilot/navigation/tests/test_signal_stop_release.py b/openpilot/starpilot/navigation/tests/test_signal_stop_release.py index b67b10b997..ed9e2cb315 100644 --- a/openpilot/starpilot/navigation/tests/test_signal_stop_release.py +++ b/openpilot/starpilot/navigation/tests/test_signal_stop_release.py @@ -26,6 +26,7 @@ def case(tmp_path): from openpilot.starpilot.lateral.turn_initiation_preferences import KEY params.put_bool(KEY, True, block=True) owner = TurnIntent(params, cp) + assert owner.guidance is not None owner.guidance.sample(NOW - 1) return owner, sm diff --git a/openpilot/starpilot/replay/export.py b/openpilot/starpilot/replay/export.py index 380ea3da20..45f461d80c 100644 --- a/openpilot/starpilot/replay/export.py +++ b/openpilot/starpilot/replay/export.py @@ -103,7 +103,7 @@ class ExportVideo: self.frames += 1 def flush(self, end_us): - if self.pending is None: + if self.pending is None or self.mux is None: raise ValueError('Replay export is missing its final frame') packet, pts, keyframe = self.pending duration = end_us - pts diff --git a/openpilot/starpilot/replay/owner.py b/openpilot/starpilot/replay/owner.py index 1eec17881c..02720d69c0 100644 --- a/openpilot/starpilot/replay/owner.py +++ b/openpilot/starpilot/replay/owner.py @@ -522,7 +522,7 @@ class ReplayOwner: self.timeline_identity = file_identity(directory / 'cache/timeline.jsonl') except (OSError, ValueError): self.status['timelineState'] = 'unavailable' - if self.status.get('purpose') == 'export': + if self.status.get('purpose') == 'export' and self.export is not None: phase, progress = value.get('exportState'), value.get('exportProgress') if phase is not None: if phase not in {'rendering', 'finalizing', 'ready'} or not _finite(progress) or not 0 <= progress <= 1: @@ -779,6 +779,8 @@ class ReplayOwner: raise Rejected('export_incomplete') destination = self.root / 'exports' / sid _owned_dir(destination) + if self.export is None: + raise Rejected('export_incomplete') path.replace(destination / 'replay.mp4') self.export.update(bytes=info.st_size) except Exception as failure: @@ -815,7 +817,7 @@ class ReplayOwner: with self.lock: if reaped: previous_error = self.status.get('errorCode') - if export_budget: + if export_budget and self.export is not None: self.export.update(state='failed' if error else 'cancelled' if self.cancel.is_set() else 'ready', error=error, expires=self.clock() + EXPORT_TTL) self.status = self._idle(error or previous_error) @@ -824,7 +826,7 @@ class ReplayOwner: self.pending = None self.session_dir = None else: - if export_budget: + if export_budget and self.export is not None: self.export.update(state='failed', error=error or 'stop_unconfirmed') self.retained_lease = lease self.status.update(state='failed', errorCode=error or 'stop_unconfirmed', frameReady=False, mediaReady=False) diff --git a/openpilot/starpilot/replay/render.py b/openpilot/starpilot/replay/render.py index 78d0fd2253..f77fc4dab6 100644 --- a/openpilot/starpilot/replay/render.py +++ b/openpilot/starpilot/replay/render.py @@ -191,9 +191,13 @@ class Engine: self.reader.start() def _read(self): + stdout = self.process.stdout + if stdout is None: + self.error = "Replay status pipe unavailable" + return try: while not self.closed.is_set(): - line = self.process.stdout.readline(MAX_WORKER_STATUS + 1) + line = stdout.readline(MAX_WORKER_STATUS + 1) if not line: break if len(line) > MAX_WORKER_STATUS or not line.endswith('\n'): @@ -228,8 +232,11 @@ class Engine: return True def _write(self, value): - self.process.stdin.write(json.dumps(value, allow_nan=False, separators=(',', ':')) + '\n') - self.process.stdin.flush() + stdin = self.process.stdin + if stdin is None: + raise RuntimeError('Replay command pipe unavailable') + stdin.write(json.dumps(value, allow_nan=False, separators=(',', ':')) + '\n') + stdin.flush() def resume(self, epoch): with self.write_lock: @@ -245,7 +252,8 @@ class Engine: self.closed.set() if self.process.poll() is None: try: - self.process.stdin.close() + if self.process.stdin is not None: + self.process.stdin.close() self.process.wait(timeout=2) except (OSError, subprocess.TimeoutExpired): self.process.terminate() @@ -254,7 +262,8 @@ class Engine: except subprocess.TimeoutExpired: self.process.kill() self.process.wait(timeout=2) - self.process.stdout.close() + if self.process.stdout is not None: + self.process.stdout.close() # A hidden model/path must retain its update until a later draw reads it. @@ -353,8 +362,10 @@ class Compositor: self.monitor = DriverMonitorLayer(self.profile) self.view.driver_monitor_layer = self._monitor_layer if self.profile == 'compact': - self.view.stock_confidence_layer = lambda rect, state: self.camera.render_stock_confidence_layer(rect, lateral_active=state.lateral_active) - self.view.stock_confidence_reset = self.camera.reset_stock_confidence_layer + confidence_layer = getattr(self.camera, 'render_stock_confidence_layer', None) + if confidence_layer is not None: + self.view.stock_confidence_layer = lambda rect, state: confidence_layer(rect, lateral_active=state.lateral_active) + self.view.stock_confidence_reset = getattr(self.camera, 'reset_stock_confidence_layer', None) self.view.extra_overlays = lambda rect, state: self.camera.render_model_source_layer(rect, show_long_indicator=None) def _camera_layer(self, rect, state): @@ -550,6 +561,8 @@ class Compositor: if self._draw_rejection(epoch) is not None: return False sample = self.ui.replay_sample + if sample is None or sample.now_ns is None: + return False key = epoch, sample.now_ns from openpilot.starpilot.system.starport import gpu_nv12 from openpilot.starpilot.ui.shell import ShellMode @@ -591,9 +604,10 @@ class Compositor: return try: pixels = self.readback.finish() - sample = self.ui.replay_clock.sample() + replay_clock = self.ui.replay_clock + sample = replay_clock.sample() if replay_clock is not None else None meta = self.meta - yield (pixels, meta) if meta is not None and sample.valid and sample.epoch == meta[0] else None + yield (pixels, meta) if meta is not None and sample is not None and sample.valid and sample.epoch == meta[0] else None finally: self.readback.release() @@ -711,11 +725,11 @@ def run(session_dir: Path, route_id: str, data_dir: Path, target: str, profile: if publisher is not None: publisher.publish(pixels, epoch=epoch, position=position, captured_ns=captured_ns) elif export_budget: - if exporter is not None: + if exporter is not None and encoder is not None: packet, keyframe = encoder.encode_nv12(pixels, keyframe=not exporter.seen or epoch != published_epoch or exporter.frames % 10 == 0) exporter.frame(packet, position=position, keyframe=keyframe) published_epoch, published_at = epoch, captured_ns / 1e9 - else: + elif media is not None and encoder is not None: new_epoch = epoch != media.epoch pts_us, keyframe = timeline.next(epoch, captured_ns) packet, actual_keyframe = encoder.encode_nv12(pixels, keyframe=keyframe) @@ -736,6 +750,8 @@ def run(session_dir: Path, route_id: str, data_dir: Path, target: str, profile: pending_frame = None timeline.flush() for frame, duration in ready_frames: + if mux is None or media is None: + raise RuntimeError("Replay media output unavailable") packet, keyframe, epoch, position, captured_ns, pts_us = frame fragment = mux.frame(packet, pts_us=pts_us, duration_us=duration, keyframe=keyframe) media.publish(fragment, position=position, keyframe=keyframe) diff --git a/openpilot/starpilot/replay/tests/test_frames.py b/openpilot/starpilot/replay/tests/test_frames.py index ed2fa09790..4265b5d395 100644 --- a/openpilot/starpilot/replay/tests/test_frames.py +++ b/openpilot/starpilot/replay/tests/test_frames.py @@ -1,6 +1,7 @@ import pytest import fcntl +from openpilot.common.test import require_value from openpilot.starpilot.replay.frames import HEADER_SIZE, SEQ, ReplayFramePublisher, ReplayFrameReader SESSION = 'a' * 32 @@ -13,10 +14,11 @@ def test_coherent_epoch_and_viewer_close_preserves_owned_file(tmp_path): try: publisher.publish(b'\x11' * 32, epoch=1, position=15.25, captured_ns=123) frame = reader.latest() + assert frame is not None assert (frame.data, frame.epoch, frame.position, frame.frame_id) == (b'\x11' * 32, 1, 15.25, 1) assert reader.latest() is None publisher.publish(b'\x22' * 32, epoch=2, position=2, captured_ns=456) - assert reader.latest().epoch == 2 + assert require_value(reader.latest()).epoch == 2 reader.close() assert reader.latest() is None assert path.exists() @@ -75,7 +77,7 @@ def test_kernel_lock_prevents_copying_pixels_while_writer_is_active(tmp_path): fcntl.flock(publisher.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) assert reader.latest() is None fcntl.flock(publisher.fd, fcntl.LOCK_UN) - assert reader.latest().data == b'a' * 32 + assert require_value(reader.latest()).data == b'a' * 32 assert reader.fd is not None fcntl.flock(reader.fd, fcntl.LOCK_SH | fcntl.LOCK_NB) with pytest.raises(RuntimeError, match='consumer stalled'): @@ -83,7 +85,7 @@ def test_kernel_lock_prevents_copying_pixels_while_writer_is_active(tmp_path): assert publisher.frame_id == 1 fcntl.flock(reader.fd, fcntl.LOCK_UN) publisher.publish(b'b' * 32, epoch=2, position=1, captured_ns=2) - assert reader.latest().data == b'b' * 32 + assert require_value(reader.latest()).data == b'b' * 32 finally: reader.close() publisher.close() diff --git a/openpilot/starpilot/sentry_mode/tests/test_actions.py b/openpilot/starpilot/sentry_mode/tests/test_actions.py index a10f00e911..05182765bf 100644 --- a/openpilot/starpilot/sentry_mode/tests/test_actions.py +++ b/openpilot/starpilot/sentry_mode/tests/test_actions.py @@ -7,6 +7,7 @@ import tempfile import unittest from unittest import mock +from openpilot.common.test import require_value from openpilot.common.params import Params from openpilot.starpilot.sentry_mode.actions import commit from openpilot.starpilot.sentry_mode.preferences import KEY, Preferences, decode, encode @@ -94,11 +95,11 @@ class SentryActionsTest(unittest.TestCase): owner = SentryOwner(self.params, lambda: True) self.assertTrue(owner.apply(FeatureSettingsRequest(SENSITIVITY, None, "0.005", confirmation=True))) first = self.path.read_bytes() - self.assertEqual(decode(first).settings.sensitivity, 0.005) + self.assertEqual(require_value(decode(first)).settings.sensitivity, 0.005) self.assertFalse(owner.apply(FeatureSettingsRequest(WARNING, first, "10.1", confirmation=True))) self.assertEqual(self.path.read_bytes(), first) self.assertTrue(owner.apply(FeatureSettingsRequest(WARNING, first, "10.0", confirmation=True))) - self.assertEqual(decode(self.path.read_bytes()).settings.warning_time_seconds, 10.0) + self.assertEqual(require_value(decode(self.path.read_bytes())).settings.warning_time_seconds, 10.0) self.path.unlink() calls = 0 def parked(): diff --git a/openpilot/starpilot/software/fast_update.py b/openpilot/starpilot/software/fast_update.py index f3ff675950..b1539bbfb1 100644 --- a/openpilot/starpilot/software/fast_update.py +++ b/openpilot/starpilot/software/fast_update.py @@ -112,7 +112,7 @@ def run(command, cwd, progress=None, *, timeout=None, download=False, cancelled= pending_progress = None progress_at = time.monotonic() for key, _ in selector.select(min(0.1, max(0.0, deadline - time.monotonic()))): - chunk = os.read(key.fileobj.fileno(), 4096) + chunk = os.read(key.fd, 4096) if not chunk: selector.unregister(key.fileobj) continue diff --git a/openpilot/starpilot/soloist/phone_audio.py b/openpilot/starpilot/soloist/phone_audio.py index 9fc0f75a55..adfc211d28 100644 --- a/openpilot/starpilot/soloist/phone_audio.py +++ b/openpilot/starpilot/soloist/phone_audio.py @@ -69,6 +69,8 @@ class PhoneInput: def _call(self, *args, **kwargs): try: + if self.client is None: + raise RuntimeError("Bluetooth service unavailable") return self.client._call(*args, **kwargs) except Exception as error: raise RuntimeError(str(error)) from error @@ -219,8 +221,11 @@ def relay(address: str, server: str, config: Path): '-r', '48000', '-c', '2', '--buffer-time=200000', '--period-time=20000'], env={**os.environ, 'ALSA_CONFIG_PATH': str(config)}, stdout=subprocess.PIPE) as capture: try: + source = capture.stdout + if source is None: + raise RuntimeError("Phone audio pipe unavailable") mute_until = 0.0 - while data := capture.stdout.read(3840): + while data := source.read(3840): now = time.monotonic() if len(data) % 4: raise RuntimeError('Incomplete phone audio frame') diff --git a/openpilot/starpilot/soloist/supervisor.py b/openpilot/starpilot/soloist/supervisor.py index 5d66c6b647..1eb78b112d 100644 --- a/openpilot/starpilot/soloist/supervisor.py +++ b/openpilot/starpilot/soloist/supervisor.py @@ -523,11 +523,14 @@ class Supervisor: self._set('retrying', 'Reconnecting Spotify on the new network…') def _pull(self, now: float) -> None: - snapshot = self.client.snapshot() if self.client is not None else {} + client = self.client + if client is None: + return + snapshot = client.snapshot() if now < self.pull_at or not (snapshot.get('connected') and snapshot.get('loggedIn')) or snapshot.get('active') or parked(): return self.pull_at = now + PULL_RETRY_SECONDS - self.client.send('activate', {}) + client.send('activate', {}) def _retry_login(self, now: float) -> None: self.stop_children() diff --git a/openpilot/starpilot/soloist/tests/test_package.py b/openpilot/starpilot/soloist/tests/test_package.py index c316420b15..93f5198523 100644 --- a/openpilot/starpilot/soloist/tests/test_package.py +++ b/openpilot/starpilot/soloist/tests/test_package.py @@ -191,6 +191,7 @@ def test_import_job_reports_failure_and_removes_upload(tmp_path): job = package.ImportJob(layout, digest=lambda: ('0' * 32, 1), probe=lambda _exe: VERSION_LINE, now=NOW) path = write(tmp_path, archive()) job.start(path=path, enabled=lambda: True) + assert job.thread is not None job.thread.join(timeout=5) assert job.status()['state'] == 'failed' and job.status()['code'] == 'NOT_OFFICIAL' assert not path.exists() diff --git a/openpilot/starpilot/speed_limits/offset_document.py b/openpilot/starpilot/speed_limits/offset_document.py index 3a185d35bd..258747974e 100644 --- a/openpilot/starpilot/speed_limits/offset_document.py +++ b/openpilot/starpilot/speed_limits/offset_document.py @@ -92,7 +92,7 @@ def decode(raw: bytes) -> OffsetDocument | NeedsReview: def to_value(document: OffsetDocument | NeedsReview) -> dict[str, object]: checked = validate(document) - return ({'version': 1, 'state': 'needs_review'} if checked is NEEDS_REVIEW else + return ({'version': 1, 'state': 'needs_review'} if isinstance(checked, NeedsReview) else {'version': 1, 'bounds_mps': list(checked.bounds_mps), 'offsets_mps': list(checked.offsets_mps)}) diff --git a/openpilot/starpilot/speed_limits/selection.py b/openpilot/starpilot/speed_limits/selection.py index a4be436ea7..a422483506 100644 --- a/openpilot/starpilot/speed_limits/selection.py +++ b/openpilot/starpilot/speed_limits/selection.py @@ -59,13 +59,14 @@ def select_limit(observations: Mapping[Source, Observation], policy: SelectionPo unavailable = [] below_minimum = [] - eligible = [] + eligible: dict[Source, float] = {} def consider(source): observation = observations[source] - if observation.kind == ObservationKind.VALID: - if observation.candidate.speed_mps >= MINIMUM_LIMIT_MPS: - eligible.append(source) + candidate = observation.candidate + if observation.kind == ObservationKind.VALID and candidate is not None: + if candidate.speed_mps >= MINIMUM_LIMIT_MPS: + eligible[source] = candidate.speed_mps return below_minimum.append(source) unavailable.append((source, ObservationKind.ABSENT)) @@ -77,16 +78,16 @@ def select_limit(observations: Mapping[Source, Observation], policy: SelectionPo if eligible: if policy.mode == SelectionMode.ORDERED: - selected = eligible[0] + selected = next(iter(eligible)) else: # Stable source ordering makes equal-limit ties independent of input map order. choose = max if policy.mode == SelectionMode.HIGHEST else min - selected = choose(eligible, key=lambda source: observations[source].candidate.speed_mps) + selected = choose(eligible, key=eligible.__getitem__) reason = "primary" elif policy.online_fallback: considered += (Source.ONLINE,) consider(Source.ONLINE) - selected = eligible[0] if eligible else None + selected = next(iter(eligible)) if eligible else None reason = "online_fallback" if selected is not None else "no_candidate" else: selected = None diff --git a/openpilot/starpilot/speed_limits/tests/test_action_arbitration.py b/openpilot/starpilot/speed_limits/tests/test_action_arbitration.py index 1da932fd32..903470aaca 100644 --- a/openpilot/starpilot/speed_limits/tests/test_action_arbitration.py +++ b/openpilot/starpilot/speed_limits/tests/test_action_arbitration.py @@ -30,6 +30,7 @@ class TestActionArbitration(unittest.TestCase): def test_confirmation_consumption_survives_release_and_long_delay(self): pending = accept.step(accept.new_session(SESSION), OBSERVATION, AUTHORITY, accept.Policy(), now_ns=0) ledger = begin() + assert pending.state.pending is not None decision = accept.step(pending.state, OBSERVATION, AUTHORITY, accept.Policy(), now_ns=2, action=accept.DriverAction(SESSION, 1, pending.state.pending.decision_id, accept.ActionKind.ACCEPT)) bound = arb.resolve_acceptance(ledger, 1, decision, now_ns=2) @@ -43,17 +44,20 @@ class TestActionArbitration(unittest.TestCase): def test_adoption_receipt_and_effect_keep_originating_action(self): shown = accept.step(accept.new_session(SESSION), OBSERVATION, AUTHORITY, accept.Policy(), now_ns=0) + assert shown.state.presentation is not None request = accept.AdoptRequest(SESSION, 1, shown.state.presentation.presentation_id, CANDIDATE) adopted = accept.step(shown.state, OBSERVATION, AUTHORITY, accept.Policy(), now_ns=2, adopt=request) ledger = arb.resolve_acceptance(begin(), 1, adopted, now_ns=2).state result = change(ledger, previous=25.0, selected=adopted.control_target_mps, now=10_000_000_000) self.assertEqual(result.change.disposition, arb.Disposition.SLC_CONSUMED) + assert adopted.adoption_receipt is not None self.assertEqual(result.change.action_id, adopted.adoption_receipt.sequence_id) def test_final_unconsumed_receipt_does_not_swallow_cruise_input(self): shown = accept.step(accept.new_session(SESSION), OBSERVATION, AUTHORITY, accept.Policy(), now_ns=0) decision = accept.step(shown.state, OBSERVATION, AUTHORITY, accept.Policy(), now_ns=2, action=accept.DriverAction(SESSION, 1, 999, accept.ActionKind.ACCEPT)) + assert decision.action_receipt is not None self.assertFalse(decision.action_receipt.consumed) ledger = arb.resolve_acceptance(begin(), 1, decision, now_ns=2).state result = change(ledger) @@ -199,6 +203,7 @@ class TestActionArbitration(unittest.TestCase): def test_receipt_replay_errors_and_wrong_action_do_not_resolve(self): pending = accept.step(accept.new_session(SESSION), OBSERVATION, AUTHORITY, accept.Policy(), now_ns=0) + assert pending.state.pending is not None accepted = accept.step(pending.state, OBSERVATION, AUTHORITY, accept.Policy(), now_ns=2, action=accept.DriverAction(SESSION, 1, pending.state.pending.decision_id, accept.ActionKind.ACCEPT)) assert accepted.action_receipt is not None @@ -222,6 +227,7 @@ class TestActionArbitration(unittest.TestCase): def test_acceptance_clock_must_belong_to_transaction_lifecycle(self): pending = accept.step(accept.new_session(SESSION), OBSERVATION, AUTHORITY, accept.Policy(), now_ns=0) + assert pending.state.pending is not None accepted = accept.step(pending.state, OBSERVATION, AUTHORITY, accept.Policy(), now_ns=2, action=accept.DriverAction(SESSION, 1, pending.state.pending.decision_id, accept.ActionKind.ACCEPT)) for timestamp in (0, 100): diff --git a/openpilot/starpilot/speed_limits/tests/test_advance.py b/openpilot/starpilot/speed_limits/tests/test_advance.py index 2211930329..1ec579d70b 100644 --- a/openpilot/starpilot/speed_limits/tests/test_advance.py +++ b/openpilot/starpilot/speed_limits/tests/test_advance.py @@ -40,6 +40,7 @@ class Drive: offsets=OffsetSchedule((OffsetBand(0., None, 2.),))) self.runtime = Runtime(settings, session_id='drive', is_metric=True) self.tick(target=0.) + assert self.runtime.state.acceptance.accepted is not None assert self.runtime.state.acceptance.accepted.candidate.speed_mps == 20. self.runtime.settings = replace(settings, acceptance=acc.Policy(confirm_lower=confirm, confirm_higher=confirm)) @@ -198,6 +199,7 @@ def test_reverse_and_inactive_control_do_not_start_advance(): def test_confirmation_latches_on_slowdown_and_stop_then_times_out_once(): drive = Drive(confirm=True) first = drive.tick().message.slcState + assert drive.runtime.advance.encounter is not None start = drive.runtime.advance.encounter.started_ns assert start is not None slower = drive.tick(speed=1., distance=59.).message.slcState @@ -213,6 +215,7 @@ def test_confirmation_latches_on_slowdown_and_stop_then_times_out_once(): def test_exact_deadline_action_wins_and_crossing_does_not_repeat(kind): drive = Drive(confirm=True) state = drive.tick().message.slcState + assert drive.runtime.advance.encounter is not None start = drive.runtime.advance.encounter.started_ns assert start is not None action = drive.action(state, kind) @@ -227,6 +230,7 @@ def test_exact_deadline_action_wins_and_crossing_does_not_repeat(kind): def test_recovery_keeps_deadline_and_retires_actions_only_for_a_new_producer(producer): drive = Drive(confirm=True) first = drive.tick().message.slcState + assert drive.runtime.advance.encounter is not None start = drive.runtime.advance.encounter.started_ns assert start is not None lost = drive.tick(alive=False) @@ -271,7 +275,9 @@ def test_source_gap_keeps_early_confirmation_actionable_and_does_not_repeat_at_t assert not output.message.slcState.hasPending assert output.result.ceiling.speed_mps == (17. if kind == 'accept' else 22.) encounter = drive.runtime.advance.encounter + assert encounter is not None assert (encounter.accepted_ns is not None) == (kind == 'accept') + assert encounter is not None assert encounter.declined == (kind == 'reject') crossed = drive.tick(current=15., target=0., way=2) assert not crossed.message.slcState.hasPending @@ -286,6 +292,7 @@ def test_disengagement_cancels_early_confirmation_and_reengagement_gets_a_fresh_ drive.sm['controlsState'].longControlState = 'off' inactive = drive.tick(at=start+2_000_000_000) assert not inactive.message.slcState.hasPending + assert drive.runtime.advance.encounter is not None assert not drive.runtime.advance.encounter.declined drive.sm['carControl'].enabled = drive.sm['carControl'].longActive = True drive.sm['selfdriveState'].enabled = True @@ -298,6 +305,7 @@ def test_disengagement_cancels_early_confirmation_and_reengagement_gets_a_fresh_ assert stale_action.message.slcState.hasPending assert drive.tick(at=restarted+9_000_000_000).message.slcState.hasPending assert not drive.tick(at=restarted+acc.CONFIRMATION_NS).message.slcState.hasPending + assert drive.runtime.advance.encounter is not None assert drive.runtime.advance.encounter.declined @@ -342,6 +350,7 @@ def test_short_zone_can_qualify_exit_immediately_without_hidden_dwell(): assert exit_offer.message.slcState.speedLimit == 15. assert exit_offer.message.slcState.acceptedSpeedLimit == 20. assert exit_offer.result.ceiling.speed_mps == 22. + assert drive.runtime.history_limit is not None assert drive.runtime.history_limit.candidate.speed_mps == 15. drive.runtime.reset() assert drive.tick(alive=False).message.slcState.acceptedSpeedLimit == 15. @@ -391,6 +400,7 @@ def test_stale_current_adopt_cannot_cancel_or_replace_a_fresh_producer_proposal( assert not rejected.result.errors assert rejected.message.slcState.acceptedSpeedLimit == 15. assert rejected.message.slcState.upcomingBoundaryId == BOUNDARY + assert drive.runtime.advance.encounter is not None assert not drive.runtime.advance.encounter.disabled @@ -465,7 +475,10 @@ def test_actual_go_fixture_qualifies_current_and_upcoming_fields_with_host_schem source = MapSource() current = source.step(frame, received=True, now_boot_ns=frame.event_mono_ns, transport_alive=True, drive_session='drive', car_fingerprint='car') + assert current.candidate is not None assert current.candidate.speed_mps == 20. + assert source.upcoming is not None + assert source.upcoming.observation.candidate is not None assert source.upcoming.observation.candidate.speed_mps == 15. assert source.upcoming.boundary_id == BOUNDARY and source.upcoming.way_id == 2 and source.upcoming.distance_m == 60. @@ -817,9 +830,11 @@ def test_early_limit_replaces_history_only_after_current_road_confirms_it(): drive = Drive() early = drive.tick(target=25.).message.slcState assert early.acceptedSpeedLimit == 25. and early.acceptedIsPreview + assert drive.runtime.history_limit is not None assert drive.runtime.history_limit.candidate.speed_mps == 20. gap = drive.tick(alive=False).message.slcState assert gap.acceptedSpeedLimit == 25. and gap.acceptedIsPreview + assert drive.runtime.history_limit is not None assert drive.runtime.history_limit.candidate.speed_mps == 20. drive.runtime.reset() assert drive.tick(alive=False).message.slcState.acceptedSpeedLimit == 20. @@ -827,6 +842,7 @@ def test_early_limit_replaces_history_only_after_current_road_confirms_it(): assert drive.tick(target=25.).message.slcState.acceptedSpeedLimit == 25. arrived = drive.tick(current=25., way=2, target=0.).message.slcState assert arrived.acceptedSpeedLimit == 25. and not arrived.acceptedIsPreview + assert drive.runtime.history_limit is not None assert drive.runtime.history_limit.candidate.speed_mps == 25. drive.runtime.reset() assert drive.tick(alive=False).message.slcState.acceptedSpeedLimit == 25. diff --git a/openpilot/starpilot/speed_limits/tests/test_confirmation_engagement.py b/openpilot/starpilot/speed_limits/tests/test_confirmation_engagement.py index 606a9942d3..86854ed970 100644 --- a/openpilot/starpilot/speed_limits/tests/test_confirmation_engagement.py +++ b/openpilot/starpilot/speed_limits/tests/test_confirmation_engagement.py @@ -37,6 +37,7 @@ def test_runtime_cancels_old_action_and_restarts_confirmation_after_disengagemen sm['controlsState'].longControlState = 'off' inactive = runtime.step(sm, cp, now_ns=START+50_000_000, request=action) assert not inactive.message.slcState.hasPending and not inactive.message.slcState.hasAccepted + assert inactive.action_result is not None assert not inactive.action_result.change now = START+20_000_000_000 sm.advance(now) diff --git a/openpilot/starpilot/speed_limits/tests/test_overrides.py b/openpilot/starpilot/speed_limits/tests/test_overrides.py index 11d3ea496a..26b13178c0 100644 --- a/openpilot/starpilot/speed_limits/tests/test_overrides.py +++ b/openpilot/starpilot/speed_limits/tests/test_overrides.py @@ -167,12 +167,14 @@ class OverrideTests(unittest.TestCase): pending_policy = acc.Policy(confirm_lower=True, confirm_higher=True) state = replace(acc.new_session(SESSION, acc.AcceptedLimit(HIGH, SESSION, 0)), received_speed_mps=HIGH.speed_mps) pending = acc.step(state, observation(LOW), ACTIVE, pending_policy, now_ns=0) + assert pending.state.pending is not None action = acc.DriverAction(SESSION, 1, pending.state.pending.decision_id, acc.ActionKind.ACCEPT) ledger = arb.step(arb.new_ledger(SESSION), arb.BeginAction(SESSION, 1, arb.Origin.DRIVER_CRUISE, self.first.context.context_id), now_ns=1).state accepted = acc.step(pending.state, observation(LOW), ACTIVE, pending_policy, now_ns=2, action=action) ledger = arb.resolve_acceptance(ledger, 1, accepted, now_ns=2).state delayed = arb.step(ledger, arb.CruiseChange(SESSION, 1, 1, 20.0, 25.0), now_ns=60_000_000_000).change + assert delayed is not None self.assertEqual(delayed.disposition, arb.Disposition.SLC_CONSUMED) self.decision(60_000_000_000) result = self.reduce(60_000_000_000, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0), change=delayed) @@ -318,6 +320,7 @@ class OverrideTests(unittest.TestCase): replay = ov.step(next_state.state, next_acceptance, ACTIVE, POLICY, ov.SelectedEvidence(ov.EvidenceKind.VALID, 26.0), PEDAL_OFF, now_ns=1, change=fresh) self.assertIsNone(replay.contribution_mps) + assert replay.event_receipt is not None self.assertEqual(replay.event_receipt.status, "foreign_session") def test_malformed_state_is_inert(self): @@ -384,6 +387,7 @@ class OverrideTests(unittest.TestCase): again = self.reduce(4, acceptance=adopted, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 25.0)) self.assertEqual(again.context, result.context) delayed = arb.step(ledger, arb.CruiseChange(SESSION, 3, 2, 25.0, 20.0), now_ns=10_000_000_000).change + assert delayed is not None self.assertEqual(delayed.disposition, arb.Disposition.SLC_CONSUMED) self.decision(10_000_000_000) no_rearm = self.reduce(10_000_000_000, selected=ov.SelectedEvidence(ov.EvidenceKind.VALID, 20.0), change=delayed) diff --git a/openpilot/starpilot/speed_limits/tests/test_runtime_replay.py b/openpilot/starpilot/speed_limits/tests/test_runtime_replay.py index ac2c1725d3..2df59844cf 100644 --- a/openpilot/starpilot/speed_limits/tests/test_runtime_replay.py +++ b/openpilot/starpilot/speed_limits/tests/test_runtime_replay.py @@ -324,6 +324,7 @@ class RuntimeReplayTests(unittest.TestCase): held = car.CarState(cruiseState={'available': True}) release = car.CarState(cruiseState={'available': True}, buttonEvents=[car.CarState.ButtonEvent(type='accelCruise', pressed=False)]) helper.update_v_cruise(press, True, False, pending) + assert helper.slc_consumed_button is not None self.assertEqual(helper.slc_consumed_button.pending, pending) self.assertEqual(helper.v_cruise_kph, 70.0) for _ in range(55): @@ -371,7 +372,10 @@ class RuntimeReplayTests(unittest.TestCase): 2_100_000_000, 'confirmationReject', runtime.session_id, pending.decisionId, pending.presentationId)) self.assertEqual(rejected.message.slcState.actionStatus, 'reject') + assert rejected.result.acceptance is not None self.assertEqual(rejected.result.acceptance.basis, 'driver_reject') + assert first.result.acceptance is not None + assert rejected.result.acceptance is not None self.assertEqual(rejected.result.acceptance.state.accepted, first.result.acceptance.state.accepted) self.assertFalse(rejected.message.slcState.hasPending) self.assertEqual(runtime.ledger.transactions, ()) @@ -383,6 +387,7 @@ class RuntimeReplayTests(unittest.TestCase): adopted = runtime.step(self.sm, self.cp, now_ns=2_050_000_000, request=Action(runtime.session_id, 1, 0, shown.presentationId, 'adopt')) self.assertEqual(adopted.message.slcState.actionStatus, 'adopt') + assert adopted.result.ceiling is not None self.assertEqual(adopted.result.ceiling.speed_mps, 25.) self.assertEqual(self.sm['carState'].vCruise, 100.) @@ -666,9 +671,13 @@ class RuntimeReplayTests(unittest.TestCase): params.put('SLCQualifiedHistory', json.loads(raw), block=True) self.assertEqual(params.get('SLCQualifiedHistory')['source_schema'], json.loads(raw)['source_schema']) remembered = history.decode(params.get('SLCQualifiedHistory'), session_id='next-drive') + assert remembered is not None self.assertEqual(remembered.candidate.speed_mps, 20.) + assert remembered is not None self.assertEqual(remembered.candidate.observation_identity.kind, acc.IdentityKind.SESSION_VALUE) + assert remembered is not None self.assertEqual(remembered.candidate.observation_identity.session_id, 'next-drive') + assert remembered is not None self.assertNotEqual(remembered.candidate.observation_identity, candidate.observation_identity) tampered = json.loads(raw) tampered['source_schema'] = 'wrong' @@ -772,6 +781,7 @@ class RuntimeReplayTests(unittest.TestCase): self.sm.advance(2_100_000_000) request = Action(runtime.session_id, 17, pending.message.slcState.decisionId, pending.message.slcState.presentationId, 'reject') rejected = runtime.step(self.sm, self.cp, now_ns=2_100_000_000, request=request) + assert rejected.action_result is not None self.assertEqual(rejected.action_result.status, 'resolved') self.assertEqual(rejected.message.slcState.actionSequenceId, 17) self.assertEqual(rejected.message.slcState.actionStatus, 'reject') @@ -793,6 +803,8 @@ class RuntimeReplayTests(unittest.TestCase): source.carStateLogMonoTime = 2_000_000_000 matched = runtime.step(self.sm, self.cp, now_ns=2_000_000_000) + assert matched.result.selection is not None + assert matched.result.selection.observation.candidate is not None first_identity = matched.result.selection.observation.candidate.observation_identity.value self.assertTrue(matched.message.slcState.hasAccepted) self.assertFalse(matched.message.slcState.hasPending) @@ -802,6 +814,8 @@ class RuntimeReplayTests(unittest.TestCase): self.assertFalse(lagged.message.slcState.hasPending) source.producerSessionId = 'restarted-card' restarted = runtime.step(self.sm, self.cp, now_ns=2_010_000_000) + assert restarted.result.selection is not None + assert restarted.result.selection.observation.candidate is not None second_identity = restarted.result.selection.observation.candidate.observation_identity.value self.assertNotEqual(first_identity, second_identity) diff --git a/openpilot/starpilot/speed_limits/tests/test_selection.py b/openpilot/starpilot/speed_limits/tests/test_selection.py index 22c1b0e4bc..304a1cb54b 100644 --- a/openpilot/starpilot/speed_limits/tests/test_selection.py +++ b/openpilot/starpilot/speed_limits/tests/test_selection.py @@ -4,6 +4,7 @@ from typing import Any, cast import unittest from dataclasses import replace +from openpilot.common.test import require_value from openpilot.starpilot.speed_limits.acceptance import Candidate, IdentityKind, Observation, ObservationIdentity, ObservationKind from openpilot.starpilot.speed_limits.acceptance import (AcceptedLimit, ActionKind, AdoptRequest, Authority, DriverAction, LongitudinalOwner, Mode, Policy, new_session, step) @@ -168,15 +169,17 @@ class TestSourceSelection(unittest.TestCase): # Values and sequence reproduce the observed accepted65 / reject45 / lost-source case. for index, (speed, reject) in enumerate(((29.0576, False), (20.1168, False), (20.1168, True), (None, False))): chosen = select_limit(observations(dashboard=speed) if speed is not None else observations(), source_policy) - action = DriverAction(state.session_id, 1, state.pending.decision_id, ActionKind.REJECT) if reject else None + action = DriverAction(state.session_id, 1, require_value(state.pending).decision_id, ActionKind.REJECT) if reject else None decision = step(state, chosen.observation, authority, acceptance_policy, now_ns=index * 50_000_000, action=action) self.assertFalse(decision.errors) self.assertEqual(decision.control_target_mps, 29.0576) + assert decision.state.accepted is not None self.assertEqual(decision.state.accepted.candidate.speed_mps, 29.0576) self.assertEqual(decision.state.pending is not None, index == 1) if index > 0: self.assertIsNone(decision.history_write) if reject: + assert decision.action_receipt is not None self.assertTrue(decision.action_receipt.consumed) state = decision.state returned = select_limit(observations(dashboard=20.1168), source_policy) @@ -198,6 +201,7 @@ class TestSourceSelection(unittest.TestCase): selected = select_limit(supplied, source_policy) decision = step(accepted.state, selected.observation, system, acceptance_policy, now_ns=1) self.assertEqual(decision.state.accepted, accepted.state.accepted) + assert accepted.state.accepted is not None self.assertEqual(decision.control_target_mps, accepted.state.accepted.candidate.speed_mps) self.assertEqual(decision.state.observation.kind, kind) for authority in (Authority(Mode.LATERAL_ONLY, LongitudinalOwner.NONE, True, False, False, False), @@ -216,6 +220,7 @@ class TestSourceSelection(unittest.TestCase): supplied[Source.DASHBOARD] = Observation(ObservationKind.VALID, candidate) selected = select_limit(supplied, policy(slots=(Source.DASHBOARD, None))) self.assertIs(selected.observation.candidate, candidate) + assert selected.observation.candidate is not None self.assertIs(selected.observation.candidate.observation_identity, identity) self.assertEqual(selected.errors, ()) @@ -243,19 +248,24 @@ class TestSourceSelection(unittest.TestCase): supplied[Source.DASHBOARD] = Observation( ObservationKind.VALID, Candidate("dashboard", ObservationIdentity(IdentityKind.SESSION_VALUE, session_id="drive"), speed)) selected = select_limit(supplied, selection_policy) - action = DriverAction("drive", 0, state.pending.decision_id, ActionKind.REJECT) if index == 2 else None + action = DriverAction("drive", 0, require_value(state.pending).decision_id, ActionKind.REJECT) if index == 2 else None decision = step(state, selected.observation, authority, acceptance_policy, now_ns=index, action=action) self.assertEqual(decision.errors, ()) self.assertEqual(decision.control_target_mps, 29.0576) state = decision.state self.assertEqual(decision.basis, "rejected") shown = state.presentation + assert shown is not None request = AdoptRequest("drive", 1, shown.presentation_id, shown.candidate) adopted = step(state, selected.observation, authority, acceptance_policy, now_ns=5, adopt=request) + assert adopted.adoption_receipt is not None self.assertTrue(adopted.adoption_receipt.consumed) self.assertEqual(adopted.control_target_mps, 20.1168) self.assertIsNone(adopted.state.rejected) + assert adopted.adoption_receipt is not None self.assertEqual(adopted.adoption_receipt.sequence_id, request.sequence_id) + assert shown is not None + assert adopted.history_write is not None self.assertEqual(adopted.history_write.candidate, shown.candidate) diff --git a/openpilot/starpilot/speed_limits/tests/test_set_speed.py b/openpilot/starpilot/speed_limits/tests/test_set_speed.py index 3155dc4f51..9e8f5d42a1 100644 --- a/openpilot/starpilot/speed_limits/tests/test_set_speed.py +++ b/openpilot/starpilot/speed_limits/tests/test_set_speed.py @@ -391,6 +391,7 @@ def test_automatic_adoption_does_not_consume_confirmation_actions_and_late_manua first = acc.step(acc.new_session('drive'), observation, authority, policy, now_ns=0) action = acc.DriverAction('drive', 1, first.state.next_decision_id - 1, acc.ActionKind.ACCEPT) output = acc.step(first.state, observation, authority, policy, now_ns=1 if automatic else acc.CONFIRMATION_NS + 1, action=action) + assert output.action_receipt is not None assert not output.action_receipt.consumed assert (output.state.accepted is not None) == automatic diff --git a/openpilot/starpilot/speed_limits/tests/test_tesla_set_speed.py b/openpilot/starpilot/speed_limits/tests/test_tesla_set_speed.py index 35f87b2a51..2bcf731840 100644 --- a/openpilot/starpilot/speed_limits/tests/test_tesla_set_speed.py +++ b/openpilot/starpilot/speed_limits/tests/test_tesla_set_speed.py @@ -20,6 +20,7 @@ from opendbc.car.structs import car from opendbc.car.tesla.interface import CarInterface as TeslaInterface from opendbc.car.tesla.speed_sync import prepare, selected from opendbc.car.tesla.values import CAR as TESLA, TeslaFlags, TeslaSafetyFlags +from openpilot.common.test import require_value from openpilot.common.constants import CV from openpilot.selfdrive.car import card from openpilot.selfdrive.car.cruise import VCruiseHelper, slc_target_kph @@ -205,6 +206,8 @@ def test_composition_without_the_rule_ignores_the_rule_fields_and_keeps_the_cap( assert capped.override is None and capped.state.override is None and capped.status == 'accepted' ruled = comp.step(state, replace(plain, set_speed_rule=True)) assert ruled.ceiling is None and ruled.state.override is not None and ruled.status == 'accepted' + assert capped.coordinate is not None + assert ruled.coordinate is not None assert ruled.coordinate.cluster_target_mps == capped.coordinate.cluster_target_mps @@ -282,7 +285,7 @@ def test_default_policy_adopts_at_once_and_never_tracks_a_source(): assert (policy.automatic_adoption_ns, policy.source_switch_ns) == (0, 0) first = acc.step(acc.new_session('drive'), acc.Observation(acc.ObservationKind.VALID, candidate), authority, policy, now_ns=0) second = acc.step(first.state, acc.Observation(acc.ObservationKind.VALID, other), authority, policy, now_ns=1) - assert first.basis == second.basis == 'accepted' and second.state.accepted.candidate == other + assert first.basis == second.basis == 'accepted' and require_value(second.state.accepted).candidate == other assert second.state.received_source is None and second.state.switch_candidate is None for invalid in (replace(policy, automatic_adoption_ns=-1), replace(policy, source_switch_ns=True), replace(policy, source_switch_ns=acc.CONFIRMATION_NS + 1)): @@ -296,8 +299,10 @@ def test_automatic_countdown_never_consumes_plus_or_minus_and_late_accept_is_dec for automatic in (False, True): policy = acc.Policy(not automatic, not automatic, automatic_adoption_ns=acc.AUTOMATIC_ADOPTION_NS) pending = acc.step(acc.new_session('drive'), observation, authority, policy, now_ns=0) + assert pending.state.pending is not None action = acc.DriverAction('drive', 1, pending.state.pending.decision_id, acc.ActionKind.ACCEPT) output = acc.step(pending.state, observation, authority, policy, now_ns=1 if automatic else acc.CONFIRMATION_NS + 1, action=action) + assert output.action_receipt is not None assert not output.action_receipt.consumed assert output.state.accepted is None @@ -551,6 +556,7 @@ def test_alignment_waits_for_the_previous_command_and_newer_set_evidence(drive, limit(65) waiting = tick(runtime, sm, cp, .06) assert waiting.command is None and waiting.message.slcState.commandStatus == 'issued' + assert runtime.commanded_acceptance is not None assert runtime.commanded_acceptance.candidate.speed_mps == pytest.approx(55 * CV.MPH_TO_MS) if resolution != 'expired': set_kph = slc_target_kph(command.targetMps, False) if resolution == 'applied' else previous @@ -1023,6 +1029,7 @@ def test_card_writes_the_command_once_and_its_receipt_completes_the_runtime(driv done = tick(runtime, sm, cp, 3.05, cruise_event=receipt_event(owner, receipts[0])) assert done.message.slcState.commandStatus == 'applied' and done.command is None assert done.message.slcState.isLimitingMaxSet and not done.message.slcState.driverOverrideActive + assert runtime.state.override is not None assert runtime.state.override.applied_selected_mps == pytest.approx(25.) diff --git a/openpilot/starpilot/speed_limits/vision/producer.py b/openpilot/starpilot/speed_limits/vision/producer.py index 3007e00577..6c8f19298b 100644 --- a/openpilot/starpilot/speed_limits/vision/producer.py +++ b/openpilot/starpilot/speed_limits/vision/producer.py @@ -99,6 +99,8 @@ def _camera_buffer(client): def _convert_camera_buffer(info) -> tuple[np.ndarray, int, int] | None: + if cv2 is None: + return None buffer, eof_boot_ns, frame_id, stride, width, height, uv_offset = info # VisionBuf borrows client-owned shared memory. Copy before another receive # or reconnect; only the owned array is used for conversion and inference. diff --git a/openpilot/starpilot/speed_limits/vision/stop_signs.py b/openpilot/starpilot/speed_limits/vision/stop_signs.py index 6db8afe241..f9fce4283e 100644 --- a/openpilot/starpilot/speed_limits/vision/stop_signs.py +++ b/openpilot/starpilot/speed_limits/vision/stop_signs.py @@ -52,7 +52,7 @@ def decode_stop_signs(predictions, *, ratio, pad_width, pad_height, region_width boxes.append([x1 + origin_x, y1 + origin_y, x2 - x1, y2 - y1]) scores.append(float(predictions[0, 4, index])) ids.append(int(index)) - if not boxes: + if not boxes or cv2 is None: return () keep = np.asarray(cv2.dnn.NMSBoxes(boxes, scores, threshold, .4)).reshape(-1) retained = keep[:4] diff --git a/openpilot/starpilot/speed_limits/vision/tests/test_identity_native_lifecycle.py b/openpilot/starpilot/speed_limits/vision/tests/test_identity_native_lifecycle.py index b39357d71d..754b696f4f 100644 --- a/openpilot/starpilot/speed_limits/vision/tests/test_identity_native_lifecycle.py +++ b/openpilot/starpilot/speed_limits/vision/tests/test_identity_native_lifecycle.py @@ -10,6 +10,7 @@ from openpilot.starpilot.speed_limits.vision.tests import _identity_fixture as f class TestIdentityNativeLifecycle(unittest.TestCase): def setUp(self): from openpilot.starpilot.speed_limits.vision import speed_face + assert speed_face.cv2 is not None loader = patch.object(speed_face.cv2.dnn, "readNetFromONNX", side_effect=fixture.load) loader.start() self.addCleanup(loader.stop) @@ -25,6 +26,7 @@ class TestIdentityNativeLifecycle(unittest.TestCase): self.assertIsNone(result.speed) self.assertEqual(len(result.stops), 1) self.assertEqual(core.last_classifier_forward_count, 0) + assert core._stop_face_filter is not None self.assertTrue(core._stop_face_filter.last_rows) self.assertIsNone(core.net.rgb256) @@ -32,7 +34,9 @@ class TestIdentityNativeLifecycle(unittest.TestCase): before = len(fixture.LOADS) core = traffic_signs.TrafficSignModelCore(is_metric=False) self.assertEqual(fixture.LOADS[before:], ['joint', 'reader', 'aux']) + assert core._stop_face_filter is not None net = core._stop_face_filter.net + assert core._speed_face_filter is not None self.assertIs(net, core._speed_face_filter.net) core.set_speed_enabled(False) self.assertIsNone(core.classifier_net) @@ -40,17 +44,20 @@ class TestIdentityNativeLifecycle(unittest.TestCase): with patch.object(core, '_load_net', side_effect=RuntimeError('Synthetic reader refusal')), self.assertRaises(RuntimeError): core.set_speed_enabled(True) self.assertFalse(core.speed_enabled) + assert core._stop_face_filter is not None self.assertIs(core._stop_face_filter.net, net) self.assertIsNone(core.classifier_net) before = len(fixture.LOADS) core.set_speed_enabled(True) self.assertEqual(fixture.LOADS[before:], ['joint', 'reader']) + assert core._speed_face_filter is not None self.assertIs(core._speed_face_filter.net, net) def test_nonfinite_STOP_head_invalidates_entire_current_and_clears_refs(self): core = traffic_signs.TrafficSignModelCore(is_metric=False, speed_enabled=False) core.net.net.stop_hits = True core.published_speed_limit_mph = 55 + assert core._stop_face_filter is not None core._stop_face_filter.net.logit = float('nan') with self.assertRaises(ValueError): core.infer_signs(np.zeros((760, 1344, 3), np.uint8)) diff --git a/openpilot/starpilot/speed_limits/vision/tests/test_material_validation.py b/openpilot/starpilot/speed_limits/vision/tests/test_material_validation.py index 57f172954d..fd3e3e0c75 100644 --- a/openpilot/starpilot/speed_limits/vision/tests/test_material_validation.py +++ b/openpilot/starpilot/speed_limits/vision/tests/test_material_validation.py @@ -19,6 +19,7 @@ class TestMaterialValidation(unittest.TestCase): hsv[:] = (hue, 255, 255) hsv[10:90, 15:65] = (0, 0, 255) hsv[40:50, 25:55] = 0 + assert model.cv2 is not None return model.cv2.cvtColor(hsv, model.cv2.COLOR_HSV2BGR) def test_plain_panel_and_each_color_veto(self): @@ -61,6 +62,7 @@ class TestMaterialValidation(unittest.TestCase): for image, expected in ((np.zeros((100, 80, 3), np.uint8), []), (self.panel(25), [('ge', 12), ('le', 45)])): operations.clear() + assert model.cv2 is not None hsv = model.cv2.cvtColor(image, model.cv2.COLOR_BGR2HSV) with patch.object(model.cv2, 'cvtColor', return_value=HSV(hsv)): self.assertFalse(self.validate(image)) diff --git a/openpilot/starpilot/speed_limits/vision/tests/test_speed_warning_context.py b/openpilot/starpilot/speed_limits/vision/tests/test_speed_warning_context.py index f499d0d3c9..880ed80cec 100644 --- a/openpilot/starpilot/speed_limits/vision/tests/test_speed_warning_context.py +++ b/openpilot/starpilot/speed_limits/vision/tests/test_speed_warning_context.py @@ -22,6 +22,7 @@ class TestSpeedWarningContext(unittest.TestCase): def diamond(self, image, points=None): points = points or [[128, 40], [216, 128], [128, 216], [40, 128]] + assert cv2 is not None cv2.fillConvexPoly(image, np.asarray(points, np.int32), (255, 255, 0)) return image @@ -34,9 +35,13 @@ class TestSpeedWarningContext(unittest.TestCase): def test_circle_ellipse_rectangle_and_school_header_fall_back(self): circle, ellipse, rectangle, header = [self.image() for _ in range(4)] + assert cv2 is not None cv2.circle(circle, (128, 128), 85, (255, 255, 0), -1) + assert cv2 is not None cv2.ellipse(ellipse, (128, 128), (95, 60), 20, 0, 360, (255, 255, 0), -1) + assert cv2 is not None cv2.rectangle(rectangle, (40, 40), (216, 216), (255, 255, 0), -1) + assert cv2 is not None cv2.rectangle(header, (70, 30), (180, 65), (255, 255, 0), -1) for image in [circle, ellipse, rectangle, header]: with self.subTest(kind=id(image)): @@ -94,10 +99,14 @@ class TestSpeedWarningContext(unittest.TestCase): def test_concave_outline_cannot_borrow_its_convex_hull_shape(self): contour = np.asarray([[128, 40], [216, 128], [145, 128], [128, 216], [40, 128], [110, 128]], np.int32)[:, None] + assert cv2 is not None hull = cv2.convexHull(contour) + assert cv2 is not None quad = cv2.approxPolyDP(hull, .02 * cv2.arcLength(hull, True), True) self.assertEqual(len(quad), 4) + assert cv2 is not None self.assertTrue(cv2.isContourConvex(quad)) + assert cv2 is not None self.assertFalse(cv2.isContourConvex(contour)) with mock.patch.object(cv2, 'findContours', return_value=([contour], None)): self.assertIsNone(speed_face.warning_context_box(self.blob(self.image()), [100, 100, 160, 160])) diff --git a/openpilot/starpilot/speed_limits/vision/tests/test_stop_projection.py b/openpilot/starpilot/speed_limits/vision/tests/test_stop_projection.py index 1593288e99..a6a301177f 100644 --- a/openpilot/starpilot/speed_limits/vision/tests/test_stop_projection.py +++ b/openpilot/starpilot/speed_limits/vision/tests/test_stop_projection.py @@ -82,7 +82,9 @@ class TestStopProjection(unittest.TestCase): wrapped.setInput(blob) captured = wrapped.rgb256 blob.fill(1) + assert captured is not None self.assertEqual(float(captured.max()), 0) + assert captured is not None self.assertFalse(captured.flags.writeable) wrapped.forward_stops() wrapped.setInput(blob) @@ -93,7 +95,7 @@ class TestStopProjection(unittest.TestCase): self.assertEqual(self.loads, ['traffic_signs_us_stop_detector.onnx']) self.assertIsNone(core.classifier_net) self.assertIsNone(core._speed_face_filter) - self.assertIsNotNone(core._stop_face_filter.net) + assert core._stop_face_filter.net is not None def test_mode_changes_validate_and_share_one_identity_network(self): core = self.core(True) diff --git a/openpilot/starpilot/speed_limits/vision/tests/test_stop_signs.py b/openpilot/starpilot/speed_limits/vision/tests/test_stop_signs.py index 92160da9a2..9bd7d9a700 100644 --- a/openpilot/starpilot/speed_limits/vision/tests/test_stop_signs.py +++ b/openpilot/starpilot/speed_limits/vision/tests/test_stop_signs.py @@ -5,6 +5,7 @@ from unittest.mock import patch import numpy as np +from openpilot.common.test import require_value from openpilot.starpilot.speed_limits.vision.traffic_signs import TrafficSignModelCore as VisionModelCore from openpilot.starpilot.speed_limits.vision.speed_face import StopFaceVerifier from openpilot.starpilot.speed_limits.vision.stop_signs import StopDetection, SignDetectorOutputs, decode_stop_signs @@ -119,7 +120,7 @@ class TestStopSigns(unittest.TestCase): frame = np.zeros((760, 1344, 3), np.uint8) with ( patch.object(core, '_classify_speed_limit_from_model', side_effect=AssertionError('Unused speed classifier')), - patch.object(core._stop_face_filter.net, 'forward', side_effect=AssertionError('Unexpected identity work')), + patch.object(require_value(core._stop_face_filter).net, 'forward', side_effect=AssertionError('Unexpected identity work')), ): self.assertIsNone(core.observe(frame, now=1.0)) self.assertIsNone(core.classifier_net) @@ -139,7 +140,7 @@ class TestStopSigns(unittest.TestCase): self.assertEqual(core.last_published_support_at, 0) self.assertIsNone(core.observe(np.zeros((760, 1344, 3), np.uint8), now=2.0)) core.set_speed_enabled(True) - self.assertIsNotNone(core.classifier_net) + assert core.classifier_net is not None self.assertEqual(core.published_speed_limit_mph, 0) self.assertEqual(core.history, deque()) diff --git a/openpilot/starpilot/speed_limits/vision/tests/test_vision.py b/openpilot/starpilot/speed_limits/vision/tests/test_vision.py index 62253191e0..a6e95da348 100644 --- a/openpilot/starpilot/speed_limits/vision/tests/test_vision.py +++ b/openpilot/starpilot/speed_limits/vision/tests/test_vision.py @@ -137,6 +137,7 @@ class TestVision(unittest.TestCase): 'now_boot_ns': 5_050_000_000, 'car_fingerprint': 'IONIQ6', 'drive_session': 'drive-a'} valid = vision_observation(decoded, **kw) self.assertIs(valid.kind, ObservationKind.VALID) + assert valid.candidate is not None self.assertAlmostEqual(valid.candidate.speed_mps, 24.5872, places=4) self.assertIs(vision_observation(decoded, receipt_mono_ns=1_020_000_000, now_mono_ns=1_030_000_000, now_boot_ns=7_000_000_001, car_fingerprint='IONIQ6', @@ -443,12 +444,17 @@ class TestVision(unittest.TestCase): self.assertTrue(accepted.message.slcState.hasAccepted) self.assertTrue(accepted.message.slcState.hasCeiling) self.assertEqual(accepted.message.slcState.sourceProducerSessionId, 'camera-a') + assert accepted.result.ceiling is not None self.assertAlmostEqual(accepted.result.ceiling.speed_mps, evidence.speedMps) sm.advance(2_300_000_000) expired = confirmed.step(sm, cp, now_ns=2_300_000_000, now_boot_ns=6_300_000_000) self.assertTrue(expired.message.slcState.hasCeiling) + assert expired.result.acceptance is not None self.assertEqual(expired.result.acceptance.basis, 'stale') + assert expired.result.acceptance is not None self.assertAlmostEqual(expired.result.acceptance.control_target_mps, evidence.speedMps) + assert accepted.result.acceptance is not None + assert expired.result.acceptance is not None self.assertEqual(expired.result.acceptance.state.accepted, accepted.result.acceptance.state.accepted) self.assertIs(confirmed.vision_diagnostic.kind, ObservationKind.STALE) @@ -472,12 +478,18 @@ class TestVision(unittest.TestCase): chosen.message.slcState.presentationId, 'accept')) self.assertTrue(chosen_accepted.message.slcState.hasAccepted) self.assertTrue(chosen_accepted.message.slcState.hasCeiling) + assert chosen_accepted.result.ceiling is not None self.assertAlmostEqual(chosen_accepted.result.ceiling.speed_mps, dashboard.speedMps) dashboard.status = 'unknown' sm.advance(2_350_000_000) missing = fallback.step(sm, cp, now_ns=2_350_000_000, now_boot_ns=6_350_000_000) self.assertTrue(missing.message.slcState.hasCeiling) + assert missing.result.acceptance is not None self.assertEqual(missing.result.acceptance.basis, 'unknown') + assert missing.result.acceptance is not None assert missing.result.acceptance.control_target_mps is not None + assert missing.result.acceptance is not None self.assertAlmostEqual(missing.result.acceptance.control_target_mps, dashboard.speedMps) + assert chosen_accepted.result.acceptance is not None + assert missing.result.acceptance is not None self.assertEqual(missing.result.acceptance.state.accepted, chosen_accepted.result.acceptance.state.accepted) diff --git a/openpilot/starpilot/spot_monitor/tests/test_inference.py b/openpilot/starpilot/spot_monitor/tests/test_inference.py index 795340c54e..45d93bc57f 100644 --- a/openpilot/starpilot/spot_monitor/tests/test_inference.py +++ b/openpilot/starpilot/spot_monitor/tests/test_inference.py @@ -108,6 +108,7 @@ def test_exact_asset_cpu_mask_crop_class_one_and_loaded_bytes_pinned(tiny_model, assert model.load() assert cv2.threads == 1 assert model.loaded_sha256 == inference.MODEL_SHA256 + assert cv2.dnn.loaded is not None assert cv2.dnn.loaded.tobytes() == tiny_model.read_bytes() assert (net.backend, net.target) == (cv2.dnn.DNN_BACKEND_OPENCV, cv2.dnn.DNN_TARGET_CPU) annotation = decode_annotation(b'{"version":1,"width":32,"height":32,"poly_left":[[4,4],[20,4],[4,20]],"poly_right":[]}') @@ -117,7 +118,9 @@ def test_exact_asset_cpu_mask_crop_class_one_and_loaded_bytes_pinned(tiny_model, assert cv2.mask is not None assert cv2.mask[2, 2] == 255 assert cv2.mask[-2, -2] == 0 + assert net.blob is not None assert net.blob.shape == (1, 3, 352, 352) + assert net.blob is not None assert net.blob.dtype == np.float32 assert net.blob.max() == 1.0 and net.blob.min() == 0.0 tiny_model.write_bytes(b"small tampered ONNX fixture") diff --git a/openpilot/starpilot/system/starport/apk_identity.py b/openpilot/starpilot/system/starport/apk_identity.py index 2a37e503c3..a1a42099a5 100644 --- a/openpilot/starpilot/system/starport/apk_identity.py +++ b/openpilot/starpilot/system/starport/apk_identity.py @@ -174,6 +174,7 @@ def extract_identity(path: Path, *, root_sha256: str = GOOGLE_ROOT_SHA256, now: """Return ({file name: PEM bytes}, metadata) for the identity in an Android Auto APK/XAPK/APKM.""" from cryptography import x509 from cryptography.hazmat.primitives import padding, serialization + from cryptography.hazmat.primitives.asymmetric import dh, dsa, ec, rsa from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes progress("reading") @@ -208,7 +209,11 @@ def extract_identity(path: Path, *, root_sha256: str = GOOGLE_ROOT_SHA256, now: progress("decrypting") for leaf_pem in leaves: leaf = certs[leaf_pem] - wanted = leaf.public_key().public_numbers() + public_types = (rsa.RSAPublicKey, dsa.DSAPublicKey, ec.EllipticCurvePublicKey, dh.DHPublicKey) + leaf_key = leaf.public_key() + if not isinstance(leaf_key, public_types): + continue + wanted = leaf_key.public_numbers() for mask in masks: material = derive_aes_material(leaf_pem, root_pem, mask) for blob in blobs: @@ -219,7 +224,8 @@ def extract_identity(path: Path, *, root_sha256: str = GOOGLE_ROOT_SHA256, now: key = serialization.load_pem_private_key(plain, password=None) except Exception: continue - if key.public_key().public_numbers() != wanted: + public = key.public_key() + if not isinstance(public, public_types) or public.public_numbers() != wanted: continue progress("verifying") now = now or datetime.now(UTC) diff --git a/openpilot/starpilot/system/starport/bluetooth_bridge.py b/openpilot/starpilot/system/starport/bluetooth_bridge.py index 1e6a1006a0..1b6ba85a28 100644 --- a/openpilot/starpilot/system/starport/bluetooth_bridge.py +++ b/openpilot/starpilot/system/starport/bluetooth_bridge.py @@ -790,8 +790,11 @@ class SharedBluetoothOwner(BluetoothOwner): threading.Thread(target=self._accept_worker, args=(window, lambda *_: None, lambda: None), daemon=True).start() threading.Thread(target=self._watch_pair, args=(window,), daemon=True).start() elif operation == 'cancel_pair': + if window is None: + raise BluetoothRejected('Pairing prompt changed') window.cancel() - elif operation == 'pairing_response' and (prompt_id is None or type(accepted) is not bool or not window.respond(session, prompt_id, accepted, value)): + elif operation == 'pairing_response' and (window is None or prompt_id is None or type(accepted) is not bool or + not window.respond(session, prompt_id, accepted, value)): raise BluetoothRejected('Pairing prompt changed') result = self.snapshot(session=session) result['windowPaired'] = self.window_paired diff --git a/openpilot/starpilot/system/starport/bugsink_report.py b/openpilot/starpilot/system/starport/bugsink_report.py index 71a7659d19..d7ca4e89ea 100644 --- a/openpilot/starpilot/system/starport/bugsink_report.py +++ b/openpilot/starpilot/system/starport/bugsink_report.py @@ -210,7 +210,8 @@ def session_sdp(events: list[dict]) -> dict: def session_setup(events: list[dict]) -> dict: """The setup type and profile the owner chose, as recorded when the session started.""" start = next((event for event in events if event["event"] == "session_start"), {}) - setup = start.get("setup") if isinstance(start.get("setup"), dict) else {} + setup = start.get("setup") + setup = setup if isinstance(setup, dict) else {} kind = setup.get("type") return {key: value for key, value in ( ("type", kind if kind in SETUP_TYPES else None), @@ -282,7 +283,8 @@ def session_strategy(events: list[dict], setup: dict) -> dict: return {} ready = next((event for event in reversed(events) if event["event"] == "video_setup"), {}) reply = next((event for event in events if event["event"] == "bootstrap_version_reply"), {}) - mode = ready.get("mode") if isinstance(ready.get("mode"), dict) else {} + mode = ready.get("mode") + mode = mode if isinstance(mode, dict) else {} # Only a wireless bootstrap has a version reply; the modern one is logged, the standard one is its absence. style = reply.get("style") or ("standard" if any(event["event"] == "bootstrap_start_response" for event in events) else None) strategy = {"profile": setup.get("profile"), "window_offered": ready.get("window"), "window_used": ready.get("used_window"), diff --git a/openpilot/starpilot/system/starport/car_interface.py b/openpilot/starpilot/system/starport/car_interface.py index c85f881685..e35d4c28f0 100644 --- a/openpilot/starpilot/system/starport/car_interface.py +++ b/openpilot/starpilot/system/starport/car_interface.py @@ -304,10 +304,16 @@ class DedicatedLease: self.lease = self.iface = None self._ensure() + def _acquire_lease(self, credentials, cancelled, **kwargs): + lease = self.lease + if lease is None: + raise DedicatedUnavailable("Android Auto Wi-Fi lease unavailable") + return lease.acquire(credentials, cancelled=cancelled, **kwargs) + def acquire(self, credentials, cancelled: Callable[[], bool] = lambda: False, **kwargs): self._ensure() try: - local_ip = self.lease.acquire(credentials, cancelled=cancelled, **kwargs) + local_ip = self._acquire_lease(credentials, cancelled, **kwargs) except NetworkError as error: if self.legacy or cancelled(): raise @@ -322,7 +328,7 @@ class DedicatedLease: self.log("wifi_dedicated_reopen", error=str(error) or type(error).__name__) self._reopen() try: - local_ip = self.lease.acquire(credentials, cancelled=cancelled, **kwargs) + local_ip = self._acquire_lease(credentials, cancelled, **kwargs) except NetworkError as retry_error: if self.legacy or cancelled() or isinstance(retry_error, JoinTimeout): raise @@ -335,7 +341,7 @@ class DedicatedLease: # aa0 itself failed; finish this same join on wlan0 rather than report a failure to the car. self._fall_back(error) self._ensure() - local_ip = self.lease.acquire(credentials, cancelled=cancelled, **kwargs) + local_ip = self._acquire_lease(credentials, cancelled, **kwargs) self.aa0_failed = not isinstance(error, DedicatedUnavailable) return local_ip if not self.legacy: diff --git a/openpilot/starpilot/system/starport/projection_onroad.py b/openpilot/starpilot/system/starport/projection_onroad.py index 46c8bf5767..eed04d5030 100644 --- a/openpilot/starpilot/system/starport/projection_onroad.py +++ b/openpilot/starpilot/system/starport/projection_onroad.py @@ -221,8 +221,8 @@ class ProjectionOnroad: from openpilot.starpilot.ui.onroad_state import OnroadInput def emit_slc(request) -> None: self.slc_action(request) - self._slc_input = OnroadInput(emit_slc, native.profile.LARGE, slop=30) - self.onroad.pressed_action = lambda: self._slc_input.pressed_action + slc_input = self._slc_input = OnroadInput(emit_slc, native.profile.LARGE, slop=30) + self.onroad.pressed_action = lambda: slc_input.pressed_action self.pip = None self._pip_saved = None self._pip_read_ns = None @@ -377,7 +377,7 @@ class ProjectionOnroad: placed = self._map_placement() if self.map is not None and placed is None: self._release_map() - if self.map is None or placed is None or not self.native.ui_state.started: + if self.map is None or self.map_feed is None or placed is None or not self.native.ui_state.started: return self._map_lease.touch() document = self.favorites.document if self.favorites is not None else None @@ -398,6 +398,8 @@ class ProjectionOnroad: def _pip_layer(self, rect, state, *, submit=None): """Shared camera crops, with Android Auto's own blind-spot trigger and placements.""" + if self.pip is None: + return native = self.native now_ns = time.monotonic_ns() if self._pip_read_ns is None or not 0 <= now_ns - self._pip_read_ns < 1_000_000_000: diff --git a/openpilot/starpilot/system/starport/supervisor.py b/openpilot/starpilot/system/starport/supervisor.py index 4da7980227..951f4e4eaf 100644 --- a/openpilot/starpilot/system/starport/supervisor.py +++ b/openpilot/starpilot/system/starport/supervisor.py @@ -1622,7 +1622,7 @@ class Supervisor: adapter=adapter, unofficial=unofficial) if outcome: self.log("ladder_failed", outcome=outcome, rung=strategy.rung, next=self._ladder.strategy(address, base_modern, unofficial).rung, - version_major=boot.version_major, reason="rejected_reply" if rejected else "timeout", why=reason) + version_major=boot.version_major if boot is not None else 0, reason="rejected_reply" if rejected else "timeout", why=reason) elif boot is not None and isinstance(error, BootstrapTimeout) and error.stage == "wifi_start" and boot.only_not_ready(): self.log("ladder_not_ready", rung=strategy.rung, refusals=len(boot.refusals)) if source == "cache" and not self._stop.is_set() and drops_cached_channel(self._status["last_stage"], error): @@ -1685,7 +1685,8 @@ class Supervisor: if _stray_link(error): raise StrayLinkError(f"Bluetooth link to the car is stuck: {error}") from error # retrying cannot clear it last_error = error - self.log("sdp_retry", error=str(error), settle=settle, **({"record_hex": error.raw.hex()[:400]} if getattr(error, "raw", b"") else {})) + raw = error.raw if isinstance(error, sdp.SdpError) else b"" + self.log("sdp_retry", error=str(error), settle=settle, **({"record_hex": raw.hex()[:400]} if raw else {})) self._wait(0.35) raise RuntimeError(f"Could not find the car's Android Auto service: {last_error}") @@ -2108,8 +2109,9 @@ class Supervisor: self._record_fix_outcome(session, car_ended) if session.audio is not None: session.audio.close() - if getattr(session, "nav", None) is not None: - session.nav.close() + nav = getattr(session, "nav", None) + if nav is not None: + nav.close() watch.stop() if radio is not None: radio.stop() @@ -2279,8 +2281,9 @@ class Supervisor: if keyframe: sizes["keyframe"] = len(data) last_frame = frame - if source.view == "car": - source.source.mark_sent(frame.captured_ns) + mark_sent = getattr(source.source, "mark_sent", None) + if source.view == "car" and mark_sent is not None: + mark_sent(frame.captured_ns) sent_at = time.monotonic() ages.append(sent_at - frame.captured_ns / 1e9) sent_times.append(sent_at) diff --git a/openpilot/starpilot/system/starport/system_snapshot.py b/openpilot/starpilot/system/starport/system_snapshot.py index f558ef9059..2f795724ac 100644 --- a/openpilot/starpilot/system/starport/system_snapshot.py +++ b/openpilot/starpilot/system/starport/system_snapshot.py @@ -139,7 +139,8 @@ def collect(since: float, deadline: float = DEADLINE_SECONDS, *, run: Callable | except ProcessLookupError: pass process.wait(timeout=1.0) - process.stdout.close() + if process.stdout is not None: + process.stdout.close() entry["exit"] = process.returncode entry["seconds"] = round(time.monotonic() - started, 2) if received[name] > OUTPUT_LIMIT: diff --git a/openpilot/starpilot/system/starport/test_configuration_authority.py b/openpilot/starpilot/system/starport/test_configuration_authority.py index 111153c15b..4aa28f7d67 100644 --- a/openpilot/starpilot/system/starport/test_configuration_authority.py +++ b/openpilot/starpilot/system/starport/test_configuration_authority.py @@ -34,6 +34,7 @@ def test_configuration_park_authority_is_fresh_and_releases_physical_observer(tm messages.valid['carState'] = True assert authority.configuration_allowed() physical = authority.physical + assert physical is not None authority.close() assert physical.closed and physical.messages is None assert authority.physical is None diff --git a/openpilot/starpilot/system/starport/tests/fake_head_unit.py b/openpilot/starpilot/system/starport/tests/fake_head_unit.py index d2bd657b42..0b58a9ad4f 100644 --- a/openpilot/starpilot/system/starport/tests/fake_head_unit.py +++ b/openpilot/starpilot/system/starport/tests/fake_head_unit.py @@ -154,11 +154,13 @@ class FakeHeadUnit: if encrypted: self.tls.write(data) data = self.outgoing.read() + assert self.sock is not None self.sock.sendall(struct.pack(">BBH", channel, flags, len(data)) + data) def _read_exact(self, size: int) -> bytes: data = bytearray() while len(data) < size: + assert self.sock is not None chunk = self.sock.recv(size - len(data)) if not chunk: raise EOFError("phone closed") diff --git a/openpilot/starpilot/system/starport/tests/test_apk_identity.py b/openpilot/starpilot/system/starport/tests/test_apk_identity.py index b642d677dc..d09d62b9e7 100644 --- a/openpilot/starpilot/system/starport/tests/test_apk_identity.py +++ b/openpilot/starpilot/system/starport/tests/test_apk_identity.py @@ -103,8 +103,12 @@ def test_extracts_from_apk_and_xapk(tmp_path, ident): for path in (make_apk(tmp_path, ident), make_xapk(tmp_path, ident)): files, meta = apk_identity.extract_identity(path, root_sha256=ident["root_sha"], progress=stages.append) assert files["phone-cert.pem"] == ident["cert"] and files["root-cert.pem"] == ident["root"] + from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.serialization import load_pem_private_key - assert load_pem_private_key(files["phone-key.pem"], None).private_numbers() == load_pem_private_key(ident["key"], None).private_numbers() + actual = load_pem_private_key(files["phone-key.pem"], None) + expected = load_pem_private_key(ident["key"], None) + assert isinstance(actual, rsa.RSAPrivateKey) and isinstance(expected, rsa.RSAPrivateKey) + assert actual.private_numbers() == expected.private_numbers() assert meta["key_matches"] and meta["root_sha256"] == ident["root_sha"] assert stages[:4] == ["reading", "searching", "decrypting", "verifying"] @@ -183,6 +187,7 @@ def test_rejections_carry_codes_for_galaxy(tmp_path, ident): job = apk_identity.ImportJob(work_dir=tmp_path / "work", identity_dir=tmp_path / "identity") job.start(path=junk) + assert job.thread is not None job.thread.join(30) assert job.status()["state"] == "failed" and job.status()["code"] == "NOT_PACKAGE" @@ -231,6 +236,7 @@ def test_import_stops_when_master_switch_is_disabled(monkeypatch, tmp_path): monkeypatch.setattr(apk_identity, "install_identity", unexpected_install) job = apk_identity.ImportJob(work_dir=tmp_path) job.start(path=source, enabled=lambda: enabled["value"]) + assert job.thread is not None job.thread.join(timeout=5) assert not job.busy() assert "disabled" in job.status()["error"] @@ -244,6 +250,7 @@ def test_import_job_labels_metadata_free_package_with_offered_version(tmp_path, installed.clear() job = apk_identity.ImportJob(work_dir=tmp_path, root_sha256=ident["root_sha"]) job.start(path=path, app_version=hint) + assert job.thread is not None job.thread.join(timeout=5) assert job.status()["state"] == "done" and installed.get("app_version") == expected diff --git a/openpilot/starpilot/system/starport/tests/test_bugsink_report.py b/openpilot/starpilot/system/starport/tests/test_bugsink_report.py index f46e033101..7dfe9bd2aa 100644 --- a/openpilot/starpilot/system/starport/tests/test_bugsink_report.py +++ b/openpilot/starpilot/system/starport/tests/test_bugsink_report.py @@ -324,9 +324,9 @@ def test_supervisor_records_build_at_session_start(monkeypatch): sup.config = {"connection": "wired", "receiver_name": ""} sup._stop = threading.Event() sup._stop.set() - sup._set = lambda **_: None # ty: ignore[invalid-assignment] # test double + sup._set = lambda **_: None sup._count_dedicated = lambda _: None # ty: ignore[invalid-assignment] # test double - sup._release_phone = lambda: None # ty: ignore[invalid-assignment] # test double + sup._release_phone = lambda: None sup._run(1) assert records[0]["software"] == {"repo": "unknown", "commit": "session-build", "branch": "session-branch"} diff --git a/openpilot/starpilot/system/starport/tests/test_car_interface.py b/openpilot/starpilot/system/starport/tests/test_car_interface.py index bea2a1d5f8..2b9a0fadc8 100644 --- a/openpilot/starpilot/system/starport/tests/test_car_interface.py +++ b/openpilot/starpilot/system/starport/tests/test_car_interface.py @@ -432,6 +432,7 @@ def test_interface_lease_ready_heartbeat_and_close(monkeypatch): child = iface.child time.sleep(0.3) iface.close() + assert child is not None assert child.returncode == 0 diff --git a/openpilot/starpilot/system/starport/tests/test_diagnostics_logging.py b/openpilot/starpilot/system/starport/tests/test_diagnostics_logging.py index a1b4fecaac..92030e01cf 100644 --- a/openpilot/starpilot/system/starport/tests/test_diagnostics_logging.py +++ b/openpilot/starpilot/system/starport/tests/test_diagnostics_logging.py @@ -456,8 +456,10 @@ def test_session_log_full_queue_close_then_reopen_retires_old_writer(tmp_path, m log.close() finally: release.set() + assert old_writer is not None old_writer.join(timeout=2) log.close() + assert old_writer is not None assert not old_writer.is_alive() assert all(handle.closed for handle in handles) files = sorted(tmp_path.glob("session-*.jsonl")) diff --git a/openpilot/starpilot/system/starport/tests/test_media_controls.py b/openpilot/starpilot/system/starport/tests/test_media_controls.py index 3bc4507954..24449a1c56 100644 --- a/openpilot/starpilot/system/starport/tests/test_media_controls.py +++ b/openpilot/starpilot/system/starport/tests/test_media_controls.py @@ -41,7 +41,7 @@ def session_with_input(focused): session.audio, session.mode, session.input_channel, session.input_events = None, None, 3, 0 session.touch, session.focused, session.keys = None, focused, KeyTracker() session.touch_events, session.events, session.actions = [], [], [] # ty: ignore[invalid-assignment] # test double - session.event = lambda name, **values: session.events.append((name, values)) # ty: ignore[invalid-assignment] # test double + session.event = lambda name, **values: session.events.append((name, values)) session.media_control = session.actions.append return session diff --git a/openpilot/starpilot/system/starport/tests/test_nav_status.py b/openpilot/starpilot/system/starport/tests/test_nav_status.py index 1aac1af378..5e5aa6139e 100644 --- a/openpilot/starpilot/system/starport/tests/test_nav_status.py +++ b/openpilot/starpilot/system/starport/tests/test_nav_status.py @@ -182,7 +182,9 @@ def test_image_head_units_get_the_turn_arrow_at_their_size(): feed.value = GUIDING tick(stream, now) turn = parse_fields(next(body for _, kind, body in session.sent if kind == ns.NAV_TURN)) - assert turn[4][0].startswith(b'\x89PNG') + image = turn[4][0] + assert isinstance(image, bytes) + assert image.startswith(b'\x89PNG') def test_enum_head_units_get_no_image(nav): diff --git a/openpilot/starpilot/system/starport/tests/test_phone_window.py b/openpilot/starpilot/system/starport/tests/test_phone_window.py index 188945efb6..ce39941504 100644 --- a/openpilot/starpilot/system/starport/tests/test_phone_window.py +++ b/openpilot/starpilot/system/starport/tests/test_phone_window.py @@ -63,6 +63,7 @@ class PhoneWindowTest(unittest.TestCase): self.assertEqual(prompt['address'], '11:22:33:44:55:66') self.assertTrue(prompt['prompt']['displayOnly'], 'the code is shown, not waited on') FakeWindowBlueZ.bonded.set() + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(2)) final = self.owner.phone_window('status', SESSION) assert final is not None @@ -115,7 +116,9 @@ class PhoneWindowTest(unittest.TestCase): self.assertIsNone(self.owner.phone_window('status', other)) self.assertIsNone(self.owner.phone_window('pairing_response', other, prompt_id=prompt['prompt']['id'], accepted=True)) self.owner.phone_window('cancel_pair', SESSION) + assert self.owner.pairing is not None self.assertTrue(self.owner.pairing.done.wait(2)) + assert self.owner.pairing is not None self.assertNotEqual(self.owner.pairing.state, 'paired') def test_ending_projection_closes_the_window_before_the_lease_restores_visibility(self): @@ -124,6 +127,7 @@ class PhoneWindowTest(unittest.TestCase): window = self.owner.pairing self.assertIsInstance(window, OpenPairingSession) self.owner.release_phone_role(self.lease) # ty: ignore[invalid-argument-type] # test double + assert window is not None self.assertTrue(window.done.is_set()) self.assertEqual(FakeWindowBlueZ.instances[-1].visibility[-1], ('/org/bluez/hci0', True, False)) self.assertFalse(self.owner.journal_path.exists()) diff --git a/openpilot/starpilot/system/starport/tests/test_projection_layout_runtime.py b/openpilot/starpilot/system/starport/tests/test_projection_layout_runtime.py index c37967c3b4..f9a5c84495 100644 --- a/openpilot/starpilot/system/starport/tests/test_projection_layout_runtime.py +++ b/openpilot/starpilot/system/starport/tests/test_projection_layout_runtime.py @@ -179,6 +179,7 @@ class TestProjectionLayoutRuntime(unittest.TestCase): self.assertIsNone(watcher.take(), 'each save is handed over once') finally: watcher.close() + assert watcher._thread is not None self.assertFalse(watcher._thread.is_alive()) def test_take_never_touches_files(self): diff --git a/openpilot/starpilot/system/starport/tests/test_projection_map.py b/openpilot/starpilot/system/starport/tests/test_projection_map.py index 33a43f737b..ef4c427128 100644 --- a/openpilot/starpilot/system/starport/tests/test_projection_map.py +++ b/openpilot/starpilot/system/starport/tests/test_projection_map.py @@ -74,19 +74,26 @@ class TestProjectionMap(unittest.TestCase): layout = self.layout(enabled=True, x=100, y=200, width=640, height=480, opacity=45) view = projection.ProjectionOnroad(dependencies=native, viewport=(2880, 1080), customization=layout) self.assertIsInstance(view.map, FakeMap) + assert view.map is not None self.assertIs(view.map.fonts, view.fonts) self.assertEqual(view.onroad.map_layer, view._map_layer) view.prepare() + assert view.map is not None self.assertEqual(view.map.prepared, [], "nothing to prepare while offroad") native.ui_state.started = True view.prepare() + assert view.map is not None self.assertEqual(view.map.prepared, [("map input", 640, 480)]) + assert view.map_feed is not None self.assertEqual(view.map_feed.reads, [native.ui_state.sm]) + assert view.map_feed is not None self.assertEqual(view.map_feed.destinations, [None], "no favorites: the feed keeps navigation's own name") view._map_layer(None, None) + assert view.map is not None self.assertEqual(view.map.drawn, [((100, 200, 640, 480), 0.45)]) overlay = view.map view.close() + assert overlay is not None self.assertTrue(overlay.closed) def test_older_dependencies_without_a_map_still_work(self): @@ -121,6 +128,7 @@ class TestProjectionMap(unittest.TestCase): off["widgets"]["nav_map"]["enabled"] = False view.apply_layout(off) view.prepare() + assert overlay is not None self.assertTrue(overlay.closed) self.assertIsNone(view.map) self.assertIsNone(view.onroad.map_layer) diff --git a/openpilot/starpilot/system/starport/tests/test_starport.py b/openpilot/starpilot/system/starport/tests/test_starport.py index fd52e8f85f..53b2be9f85 100644 --- a/openpilot/starpilot/system/starport/tests/test_starport.py +++ b/openpilot/starpilot/system/starport/tests/test_starport.py @@ -1362,14 +1362,14 @@ def test_supervisor_retries_wifi_recovery_while_idle(monkeypatch): monkeypatch.setattr(network, "rejoin_interrupted", lambda log: True) sup = supervisor.Supervisor.__new__(supervisor.Supervisor) sup.log, sup._wifi_recover_at = (lambda *a, **k: None), 0.0 # ty: ignore[invalid-assignment] # test double - sup._session_alive = lambda: False # ty: ignore[invalid-assignment] # test double + sup._session_alive = lambda: False sup.recover_wifi(100) sup.recover_wifi(110) # waits before retrying sup.recover_wifi(100 + supervisor.WIFI_RECOVER_RETRY_S) sup.recover_wifi(1000) # done assert len(calls) == 2 sup._wifi_recover_at = 0.0 - sup._session_alive = lambda: True # ty: ignore[invalid-assignment] # test double + sup._session_alive = lambda: True sup.recover_wifi(2000) # never while a session owns wlan0 assert len(calls) == 2 diff --git a/openpilot/starpilot/system/starport/tests/test_unacked_video.py b/openpilot/starpilot/system/starport/tests/test_unacked_video.py index d8476c0baa..160a59f8c6 100644 --- a/openpilot/starpilot/system/starport/tests/test_unacked_video.py +++ b/openpilot/starpilot/system/starport/tests/test_unacked_video.py @@ -200,6 +200,7 @@ def test_the_owner_toggle_works_on_h264_without_any_fix(identity): session.authenticate() session.start("StarPilot", "comma.ai") pump_until(session, lambda: session.focused) + assert session.mode is not None assert session.mode.codec != CODEC_H265 count = session.window * 3 assert send_frames(hu, session, count) == count diff --git a/openpilot/starpilot/system/starport/view.py b/openpilot/starpilot/system/starport/view.py index d01c788517..683d6ab44f 100644 --- a/openpilot/starpilot/system/starport/view.py +++ b/openpilot/starpilot/system/starport/view.py @@ -90,7 +90,7 @@ class ViewSource: self.process = subprocess.Popen(self.renderer_command, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, close_fds=True) finally: - if output is not subprocess.DEVNULL: + if not isinstance(output, int): output.close() self.touch = TouchSender(self.touch_path) except BaseException: diff --git a/openpilot/starpilot/tests/test_dom_handoff_migration.py b/openpilot/starpilot/tests/test_dom_handoff_migration.py index 32e1e4d753..885f71b45d 100644 --- a/openpilot/starpilot/tests/test_dom_handoff_migration.py +++ b/openpilot/starpilot/tests/test_dom_handoff_migration.py @@ -10,6 +10,7 @@ from unittest.mock import patch spec = importlib.util.spec_from_file_location('handoff_state_migration', Path(__file__).resolve().parents[1] / 'state_migration.py') assert spec is not None migration = importlib.util.module_from_spec(spec) +assert spec.loader is not None spec.loader.exec_module(migration) diff --git a/openpilot/starpilot/tests/test_ev6_startup.py b/openpilot/starpilot/tests/test_ev6_startup.py index d91c03c614..c748d277e3 100644 --- a/openpilot/starpilot/tests/test_ev6_startup.py +++ b/openpilot/starpilot/tests/test_ev6_startup.py @@ -110,6 +110,7 @@ class TestEV6Startup(unittest.TestCase): self.addCleanup(holder.close) if (capture and requested and mode in ('sent', 'sent_restore') and not warm_fault and not wrong_bus and admission_results and admission_results[0]): + assert holder.owner is not None self.assertIs(holder.owner.outcome, Outcome.SENT_UNCONFIRMED) self.assertTrue(ci.CP.openpilotLongitudinalControl) self.assertEqual(ci.CP.safetyConfigs[-1].safetyParam, diff --git a/openpilot/starpilot/tests/test_ev9_lead_inputs.py b/openpilot/starpilot/tests/test_ev9_lead_inputs.py index 1a1409fcfa..b5e4dc4c3d 100644 --- a/openpilot/starpilot/tests/test_ev9_lead_inputs.py +++ b/openpilot/starpilot/tests/test_ev9_lead_inputs.py @@ -115,7 +115,7 @@ class TestEV9LeadInputs(unittest.TestCase): for parser in ci.can_parsers.values(): for address in parser.addresses: name = parser.dbc.addr_to_msg[address].name - fields = {'GEAR': 5} if name == 'ACCELERATOR' else {} + fields = {'GEAR': 5.0} if name == 'ACCELERATOR' else {} frames.append(packer.make_can_msg(name, parser.bus, fields)) frames.append(camera_packet(packer, 1, tick+1, 30., -1.)) stamp = messages.now+OFFSET-1000 diff --git a/openpilot/starpilot/tests/test_first_start_migration.py b/openpilot/starpilot/tests/test_first_start_migration.py index e794d2bab2..6ee6a15b3f 100644 --- a/openpilot/starpilot/tests/test_first_start_migration.py +++ b/openpilot/starpilot/tests/test_first_start_migration.py @@ -10,6 +10,7 @@ SOURCE = Path(__file__).resolve().parents[1] / 'state_migration.py' spec = importlib.util.spec_from_file_location('isolated_state_migration', SOURCE) assert spec is not None migration = importlib.util.module_from_spec(spec) +assert spec.loader is not None spec.loader.exec_module(migration) diff --git a/openpilot/starpilot/tests/test_ford_native_pinion_guard.py b/openpilot/starpilot/tests/test_ford_native_pinion_guard.py index fbe1cae14d..0aeb4481a8 100644 --- a/openpilot/starpilot/tests/test_ford_native_pinion_guard.py +++ b/openpilot/starpilot/tests/test_ford_native_pinion_guard.py @@ -13,6 +13,7 @@ from opendbc.car.ford.values import CAR, DBC, CarControllerParams from opendbc.bluepilot_lateral.hosts.starpilot.safety_param import init_ford_safety_param_starpilot from opendbc.safety.tests.libsafety import libsafety_py from openpilot.starpilot.car.ford.bluepilot import FordBluePilotController +from openpilot.starpilot.car.ford.starpilot_controller import StarPilotFordController from openpilot.starpilot.car.ford.controller_selection import FordController @@ -90,12 +91,14 @@ def test_pinion_guard_preserves_host_and_native_bounds(car, speed, sign, ratio, if not safety.safety_tx_hook(libsafety_py.make_CANPacket(address, bus, data)): blocked.append((frame, hex(address))) assert sent > 40 + angle = controller.bp.angle + assert isinstance(angle, StarPilotFordController) if refused: assert blocked - assert controller.bp.angle.native_curvature_bounds is None + assert angle.native_curvature_bounds is None else: assert not blocked, blocked - bounds = controller.bp.angle.native_curvature_bounds + bounds = angle.native_curvature_bounds assert bounds is not None low, high = bounds assert low <= controller.bp.angle.bp_kappa_cmd <= high @@ -180,7 +183,9 @@ def test_yaw_guard_keeps_encoded_shadow_inside_native_measurements(car, speed, s sent += 1 assert safety.safety_tx_hook(libsafety_py.make_CANPacket(address, bus, data)), (frame, hex(address)) assert sent > 30 - bounds = controller.bp.angle.native_curvature_bounds + angle = controller.bp.angle + assert isinstance(angle, StarPilotFordController) + bounds = angle.native_curvature_bounds assert bounds is not None assert bounds[0] <= controller.bp.angle.bp_kappa_cmd <= bounds[1] finally: diff --git a/openpilot/starpilot/tests/test_ford_starpilot_angle.py b/openpilot/starpilot/tests/test_ford_starpilot_angle.py index 0c9260211e..823a0cf539 100644 --- a/openpilot/starpilot/tests/test_ford_starpilot_angle.py +++ b/openpilot/starpilot/tests/test_ford_starpilot_angle.py @@ -275,7 +275,9 @@ def test_new_invalid_frame_cannot_reuse_cached_turn_intent(invalid): host.update(frame, 5) assert host.inputs.model is not None # Upstream correctly retains its previous complete snapshot. packets, _ = host.step_lateral(cc, cs, cc.actuators, 0.) - assert host.angle.conditioner.curvature is None + angle = host.angle + assert isinstance(angle, StarPilotFordController) + assert angle.conditioner.curvature is None assert host.angle.bp_path_angle_final == 0. assert all((data[0] >> 4) & 7 == 0 for address, data, _ in packets if address == 0x3D6) diff --git a/openpilot/starpilot/tests/test_gm_vision_source.py b/openpilot/starpilot/tests/test_gm_vision_source.py index 43f6763fce..d799f643b2 100644 --- a/openpilot/starpilot/tests/test_gm_vision_source.py +++ b/openpilot/starpilot/tests/test_gm_vision_source.py @@ -160,6 +160,7 @@ class TestGmVisionSource(unittest.TestCase): assert_cap(repeated, 55, sm, driver_set) if confirmation: self.assertEqual(repeated.result.state.acceptance.accepted, approved) + assert repeated.result.acceptance is not None self.assertIsNone(repeated.result.acceptance.history_write) evidence.speedMps = next_mph * .44704 evidence.episode += 1 @@ -172,6 +173,7 @@ class TestGmVisionSource(unittest.TestCase): accepted_mph = 55 if confirmation else next_mph self.assertAlmostEqual(changed.message.slcState.acceptedSpeedLimit, accepted_mph * .44704, places=4) assert_cap(changed, accepted_mph, sm, driver_set) + assert changed.result.acceptance is not None self.assertEqual(changed.result.acceptance.policy, runtime.settings.acceptance) sm.data['carControl'].longActive = False sm.advance(5_080_000_000) diff --git a/openpilot/starpilot/ui/bluetooth_compact.py b/openpilot/starpilot/ui/bluetooth_compact.py index 5dc9d41011..bd67936bc7 100644 --- a/openpilot/starpilot/ui/bluetooth_compact.py +++ b/openpilot/starpilot/ui/bluetooth_compact.py @@ -101,7 +101,8 @@ class BluetoothCompact(NavScroller): pairing_action = operation in ("pairing_response", "cancel_pair") if not (self._pairing_ready() if pairing_action else self._ready()): return - if operation == "power" and not self.status.get("parked"): + status = self.status + if operation == "power" and (status is None or not status.get("parked")): return if pairing_action and operation == "pairing_response": prompt = ((self.status or {}).get("pairing") or {}).get("prompt") @@ -338,8 +339,9 @@ class BluetoothCompact(NavScroller): "Remove phones paired for the StarPilot app only?", self.icon, lambda: self._forget_app_only(), red=True))) cards.append(cleanup) - self.pairing_page._scroller.items.clear() - self.pairing_page._scroller.add_widgets(cards) + if self.pairing_page is not None: + self.pairing_page._scroller.items.clear() + self.pairing_page._scroller.add_widgets(cards) def _forget_app_phone(self, phone_id: str): from openpilot.starpilot.galaxy_bluetooth.phone_ui import forget_app_phone diff --git a/openpilot/starpilot/ui/bluetooth_large.py b/openpilot/starpilot/ui/bluetooth_large.py index 6518960f8d..5ca507607c 100644 --- a/openpilot/starpilot/ui/bluetooth_large.py +++ b/openpilot/starpilot/ui/bluetooth_large.py @@ -112,7 +112,8 @@ class BluetoothLarge(Widget): pairing_action = operation in ("pairing_response", "cancel_pair") if not (self._pairing_ready() if pairing_action else self._ready()): return - if operation == "power" and not self.status.get("parked"): + status = self.status + if operation == "power" and (status is None or not status.get("parked")): return if pairing_action and operation == "pairing_response": prompt = ((self.status or {}).get("pairing") or {}).get("prompt") @@ -195,10 +196,11 @@ class BluetoothLarge(Widget): if prompt and self._pairing_ready() and prompt["id"] != self.last_prompt_id and not gui_app.mouse_events: self.last_prompt_id = prompt["id"] self._prompt(prompt) - if (self.active and self.scan_on_ready and self._ready() and - self.status.get("powered") and self.status.get("parked")): + status = self.status + if (self.active and self.scan_on_ready and self._ready() and status is not None and + status.get("powered") and status.get("parked")): self.scan_on_ready = False - if not self.status.get("discovering"): + if not status.get("discovering"): self._request("auto_scan") return if self.pending is None and time.monotonic() >= self.next_refresh: diff --git a/openpilot/starpilot/ui/clip.py b/openpilot/starpilot/ui/clip.py index 69c01ac9e8..0dde8a9b64 100644 --- a/openpilot/starpilot/ui/clip.py +++ b/openpilot/starpilot/ui/clip.py @@ -4,7 +4,7 @@ from __future__ import annotations from contextlib import contextmanager from contextvars import ContextVar -from collections.abc import Iterator +from collections.abc import Generator from openpilot.starpilot.ui.raylib import rl @@ -20,7 +20,7 @@ def _intersection(a: rl.Rectangle, b: rl.Rectangle) -> rl.Rectangle: @contextmanager -def placed_at(rect: rl.Rectangle, parent_clip: rl.Rectangle | None = None) -> Iterator[None]: +def placed_at(rect: rl.Rectangle, parent_clip: rl.Rectangle | None = None) -> Generator[None]: """Translate view geometry and its explicit scissors together. The compact scroller already has a screen-space scissor. Child scissors replace @@ -42,7 +42,7 @@ def placed_at(rect: rl.Rectangle, parent_clip: rl.Rectangle | None = None) -> It @contextmanager -def clipped(rect: rl.Rectangle, parent: rl.Rectangle) -> Iterator[None]: +def clipped(rect: rl.Rectangle, parent: rl.Rectangle) -> Generator[None]: bounds = _intersection(rect, parent) rl.rl_draw_render_batch_active() begin_scissor_mode(bounds.x, bounds.y, bounds.width, bounds.height) diff --git a/openpilot/starpilot/ui/feature_settings_owner.py b/openpilot/starpilot/ui/feature_settings_owner.py index 4862a18f7c..9fbac4c86b 100644 --- a/openpilot/starpilot/ui/feature_settings_owner.py +++ b/openpilot/starpilot/ui/feature_settings_owner.py @@ -1800,6 +1800,8 @@ class FeatureSettingsOwner: })): return False if key == "CustomPersonalities": + if not isinstance(encoded, str): + return False dependencies = dict(request.dependencies) if doc is not None: dependencies[PERSONALITY_PROFILES_PARAM] = updated_document diff --git a/openpilot/starpilot/ui/layout_preview_renderer.py b/openpilot/starpilot/ui/layout_preview_renderer.py index fec44f6bf2..36074bbe2d 100644 --- a/openpilot/starpilot/ui/layout_preview_renderer.py +++ b/openpilot/starpilot/ui/layout_preview_renderer.py @@ -301,9 +301,10 @@ class _Canvas: def _render_driver_monitor(self, rect: rl.Rectangle, state: OnroadState, *, general: bool = False) -> None: top_icons = (not general and self.profile == Profile.COMPACT and state.alert.size == AlertSize.NONE and state.appearance.camera_view != CameraViewChoice.DRIVER and not state.reverse_driver_camera and - self.view.compact_hud._set_speed_alpha.x > 0.01 and + self.view is not None and self.view.compact_hud._set_speed_alpha.x > 0.01 and placement(state.customization, self.profile, "max_speed")["enabled"]) - self.monitor.render(rect, state, top_icons=top_icons, y_offset=self.viewport[1] - 1080 if self.viewport else 0) + if self.monitor is not None: + self.monitor.render(rect, state, top_icons=top_icons, y_offset=self.viewport[1] - 1080 if self.viewport else 0) def render(self, state: OnroadState, scene: str) -> bytes: if self.view is None or self.fonts is None or self.target is None: @@ -311,7 +312,7 @@ class _Canvas: self._settle(state) width, height = self.viewport or self.profile.size placed = self._map_placement(state) if self.map is not None else None - if placed is not None: + if placed is not None and self.map is not None: from openpilot.starpilot.ui.onroad_map import sample_input self.map.prepare(sample_input(), placed["width"], placed["height"]) # offscreen, before the preview target rl.begin_texture_mode(self.target) diff --git a/openpilot/starpilot/ui/longitudinal_developer.py b/openpilot/starpilot/ui/longitudinal_developer.py index a41a82f63b..c7e9c0e659 100644 --- a/openpilot/starpilot/ui/longitudinal_developer.py +++ b/openpilot/starpilot/ui/longitudinal_developer.py @@ -53,8 +53,10 @@ def apply(owner, request): except (ValueError, TypeError, OverflowError): return False + row_key = row.key + def authorized(): - current = next((entry for entry in rows(owner) if entry.key == row.key), None) + current = next((entry for entry in rows(owner) if entry.key == row_key), None) return current is not None and current.available and current.capability == row.capability return commit_exact(owner.params, key=KEY, max_bytes=LIMIT, raw=encoded, expected=row.source, diff --git a/openpilot/starpilot/ui/native/_raylib_extra.pyi b/openpilot/starpilot/ui/native/_raylib_extra.pyi new file mode 100644 index 0000000000..e9154594fb --- /dev/null +++ b/openpilot/starpilot/ui/native/_raylib_extra.pyi @@ -0,0 +1,3 @@ +from types import ModuleType + +def install(target: ModuleType, path: str) -> None: ... diff --git a/openpilot/starpilot/ui/onroad_lane_alerts.py b/openpilot/starpilot/ui/onroad_lane_alerts.py index 78bd6963e0..c30f5f8bf8 100644 --- a/openpilot/starpilot/ui/onroad_lane_alerts.py +++ b/openpilot/starpilot/ui/onroad_lane_alerts.py @@ -2,7 +2,7 @@ from typing import Any -from openpilot.selfdrive.selfdrived.events import EVENTS, ET, EventName +from openpilot.selfdrive.selfdrived.events import Alert, EVENTS, ET, EventName from openpilot.starpilot.ui.onroad_state import AlertSize, OnroadAlert @@ -24,6 +24,8 @@ def lateral_lane_alert(native: OnroadAlert, *, car: Any, control: Any, model: An else: return native warning = EVENTS[event][ET.WARNING] + if not isinstance(warning, Alert): + return native name = next(name for name in ('preLaneChangeLeft', 'preLaneChangeRight', 'laneChangeBlocked', 'laneChange') if getattr(EventName, name) == event) return OnroadAlert((AlertSize.NONE, AlertSize.SMALL, AlertSize.MID, AlertSize.FULL)[warning.alert_size], diff --git a/openpilot/starpilot/ui/onroad_map.py b/openpilot/starpilot/ui/onroad_map.py index 68f57691e0..914cc808c7 100644 --- a/openpilot/starpilot/ui/onroad_map.py +++ b/openpilot/starpilot/ui/onroad_map.py @@ -926,7 +926,8 @@ class MapOverlay: vec2, scalar = rl.ShaderUniformDataType.SHADER_UNIFORM_VEC2, rl.ShaderUniformDataType.SHADER_UNIFORM_FLOAT for name, value, kind in (("size", size, vec2), ("radius", radius, scalar), ("feather", feather, scalar), ("opacity", alpha, scalar)): rl.set_shader_value(self._shader, self._uniforms[name], value, kind) - rl.set_shader_value_texture(self._shader, self._uniforms["guidance"], self._guidance.texture) + if self._guidance is not None: + rl.set_shader_value_texture(self._shader, self._uniforms["guidance"], self._guidance.texture) rl.draw_texture_pro(self._widget.texture, rl.Rectangle(0, 0, width, height), rect, rl.Vector2(0, 0), 0, rl.WHITE) finally: rl.end_shader_mode() @@ -951,22 +952,25 @@ class MapOverlay: def _draw_road_name(self, rect: rl.Rectangle) -> None: """Draw the current road below the car, independent of map opacity.""" + fonts = self.fonts + if fonts is None: + return from openpilot.starpilot.ui.presentation import FontRole size = max(18, round(min(rect.width, rect.height) * 0.075)) limit = rect.width * 0.8 - size key = (self._name, size, round(limit)) if self._name_layout is None or self._name_layout[0] != key: text = self._name - while len(text) > 3 and self.fonts.measure(text, FontRole.MEDIUM, size).width > limit: + while len(text) > 3 and fonts.measure(text, FontRole.MEDIUM, size).width > limit: text = text[:-4] + "..." if text.endswith("...") else text[:-1] + "..." - self._name_layout = key, text, self.fonts.measure(text, FontRole.MEDIUM, size).width + self._name_layout = key, text, fonts.measure(text, FontRole.MEDIUM, size).width _, text, text_width = self._name_layout pad = size * 0.55 pill = rl.Rectangle(rect.x + (rect.width - text_width) / 2 - pad, rect.y + rect.height * CAR_ANCHOR + 38, text_width + pad * 2, size * 1.55) rl.draw_rectangle_rounded(pill, 0.5, 8, rl.Color(15, 13, 23, 255)) rl.draw_rectangle_rounded_lines_ex(pill, 0.5, 8, 1.5, rl.Color(150, 140, 200, 255)) - self.fonts.draw(text, FontRole.MEDIUM, size, pill.x + pad, pill.y + size * 0.27, rl.Color(240, 242, 250, 255)) + fonts.draw(text, FontRole.MEDIUM, size, pill.x + pad, pill.y + size * 0.27, rl.Color(240, 242, 250, 255)) def _draw_attribution(self, rect: rl.Rectangle) -> None: """Google's name and data credit along the bottom edge, solid whatever the map's opacity.""" diff --git a/openpilot/starpilot/ui/onroad_map_layer.py b/openpilot/starpilot/ui/onroad_map_layer.py index 649abe07ea..d7a1844208 100644 --- a/openpilot/starpilot/ui/onroad_map_layer.py +++ b/openpilot/starpilot/ui/onroad_map_layer.py @@ -32,6 +32,8 @@ class NativeMapLayer: from openpilot.starpilot.ui.onroad_map import MapFeed, live_overlay self.map = live_overlay(self.fonts) self.feed = MapFeed() + if self.feed is None: + return self.map.prepare(self.feed.read(self.ui.sm), placed["width"], placed["height"]) self.prepared_size = (placed["width"], placed["height"]) diff --git a/openpilot/starpilot/ui/onroad_uniden.py b/openpilot/starpilot/ui/onroad_uniden.py index 7fa58174df..0716c8fddb 100644 --- a/openpilot/starpilot/ui/onroad_uniden.py +++ b/openpilot/starpilot/ui/onroad_uniden.py @@ -505,12 +505,12 @@ class UnidenWidget: return claimed def _state(self, mode): - return self.session.snapshot(mode).onroad if mode == ShellMode.ONROAD else None + return self.session.snapshot(mode).onroad if mode == ShellMode.ONROAD and self.session is not None else None def press(self, mode, x, y): session = self.session - self.claimed = bool(mode == ShellMode.ONROAD and not session.favorites.is_open and self.touch('down', x, y, self._state(mode))) - if self.claimed: + self.claimed = bool(session is not None and mode == ShellMode.ONROAD and not session.favorites.is_open and self.touch('down', x, y, self._state(mode))) + if self.claimed and session is not None: session.input.cancel() return self.claimed diff --git a/openpilot/starpilot/ui/path_markers.py b/openpilot/starpilot/ui/path_markers.py index 604af182bd..8511a12130 100644 --- a/openpilot/starpilot/ui/path_markers.py +++ b/openpilot/starpilot/ui/path_markers.py @@ -231,7 +231,8 @@ class PathMarkers: lead.lose() else: lead.strip, lead.box = box, bounds(box) - lead.fade_filter.update(calm + (urgent - calm) * urgency(float(lead.info.dRel), lead.info.vRel) if box is not None else 0.0) + info = lead.info + lead.fade_filter.update(calm + (urgent - calm) * urgency(float(info.dRel), info.vRel) if box is not None and info is not None else 0.0) if lead.fade_filter.x < 0.01: lead.strip = lead.box = None diff --git a/openpilot/starpilot/ui/replay_settings.py b/openpilot/starpilot/ui/replay_settings.py index 99a4292030..5df8c2855a 100644 --- a/openpilot/starpilot/ui/replay_settings.py +++ b/openpilot/starpilot/ui/replay_settings.py @@ -182,7 +182,7 @@ class ReplayController: return {'op': 'stop', 'sessionId': session, 'clientId': self.client_id, 'requestId': uuid.uuid4().hex} def _read_frame(self, key): - if key != self.reader_key: + if key != self.reader_key or self.reader is None: self._close_reader() self.reader = self.reader_factory(*key[:3]) self.reader_key = key @@ -293,7 +293,7 @@ class ReplayController: return self.closed = True self.autoplay_at = None - if self.pending_op == 'start' or self.pending_op == 'status' and not self.own_session: + if self.pending is not None and (self.pending_op == 'start' or self.pending_op == 'status' and not self.own_session): def stop_late_start(future): try: response = future.result() @@ -739,11 +739,12 @@ class ReplayPage(Widget): cards.append(button) if self.controller.error: cards.append(GreyBigButton('replay unavailable', self.controller.error)) - self.cards._scroller.items.clear() - self.cards._scroller.add_widgets(cards) + if self.cards is not None: + self.cards._scroller.items.clear() + self.cards._scroller.add_widgets(cards) def _render(self, rect): - if self.profile == Profile.COMPACT and self.page == 'routes': + if self.profile == Profile.COMPACT and self.page == 'routes' and self.cards is not None: self._compact_cards() self.cards.render(rect) return @@ -753,7 +754,7 @@ class ReplayPage(Widget): self._render_viewer() elif self.page == 'detail': self._render_detail() - elif self.profile == Profile.LARGE: + elif self.profile == Profile.LARGE and self.view is not None: self.view.render(self._state(), self.input.drag_x, draw_row=self._render_route_row) def _button(self, label, bounds, enabled=True): diff --git a/openpilot/starpilot/ui/runtime_app.py b/openpilot/starpilot/ui/runtime_app.py index 65d7c966db..fe6e5138e2 100644 --- a/openpilot/starpilot/ui/runtime_app.py +++ b/openpilot/starpilot/ui/runtime_app.py @@ -26,7 +26,7 @@ from openpilot.selfdrive.ui.layouts.home import HomeLayoutState from openpilot.selfdrive.ui.layouts.main import MainLayout, MainState from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout as MiciMainLayout from openpilot.starpilot.ui.runtime_compact import StarMiciMainLayout as StarMiciMainLayout -from openpilot.selfdrive.ui.ui_state import device as native_device, ui_state +from openpilot.selfdrive.ui.ui_state import device as native_device, ui_state, live_params from openpilot.starpilot.ui.vehicle_bool import VEHICLE_BOOL_KEYS, confirmation_question as vehicle_question from openpilot.starpilot.ui.vehicle_large import SELECTION_PAGE, VehicleLarge from openpilot.starpilot.ui.clip import placed_at @@ -67,7 +67,7 @@ from openpilot.starpilot.ui.models_state import model_needs_gpu, model_toolbar, from openpilot.starpilot.ui.maps_state import MapStatusSource from openpilot.starpilot.galaxy.access import GalaxyAccessOwner, default_owner from openpilot.starpilot.ui.galaxy_access import GalaxyAccessFlow -from openpilot.starpilot.ui.home_state import HomeActionKind +from openpilot.starpilot.ui.home_state import HomeAction, HomeActionKind from openpilot.starpilot.ui.presentation import BitmapFonts, FontRole, Profile, default_font_directory from openpilot.starpilot.ui.startup import slc_action_transport_enabled, validate_artwork, validate_fonts from openpilot.starpilot.speed_limits.vision_gate import diagnostic_choice_enabled @@ -905,11 +905,13 @@ class StarShellSession(TeslaSpeedActions): width, height = widget_size(state.customization, self.profile, key) shift = (state.viewport_width - 1860) if self.profile == Profile.LARGE and key == "pip_right" else 0 camera_positions[side] = Rect(position["x"] + shift, position["y"], width, height) + draw_submit = submit + if submit is not None and self.profile == Profile.COMPACT: + def draw_submit(_key, draw): + return submit("pip_left", draw) status = self.pip_renderer.render(rect, saved.mask, signals, enabled=True, on_blinker=saved.on_blinker, on_bsm=saved.on_bsm, invert=saved.invert, - placements=camera_positions, - **({"submit": (lambda _key, draw: submit("pip_left", draw)) if self.profile == Profile.COMPACT else submit} - if submit is not None else {})) + placements=camera_positions, submit=draw_submit) if status not in ("rendered", "inactive") and state.alert.size == AlertSize.NONE: self.fonts.draw("ADJ SPOT CAMERA UNAVAILABLE", FontRole.MEDIUM, 18 if self.profile == Profile.COMPACT else 25, @@ -957,9 +959,10 @@ class StarShellSession(TeslaSpeedActions): return state def map_snapshot(self): - if getattr(self, "map_source", None) is None: - self.map_source = MapStatusSource() - return self.map_source.snapshot() + source = getattr(self, "map_source", None) + if source is None: + source = self.map_source = MapStatusSource() + return source.snapshot() def model_snapshot(self): try: @@ -1131,7 +1134,7 @@ class StarShellSession(TeslaSpeedActions): self.selected = Destination.STAR self.display_scroll = 0 self.input.cancel() - elif action.kind == "open" and not state.editor and action.row in state.rows: + elif action.kind == "open" and not state.editor and action.row is not None and action.row in state.rows: if action.row.key == DISPLAY_MASTER and action.row.page == "display": self.display_page = "display" self.display_scroll = 0 @@ -1270,7 +1273,8 @@ class StarShellSession(TeslaSpeedActions): self.selected = Destination.STAR self.sounds_scroll = 0 self.input.cancel() - elif action.kind == "open" and state.page == "sounds:overview" and action.row in state.rows and action.row.available: + elif (action.kind == "open" + and state.page == "sounds:overview" and action.row is not None and action.row in state.rows and action.row.available): self.sounds_edit_key = action.row.key self.input.cancel() elif action.kind == "scroll" and self.sounds_edit_key is None: @@ -1299,7 +1303,7 @@ class StarShellSession(TeslaSpeedActions): self.input.cancel() elif action.kind == "scroll" and not state.editor: self.feature_scroll = feature_scroll(self.feature_scroll, action.direction, len(state.rows)) - elif action.kind == "open" and not state.editor and action.row in state.rows and action.row.page: + elif action.kind == "open" and not state.editor and action.row is not None and action.row in state.rows and action.row.page: self._lane_change_request_epoch = getattr(self, "_lane_change_request_epoch", 0) + 1 if action.row.presets: if not action.row.available: @@ -1591,13 +1595,13 @@ class StarShellSession(TeslaSpeedActions): if self._wheel_personality is not None: self._wheel_personality() return - if request.source == "onroad" and getattr(action, "kind", None) == "set_experimental": + if request.source == "onroad" and isinstance(action, OnroadRequest) and action.kind == "set_experimental": binding = self._native_favorite_actions().get(EXPERIMENTAL) if not (binding is not None and binding.available and binding.invoke is not None and action.action_token == binding.token and binding.invoke()): self._unavailable("experimental shortcut in this context") return - if request.source == "home": + if request.source == "home" and isinstance(action, HomeAction): if action.kind == HomeActionKind.OPEN_ALERTS and self._on_alerts is not None and self._on_alerts(): pass # on_alerts returns False when no alert is active, so the tap falls through to settings elif action.kind in (HomeActionKind.OPEN_SETTINGS, HomeActionKind.OPEN_ALERTS) and self._on_settings is not None: @@ -1613,7 +1617,7 @@ class StarShellSession(TeslaSpeedActions): self._unavailable("device pairing") else: self._unavailable("End to End owner") - elif request.source == "settings": + elif request.source == "settings" and isinstance(action, SettingsAction): if action.kind == SettingsActionKind.CLOSE: if self.selected == Destination.DRIVING_CONTROLS and getattr(self, "feature_edit_key", None) is not None: self._feature_ui(FeatureUiAction("back")) @@ -1956,7 +1960,7 @@ class StarMainLayout(MainLayout): def save(state: bool) -> None: try: - ui_state.params.put_bool(AGGRESSIVE_COOLING_KEY, state, block=True) + live_params(ui_state.params).put_bool(AGGRESSIVE_COOLING_KEY, state, block=True) except UnknownKeyName: item.action_item.set_state(False) diff --git a/openpilot/starpilot/ui/runtime_compact.py b/openpilot/starpilot/ui/runtime_compact.py index da13dbf78f..82c70b3515 100644 --- a/openpilot/starpilot/ui/runtime_compact.py +++ b/openpilot/starpilot/ui/runtime_compact.py @@ -9,11 +9,16 @@ class StarMiciMainLayout(MiciMainLayout): """Compact existing scroller/nav stack with StarPilot content pages.""" def __init__(self): + from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import AugmentedRoadView + from openpilot.selfdrive.ui.mici.layouts.home import MiciHomeLayout from openpilot.starpilot.ui import runtime_app as runtime runtime.validate_runtime_fonts(runtime.Profile.COMPACT) runtime.validate_runtime_assets() super().__init__() - self._native_onroad = self._car_onroad_layout + native_onroad, native_home = self._car_onroad_layout, self._home_layout + if not isinstance(native_onroad, AugmentedRoadView) or not isinstance(native_home, MiciHomeLayout): + raise RuntimeError("Compact native layouts unavailable") + self._native_onroad = native_onroad self._compact_panels: dict[runtime.Destination, runtime.Widget] = {} try: self.star = runtime.StarShellSession(runtime.Profile.COMPACT, self._native_onroad) @@ -21,7 +26,7 @@ class StarMiciMainLayout(MiciMainLayout): self._native_onroad.close() raise # Upstream's alerts pill is already wired to the alerts page; keep it on the StarPilot home - self._home_layout = runtime.StarShellPage(self.star, runtime.ShellMode.HOME, alerts_pill=self._home_layout._alerts_pill) + self._home_layout = runtime.StarShellPage(self.star, runtime.ShellMode.HOME, alerts_pill=native_home._alerts_pill) self._car_onroad_layout = runtime.StarShellPage(self.star, runtime.ShellMode.ONROAD, on_background_tap=lambda: self._scroll_to(self._home_layout)) self._settings_layout = runtime.StarCompactSettings(self.star) diff --git a/openpilot/starpilot/ui/shell.py b/openpilot/starpilot/ui/shell.py index f234d8c0b3..c6cf68ca10 100644 --- a/openpilot/starpilot/ui/shell.py +++ b/openpilot/starpilot/ui/shell.py @@ -89,28 +89,28 @@ class ShellView: self.home.render(snapshot.home) elif snapshot.mode == ShellMode.ONROAD: self.onroad.render(snapshot.onroad) - elif self.profile == Profile.LARGE and snapshot.selected == Destination.DEVICE: + elif self.profile == Profile.LARGE and snapshot.selected == Destination.DEVICE and self.device is not None: self.device.render(snapshot.device) self.settings.render_rail(snapshot.settings, selected=Destination.DEVICE) - elif self.profile == Profile.LARGE and snapshot.selected == Destination.SOFTWARE: + elif self.profile == Profile.LARGE and snapshot.selected == Destination.SOFTWARE and self.software is not None: self.software.render(snapshot.software) self.settings.render_rail(snapshot.settings, selected=Destination.SOFTWARE) - elif self.profile == Profile.LARGE and snapshot.selected == Destination.TOGGLES: + elif self.profile == Profile.LARGE and snapshot.selected == Destination.TOGGLES and self.toggles is not None: self.toggles.render(snapshot.toggles) self.settings.render_rail(snapshot.settings, selected=Destination.TOGGLES) - elif self.profile == Profile.LARGE and snapshot.selected == Destination.DRIVING_CONTROLS: + elif self.profile == Profile.LARGE and snapshot.selected == Destination.DRIVING_CONTROLS and self.features is not None: self.features.render(snapshot.features, drag_x) self.settings.render_rail(snapshot.settings, selected=Destination.STAR) - elif self.profile == Profile.LARGE and snapshot.selected == Destination.SOUNDS: + elif self.profile == Profile.LARGE and snapshot.selected == Destination.SOUNDS and self.sounds is not None: self.sounds.render(snapshot.sounds, drag_x) self.settings.render_rail(snapshot.settings, selected=Destination.STAR) - elif self.profile == Profile.LARGE and snapshot.selected == Destination.APPEARANCE: + elif self.profile == Profile.LARGE and snapshot.selected == Destination.APPEARANCE and self.appearance is not None: self.appearance.render(snapshot.appearance, drag_x) self.settings.render_rail(snapshot.settings, selected=Destination.STAR) - elif self.profile == Profile.LARGE and snapshot.selected == Destination.SYSTEM: + elif self.profile == Profile.LARGE and snapshot.selected == Destination.SYSTEM and self.display is not None: self.display.render(snapshot.display, drag_x) self.settings.render_rail(snapshot.settings, selected=Destination.STAR) - elif self.profile == Profile.LARGE and snapshot.selected == Destination.DRIVING_MODEL: + elif self.profile == Profile.LARGE and snapshot.selected == Destination.DRIVING_MODEL and self.models is not None: self.models.render(snapshot.models, drag_x) self.settings.render_rail(snapshot.settings, selected=Destination.STAR) elif self.profile == Profile.LARGE and snapshot.selected == Destination.NETWORK: diff --git a/openpilot/starpilot/ui/spacepilot/session.py b/openpilot/starpilot/ui/spacepilot/session.py index 1ae70bedcd..602d404954 100644 --- a/openpilot/starpilot/ui/spacepilot/session.py +++ b/openpilot/starpilot/ui/spacepilot/session.py @@ -131,7 +131,8 @@ class GameSession: if self.stage != Stage.PLAYING: self.stage = Stage.PLAYING # Pre-admission presses/releases cannot arm a wheel action. - self.wheel = WheelInput(self.vehicle.sample.source_boot_ns if self.vehicle is not None else 0) + sample = self.vehicle.sample if self.vehicle is not None else None + self.wheel = WheelInput(sample.source_boot_ns if sample is not None else 0) return False fire = False for sample in samples: diff --git a/openpilot/starpilot/ui/tests/test_bluetooth_compact.py b/openpilot/starpilot/ui/tests/test_bluetooth_compact.py index 631fd14154..62be04cfc5 100644 --- a/openpilot/starpilot/ui/tests/test_bluetooth_compact.py +++ b/openpilot/starpilot/ui/tests/test_bluetooth_compact.py @@ -165,6 +165,7 @@ class TestBluetoothCompact(unittest.TestCase): page.return_to_root = False with patch.object(BluetoothCompact, "_rebuild") as rebuild: page._request("power", enabled=True) + assert page.executor is not None page.executor.submit.assert_called_once_with(page._power_request, True) owner.request.assert_not_called() self.assertIs(page.pending, future) @@ -186,11 +187,14 @@ class TestBluetoothCompact(unittest.TestCase): page.queued = None with patch.object(page, "_rebuild"): page._request("power", enabled=True) + assert executor is not None executor.submit.assert_not_called() with patch("openpilot.starpilot.ui.bluetooth_compact.gui_app.remove_nav_stack_tick"), \ patch("openpilot.starpilot.ui.bluetooth_compact.NavScroller.hide_event"): page.hide_event() + assert executor is not None executor.submit.assert_called_once_with(owner.close) + assert executor is not None executor.shutdown.assert_called_once_with(wait=False, cancel_futures=False) self.assertIsNone(page.executor) @@ -236,9 +240,11 @@ class TestBluetoothCompact(unittest.TestCase): page.next_refresh = float("inf") with patch.object(BluetoothCompact, "_rebuild"): page._request("scan") + assert page.executor is not None page.executor.submit.assert_not_called() refreshing.set_result(page.status) page._tick() + assert page.executor is not None page.executor.submit.assert_called_once_with(owner.request, "scan", address=None, enabled=None) self.assertIs(page.pending, action) self.assertIsNone(page.queued) diff --git a/openpilot/starpilot/ui/tests/test_cem_passive_scene.py b/openpilot/starpilot/ui/tests/test_cem_passive_scene.py index 278ecff244..275dc1bc57 100644 --- a/openpilot/starpilot/ui/tests/test_cem_passive_scene.py +++ b/openpilot/starpilot/ui/tests/test_cem_passive_scene.py @@ -39,8 +39,10 @@ def test_real_passive_scene_survives_control_reset(aol, lead_present): safe_mode=ObservedBool(False, stamp), owner_context=owner_context(stamp), selected_t_follow_s=1.45, selected_t_follow_observed_mono_ns=stamp) # Existing stop commitment precedence is unchanged; AOL never requests control. + assert proposal.decision is not None assert proposal.decision.reason.value == ('cem_stop' if not aol and not lead_present else 'manual_chill') assert proposal.override_experimental is (None if aol else not lead_present) + assert proposal.projected is not None assert proposal.projected.perceived_stop is (not lead_present) if aol: assert not host.projector.stop_detector.committed @@ -61,6 +63,7 @@ def test_real_passive_scene_survives_control_reset(aol, lead_present): assert light.call_count == (0 if lead_present else 1) data = gauge_data(state) if not lead_present: + assert data is not None assert data.indicator_type is IndicatorType.STOP_LIGHT else: assert data is None diff --git a/openpilot/starpilot/ui/tests/test_conditional_feature.py b/openpilot/starpilot/ui/tests/test_conditional_feature.py index 283ab0a538..b3bd404e41 100644 --- a/openpilot/starpilot/ui/tests/test_conditional_feature.py +++ b/openpilot/starpilot/ui/tests/test_conditional_feature.py @@ -89,12 +89,14 @@ class ConditionalFeatureTests(unittest.TestCase): from opendbc.car.honda.fingerprints import FW_VERSIONS from opendbc.car.honda.values import CAR as HONDA (ecu, address, subaddress), versions = next(iter(FW_VERSIONS[HONDA.HONDA_CIVIC_BOSCH].items())) + assert self.cp is not None firmware = self.cp.init("carFw", 1)[0] firmware.ecu, firmware.address, firmware.subAddress = ecu, address, subaddress or 0 firmware.fwVersion, firmware.brand = versions[0], "honda" + assert self.cp is not None self.assertIsInstance(self.cp.to_dict()["carFw"][0]["fwVersion"], bytes) row = self.row("conditional:mode") - self.assertIsNotNone(row.capability) + assert row.capability is not None for malformed in ((), (self.cp.carFingerprint,), (self.cp.carFingerprint, "invalid")): self.assertFalse(self.owner.apply(replace(required_change(row), value="End to End", capability=malformed))) self.assertTrue(self.owner.apply(replace(required_change(row), value="End to End"))) @@ -107,6 +109,7 @@ class ConditionalFeatureTests(unittest.TestCase): # Hashing copies the full CP instead of marking the live builder serialized. with warnings.catch_warnings(): warnings.simplefilter("error", UserWarning) + assert self.cp is not None self.cp.to_bytes() def test_mode_request_rejects_changed_baseline_safe_mode_and_final_cp(self): @@ -495,6 +498,7 @@ class ConditionalFeatureTests(unittest.TestCase): child = subprocess.Popen([sys.executable, "-c", script, str(manual_lock_path(self.params))], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) try: + assert child.stdout is not None self.assertEqual(child.stdout.readline().strip(), "ready") self.assertFalse(self.owner.apply(request)) self.assertEqual(decode_manual(path.read_bytes()), SavedCodes(cem=2, ccm=1)) @@ -568,6 +572,7 @@ class ConditionalFeatureTests(unittest.TestCase): child = subprocess.Popen([sys.executable, "-c", script, str(root / ".lock")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) try: + assert child.stdout is not None self.assertEqual(child.stdout.readline().strip(), "ready") self.assertFalse(self.owner.apply(request)) self.assertIsNone(self.params.get("ConditionalModeConfig")) diff --git a/openpilot/starpilot/ui/tests/test_controller_feature.py b/openpilot/starpilot/ui/tests/test_controller_feature.py index aec6599308..ba6a427ffc 100644 --- a/openpilot/starpilot/ui/tests/test_controller_feature.py +++ b/openpilot/starpilot/ui/tests/test_controller_feature.py @@ -1,6 +1,7 @@ """One shared saved steering-controller choice with exact source and CP guards.""" from unittest.mock import Mock +from openpilot.common.test import require_value from openpilot.starpilot.galaxy.settings import ContextSource from pathlib import Path import tempfile @@ -56,7 +57,7 @@ class TestControllerFeature(unittest.TestCase): with self.subTest(vehicle=vehicle): self.cp = interfaces[vehicle].get_non_essential_params(vehicle) row = self.require_row() - self.assertIsNotNone(row) + assert row is not None self.assertTrue(row.available) self.assertEqual((row.label, row.value), ('Steering Controller', 'StarPilot Controller')) self.assertEqual(row.choices, ('Stock Controller', 'StarPilot Controller')) @@ -128,6 +129,7 @@ class TestControllerFeature(unittest.TestCase): self.assertEqual(steering_controller(cp), expected) def test_learning_capability_rejects_unknown_angle_and_passive_cp(self): + assert self.cp is not None original = self.cp.as_reader().as_builder() for failure in ('unknown', 'brand', 'angle', 'passive', 'dashcam', 'not_car', 'nonfinite'): with self.subTest(failure=failure): @@ -172,7 +174,7 @@ class TestControllerFeature(unittest.TestCase): def test_stale_document_cp_and_authority_rejected(self): row = self.require_row() request = required_change(row) - self.cp.lateralTuning.torque.latAccelFactor *= 1.05 + require_value(self.cp).lateralTuning.torque.latAccelFactor *= 1.05 self.assertFalse(self.owner.apply(request)) self.cp = interfaces[HYUNDAI.HYUNDAI_IONIQ_6].get_non_essential_params(HYUNDAI.HYUNDAI_IONIQ_6) row = self.require_row() @@ -249,6 +251,7 @@ class TestControllerFeature(unittest.TestCase): row = self.require_row() self.assertFalse(row.available) self.assertEqual(row.value, 'Invalid saved controller choice') + assert self.cp is not None self.assertFalse(self.owner.apply(FeatureSettingsRequest(DOCUMENT_KEY, raw, 'Stock Controller', vehicle_fingerprint=str(self.cp.carFingerprint), capability=row.capability))) diff --git a/openpilot/starpilot/ui/tests/test_covered_camera.py b/openpilot/starpilot/ui/tests/test_covered_camera.py index aff5fe1542..0aabb9087d 100644 --- a/openpilot/starpilot/ui/tests/test_covered_camera.py +++ b/openpilot/starpilot/ui/tests/test_covered_camera.py @@ -5,6 +5,7 @@ from types import SimpleNamespace as NS from unittest.mock import Mock import numpy as np +from openpilot.common.test import require_value from openpilot.starpilot.ui.raylib import rl import pytest @@ -162,7 +163,7 @@ def test_covered_model_keeps_filters_geometry_leads_and_reveal_pixels(monkeypatc covered._paint = True output = [] def capture(rect, points, color=None, gradient=None): - colors = [color] if color is not None else gradient.colors + colors = [color] if color is not None else require_value(gradient).colors output.append((points.tolist(), [tuple(getattr(c, k) for k in 'rgba') for c in colors], None if gradient is None else (gradient.start, gradient.end, gradient.stops))) monkeypatch.setattr(module, 'draw_polygon', capture) diff --git a/openpilot/starpilot/ui/tests/test_curve_glow_flicker.py b/openpilot/starpilot/ui/tests/test_curve_glow_flicker.py index 5b16e673af..e759d70d0a 100644 --- a/openpilot/starpilot/ui/tests/test_curve_glow_flicker.py +++ b/openpilot/starpilot/ui/tests/test_curve_glow_flicker.py @@ -4,6 +4,7 @@ import random import unittest from unittest.mock import patch +from openpilot.common.test import require_value from openpilot.starpilot.ui.raylib import rl from openpilot.starpilot.curve_speed.status import CurvatureDisplay, CurveObservation @@ -46,19 +47,20 @@ def worst_step(colors) -> int: class CurveGlowFlickerTests(unittest.TestCase): def test_smoothed_curvature_holds_dropouts_and_resets_after_gap(self): display = CurvatureDisplay() - self.assertEqual(display.update(curve(.01), START_NS).road_curvature, .01) + self.assertEqual(require_value(display.update(curve(.01), START_NS)).road_curvature, .01) held = display.update(curve(None), START_NS + FRAME_NS) + assert held is not None self.assertEqual(held.road_curvature, .01) - stepped = display.update(curve(.02), START_NS + 2 * FRAME_NS).road_curvature - self.assertIsNotNone(stepped) + stepped = require_value(display.update(curve(.02), START_NS + 2 * FRAME_NS)).road_curvature + assert stepped is not None self.assertGreater(stepped or 0., .01) self.assertLess(stepped or 0., .013) self.assertIsNone(display.update(None, START_NS + 3 * FRAME_NS)) - self.assertEqual(display.update(curve(.003), START_NS + 3 * FRAME_NS + 2_000_000_000).road_curvature, .003) + self.assertEqual(require_value(display.update(curve(.003), START_NS + 3 * FRAME_NS + 2_000_000_000)).road_curvature, .003) def test_glow_changes_gradually_under_jittery_curvature(self): display = CurvatureDisplay() - smoothed = [display.update(curve(value), START_NS + frame * FRAME_NS).road_curvature + smoothed = [require_value(display.update(curve(value), START_NS + frame * FRAME_NS)).road_curvature for frame, value in enumerate(jitter(200))] self.assertLessEqual(worst_step(edges(smoothed, GlowPhase())), 40) diff --git a/openpilot/starpilot/ui/tests/test_developer_preview.py b/openpilot/starpilot/ui/tests/test_developer_preview.py index 926046012b..d174e57d8a 100644 --- a/openpilot/starpilot/ui/tests/test_developer_preview.py +++ b/openpilot/starpilot/ui/tests/test_developer_preview.py @@ -19,7 +19,9 @@ class DeveloperPreviewTests(unittest.TestCase): (6.0, "SPEED", .0200), (8.0, "CURVE", 0.0)): with self.subTest(elapsed=elapsed): value = preview_at(flags, elapsed) + assert value is not None self.assertEqual((value.cem_reason, value.curve_curvature), (reason, curvature)) + assert value is not None self.assertEqual(value.label, "SYNTHETIC REPLAY PREVIEW") self.assertIsNone(preview_at(frozenset(), 1.0)) @@ -70,7 +72,9 @@ class DeveloperPreviewTests(unittest.TestCase): session._visual_preview_flags = frozenset(("cem", "csc")) session._snapshot_cache = None observed = session.snapshot(ShellMode.ONROAD) + assert observed.onroad.visual_preview is not None self.assertEqual(observed.onroad.visual_preview.cem_reason, "LEAD") + assert observed.onroad.visual_preview is not None self.assertEqual(observed.onroad.visual_preview.curve_curvature, .008) self.assertEqual(replace(observed, onroad=baseline.onroad), baseline) self.assertIsNone(baseline.onroad.visual_preview) diff --git a/openpilot/starpilot/ui/tests/test_dinish_speed.py b/openpilot/starpilot/ui/tests/test_dinish_speed.py index 1af599e435..ae4f231c8b 100644 --- a/openpilot/starpilot/ui/tests/test_dinish_speed.py +++ b/openpilot/starpilot/ui/tests/test_dinish_speed.py @@ -448,6 +448,7 @@ def test_preview_sprite_keeps_the_full_confirmation_and_sign_scenes(profile): sprite = sheet.crop((slot['x'], slot['y'], slot['x']+slot['width'], slot['y']+slot['height'])) rebuilt = Image.new('RGBA', profile.size) rebuilt.paste(sprite, (round(document['layouts'][profile][owner]['x']+slot['offsetX']), round(y+slot['offsetY']))) + assert canvas.target is not None image = rl.load_image_from_texture(canvas.target.texture) try: rl.image_flip_vertical(image) diff --git a/openpilot/starpilot/ui/tests/test_display_settings.py b/openpilot/starpilot/ui/tests/test_display_settings.py index 8a366b7100..3cf96a42b6 100644 --- a/openpilot/starpilot/ui/tests/test_display_settings.py +++ b/openpilot/starpilot/ui/tests/test_display_settings.py @@ -439,6 +439,7 @@ class DisplaySettingsTests(unittest.TestCase): self.assertIn("custom display is off", row.reason) page = replace(disabled, scroll=index // FEATURE_VISIBLE_ROWS * FEATURE_VISIBLE_ROWS) target = FeatureInput.target(800, feature_row_top(page) + (index % FEATURE_VISIBLE_ROWS + .5) * FEATURE_ROW_HEIGHT, page) + assert target is not None self.assertEqual(target.kind, "details") self.assertFalse(self.owner.apply(requests[row.key])) self.assertEqual(read_choice(self.params, row.key, large=True).value, values[row.key]) diff --git a/openpilot/starpilot/ui/tests/test_experimental_mode_persistence.py b/openpilot/starpilot/ui/tests/test_experimental_mode_persistence.py index 9955ec6d79..0ec962eed7 100644 --- a/openpilot/starpilot/ui/tests/test_experimental_mode_persistence.py +++ b/openpilot/starpilot/ui/tests/test_experimental_mode_persistence.py @@ -119,7 +119,11 @@ class TestExperimentalPersistence(unittest.TestCase): self.cp.pcmCruise = False large_panel._update_toggles() compact_panel._update_toggles() - self.assertTrue(large_panel._toggles["ExperimentalMode"].action_item.get_state()) + from openpilot.system.ui.widgets.list_view import ToggleAction + + action = large_panel._toggles["ExperimentalMode"].action_item + assert isinstance(action, ToggleAction) + self.assertTrue(action.get_state()) self.assertTrue(large_panel._toggles["ExperimentalMode"].action_item.enabled) self.assertTrue(compact_panel._experimental_btn._checked) self.assertTrue(compact_panel._experimental_btn.enabled) diff --git a/openpilot/starpilot/ui/tests/test_feature_settings_lateral.py b/openpilot/starpilot/ui/tests/test_feature_settings_lateral.py index 68bc7b3c73..39a3309191 100644 --- a/openpilot/starpilot/ui/tests/test_feature_settings_lateral.py +++ b/openpilot/starpilot/ui/tests/test_feature_settings_lateral.py @@ -1,5 +1,6 @@ """Saved Torque/AOL UI actions against real Params, CarParams and runtime parsers.""" from unittest.mock import Mock +from openpilot.common.test import require_value from openpilot.starpilot.ui.presentation import BitmapFonts @@ -121,7 +122,7 @@ class LateralFeatureSettingsTests(unittest.TestCase): tune.latAccelOffset, tune.friction) saved = read_torque_settings(self.params, vehicle) self.assertTrue(saved.valid) - self.assertIsNotNone(saved.user_factor) + assert saved.user_factor is not None self.assertIsNone(saved.user_friction) self.assertIsNone(self.params.get("AdvancedLateralTune")) self.assertIsNone(self.params.get("ForceAutoTuneOff")) @@ -309,7 +310,7 @@ class LateralFeatureSettingsTests(unittest.TestCase): self.assertTrue(read_aol_settings(self.params).enabled) self.assertFalse(self.cp.openpilotLongitudinalControl) tagged = build_ioniq6_hda2_long_candidate(self.cp, fp) - self.assertIsNotNone(tagged) + assert tagged is not None self.cp = tagged self.assertTrue(self.row("vehicle", "NostalgiaMode").available) tagged.safetyConfigs[0].safetyParam |= 0x800 @@ -336,7 +337,7 @@ class LateralFeatureSettingsTests(unittest.TestCase): self.cp = stock self.assertTrue(self.row("vehicle", "NostalgiaMode").available) tagged = build_ioniq6_hda2_long_candidate(stock, fp) - self.assertIsNotNone(tagged) + assert tagged is not None self.cp = tagged self.assertTrue(self.row("vehicle", "NostalgiaMode").available) tagged.safetyConfigs[0].safetyParam |= 0x800 @@ -541,7 +542,7 @@ class LateralFeatureSettingsTests(unittest.TestCase): self.assertEqual(parse_document(source)[str(self.cp.carFingerprint)].factor.mode, "custom") row = self.row("torque/developer", "torque:factor:reset") action = FeatureInput.target(1900, FEATURE_ROW_TOP + 77, FeatureSettingsState(page="torque", rows=(row,))) - self.assertIsNotNone(action) + assert action is not None assert action is not None self.assertEqual(action.kind, "change") self.assertEqual(action.row, row) @@ -600,7 +601,7 @@ class LateralFeatureSettingsTests(unittest.TestCase): self.assertEqual(state.rows[state.scroll].reason, "StarPilot’s FLM tuning will attempt to automatically correct torque profiles as you drive.") self.assertTrue(state.rows[state.scroll].available) - self.assertEqual(FeatureInput.target(650, 300, state).row, state.rows[state.scroll]) + self.assertEqual(require_value(FeatureInput.target(650, 300, state)).row, state.rows[state.scroll]) self.assertTrue(self.owner.apply(required_change(self.row("torque", "LateralControllerSelection")))) standard = self.owner.snapshot("torque", parked=True, system_long=True, lateral_context=True, metric=False) self.assertTrue(any(row.label == "Use StarPilot Auto Learn" for row in standard.rows)) diff --git a/openpilot/starpilot/ui/tests/test_feature_settings_navigation.py b/openpilot/starpilot/ui/tests/test_feature_settings_navigation.py index 3cfe520742..8497422064 100644 --- a/openpilot/starpilot/ui/tests/test_feature_settings_navigation.py +++ b/openpilot/starpilot/ui/tests/test_feature_settings_navigation.py @@ -7,6 +7,7 @@ from pathlib import Path import tempfile from types import SimpleNamespace as NS +from openpilot.common.test import require_value from openpilot.common.params import Params from openpilot.starpilot.longitudinal.profile_document import migrate_profile_document from openpilot.starpilot.ui import feature_settings_compact as compact @@ -331,7 +332,7 @@ class FeatureNavigationTests(unittest.TestCase): self.assertFalse(actions) controller.press(1990, feature_row_top(state) + 92, state) controller.release(1990, feature_row_top(state) + 92, state) - self.assertEqual(row_change(actions[0].row).expected, b"0") + self.assertEqual(require_value(row_change(actions[0].row)).expected, b"0") def test_swipes_page_from_controls_disabled_rows_and_blank_space(self): controls = (FeatureRow("switch", "Switch", "Off", choices=("Off", "On"), available=True), @@ -400,7 +401,7 @@ class FeatureNavigationTests(unittest.TestCase): actions = [] controller = FeatureInput(actions.append) controller.press(900, 1015, state) - self.assertIsNotNone(controller.held) + assert controller.held is not None controller.cancel_tap() controller.release(1800, 800, state) self.assertFalse(actions) @@ -534,7 +535,7 @@ class FeatureNavigationTests(unittest.TestCase): controller.release(x, feature_row_top(state) + 92, state) self.assertEqual(len(actions), 1) request = row_change(actions[0].row, actions[0].direction) - self.assertIsNotNone(request) + assert request is not None self.assertEqual((request.value, request.expected, request.dependencies), (desired, source, row.dependencies)) actions.clear() unavailable = replace(row, available=False) @@ -554,7 +555,7 @@ class FeatureNavigationTests(unittest.TestCase): master = page.rows[0] self.assertEqual(master.key, "CurveSpeedController") request = row_change(master) - self.assertIsNotNone(request) + assert request is not None if request is None: self.fail("the curve master has no action") self.assertTrue(owner.apply(request)) @@ -698,7 +699,7 @@ class FeatureNavigationTests(unittest.TestCase): owner = FeatureSettingsOwner(params, lambda _group: True, vehicle_fingerprint=lambda: "TOYOTA COROLLA TSS2") row = next(row for row in owner.snapshot("curve", parked=True, system_long=True, lateral_context=True, metric=False).rows if row.key == "curve_reset") - self.assertEqual(FeatureInput.target(1900, FEATURE_ROW_TOP + 77, FeatureSettingsState(page="curve", rows=(row,))).kind, "reset") + self.assertEqual(require_value(FeatureInput.target(1900, FEATURE_ROW_TOP + 77, FeatureSettingsState(page="curve", rows=(row,)))).kind, "reset") large = StarShellSession.__new__(StarShellSession) self.enterContext(patch.object(large, "feature_request", owner.apply)) pushed = [] diff --git a/openpilot/starpilot/ui/tests/test_feature_settings_visuals.py b/openpilot/starpilot/ui/tests/test_feature_settings_visuals.py index c23790a243..74ed4eda51 100644 --- a/openpilot/starpilot/ui/tests/test_feature_settings_visuals.py +++ b/openpilot/starpilot/ui/tests/test_feature_settings_visuals.py @@ -6,6 +6,7 @@ from types import SimpleNamespace import unittest from unittest.mock import Mock, patch +from openpilot.common.test import require_value from openpilot.starpilot.ui.raylib import rl from openpilot.starpilot.ui import clip, feature_settings as view, settings_geometry as geometry @@ -122,6 +123,7 @@ class FeatureVisualTests(unittest.TestCase): self.assertLessEqual(x + width, 2094.01) target = FeatureInput.target(x + width / 2, y + height / 2, state) if enabled: + assert target is not None self.assertEqual(target.direction, (-1 if value == "-" else 1) if value in ("-", "+") else index) else: self.assertIsNone(target) @@ -143,7 +145,9 @@ class FeatureVisualTests(unittest.TestCase): self.assertNotIn("-", text) for i, row in enumerate(rows): target = FeatureInput.target(800, feature_row_top(state) + i * FEATURE_ROW_HEIGHT + 77, state) + assert target is not None self.assertEqual(target.kind, "open") + assert target is not None self.assertEqual(target.row, row) def test_disabled_display_summaries_mute_labels_values_and_explain_the_master(self): @@ -169,6 +173,7 @@ class FeatureVisualTests(unittest.TestCase): self.assertIs(label.args[-1], geometry.TEXT_PRIMARY if available else geometry.TEXT_MUTED) self.assertIs(saved.args[-1], geometry.TEXT_SECONDARY if available else geometry.TEXT_MUTED) target = FeatureInput.target(800, feature_row_top(state) + (index + .5) * FEATURE_ROW_HEIGHT, state) + assert target is not None self.assertEqual(target.kind, "open" if available else "details") if not available: self.assertLess(label.args[4] + 33, explanations[index].args[4] + 6) @@ -221,9 +226,9 @@ class FeatureVisualTests(unittest.TestCase): self.assertGreater(by, last[1] + last[3]) self.assertEqual((bx, bw, bh), (cx, editor_width, 140)) self.assertEqual(bx + bw, cx + editor_width) - self.assertEqual(FeatureInput.target(bx + bw / 2, by + bh / 2, state).kind, "back") - self.assertEqual(FeatureInput.target(bx + 20, by + bh - 5, state).kind, "back") - self.assertEqual(FeatureInput.target(bx + bw - 20, by + bh - 5, state).kind, "back") + self.assertEqual(require_value(FeatureInput.target(bx + bw / 2, by + bh / 2, state)).kind, "back") + self.assertEqual(require_value(FeatureInput.target(bx + 20, by + bh - 5, state)).kind, "back") + self.assertEqual(require_value(FeatureInput.target(bx + bw - 20, by + bh - 5, state)).kind, "back") self.assertIsNone(FeatureInput.target(1900, by + bh + 10, state)) for index, (button, (x, y, width, height), enabled) in enumerate(value_buttons(state, row, feature_row_top(state))): label = "Mute" if button == "0" else button if button in ("-", "+", "Auto") else button + "%" @@ -233,12 +238,14 @@ class FeatureVisualTests(unittest.TestCase): self.assertAlmostEqual(drawn.args[3] + fonts.measure(*drawn.args[:3]).width / 2, x + width / 2, delta=.01) target = FeatureInput.target(x + width / 2, y + height / 2, state) if enabled: + assert target is not None self.assertEqual(target.kind, "change" if button in ("-", "+") else "action") + assert target is not None self.assertEqual(target.direction, (-1 if button == "-" else 1) if button in ("-", "+") else index) else: self.assertIsNone(target) self.assertEqual(value_buttons(replace(state, editor=False), row), ()) - self.assertEqual(FeatureInput.target(1300, feature_row_top(state) + 157, state).kind, "details") + self.assertEqual(require_value(FeatureInput.target(1300, feature_row_top(state) + 157, state)).kind, "details") self.assertIsNone(FeatureInput.target(1300, feature_row_top(state) + 330, state)) disabled = replace(state, rows=(replace(row, available=False),)) fonts.draw.reset_mock() @@ -459,12 +466,13 @@ class FeatureVisualTests(unittest.TestCase): for index, row in enumerate(rows): y = expected_top + (index + .5) * FEATURE_ROW_HEIGHT action = FeatureInput.target(1930, y, state) + assert action is not None self.assertEqual((action.kind, action.row), ("action", row)) self.assertEqual(separators[index].args[1], expected_top + (index + 1) * FEATURE_ROW_HEIGHT - 3) - self.assertEqual(FeatureInput.target(1930, expected_top + 5 * FEATURE_ROW_HEIGHT, state).kind, "scroll") + self.assertEqual(require_value(FeatureInput.target(1930, expected_top + 5 * FEATURE_ROW_HEIGHT, state)).kind, "scroll") gap = FeatureInput.target(1930, 108, state) self.assertEqual(gap.kind if gap else None, "details" if subtitle else None) - self.assertEqual(FeatureInput.target(1930, 1015, state).kind, "scroll") + self.assertEqual(require_value(FeatureInput.target(1930, 1015, state)).kind, "scroll") descriptions = [call for call in fonts.draw.call_args_list if call.args[0] == subtitle] self.assertEqual(len(descriptions), int(bool(subtitle))) if descriptions: @@ -509,7 +517,7 @@ class FeatureVisualTests(unittest.TestCase): self.assertEqual(FeatureInput.target(2000, y, state), FeatureUiAction("change", row) if available else None) self.assertIsNone(FeatureInput.target(1730, y, state)) invalid = replace(state, rows=(replace(row, value="Invalid saved choice", repair_value="Off"),)) - self.assertEqual(FeatureInput.target(2000, y, invalid).kind, "open") + self.assertEqual(require_value(FeatureInput.target(2000, y, invalid)).kind, "open") def test_toggle_stars_only_for_editable_on_and_thumb_keeps_saved_position(self): self.drawing() @@ -614,7 +622,9 @@ class FeatureVisualTests(unittest.TestCase): state = FeatureSettingsState(rows=rows, scroll=scroll) for index in range(min(FEATURE_VISIBLE_ROWS, count - scroll)): action = FeatureInput.target(600, FEATURE_ROW_TOP + (index + .5) * FEATURE_ROW_HEIGHT, state) + assert action is not None self.assertEqual(action.kind, "open") + assert action is not None reached.append(action.row) next_scroll = feature_scroll(scroll, 1, count) if next_scroll == scroll: @@ -675,10 +685,10 @@ class FeatureVisualTests(unittest.TestCase): def test_numeric_value_is_read_only_and_buttons_keep_source_binding(self): row = FeatureRow("number", "Number", "75", b"75", step=5, available=True) state = FeatureSettingsState(rows=(row,)) - self.assertEqual(FeatureInput.target(1930, FEATURE_ROW_TOP + 50, state).kind, "details") - self.assertEqual(FeatureInput.target(1820, FEATURE_ROW_TOP + 140, state).direction, -1) - self.assertEqual(FeatureInput.target(2000, FEATURE_ROW_TOP + 140, state).direction, 1) - self.assertEqual(FeatureInput.target(1925, FEATURE_ROW_TOP + 140, state).kind, "details") + self.assertEqual(require_value(FeatureInput.target(1930, FEATURE_ROW_TOP + 50, state)).kind, "details") + self.assertEqual(require_value(FeatureInput.target(1820, FEATURE_ROW_TOP + 140, state)).direction, -1) + self.assertEqual(require_value(FeatureInput.target(2000, FEATURE_ROW_TOP + 140, state)).direction, 1) + self.assertEqual(require_value(FeatureInput.target(1925, FEATURE_ROW_TOP + 140, state)).kind, "details") self.assertIsNone(FeatureInput.target(2000, FEATURE_ROW_TOP + 140, replace(state, rows=(replace(row, available=False),)))) actions = [] owner = FeatureInput(actions.append) @@ -723,7 +733,7 @@ class FeatureVisualTests(unittest.TestCase): self.assertEqual(header[0].args[3], left + 34 if expanded else left + 28) self.assertTrue(all(call.args[1:3] == (FontRole.MEDIUM, 44) for call in header)) self.assertEqual(len({call.args[4] for call in header}), 1) - self.assertNotEqual(FeatureInput.target(left + 60, 120, state).kind, "back") + self.assertNotEqual(require_value(FeatureInput.target(left + 60, 120, state)).kind, "back") for x in (left + 60, left + 207): self.assertEqual(FeatureInput.target(x, 76, state), None if expanded else FeatureUiAction("back")) self.assertIsNone(FeatureInput.target(left + 208, 76, state)) diff --git a/openpilot/starpilot/ui/tests/test_global_feature_presentation.py b/openpilot/starpilot/ui/tests/test_global_feature_presentation.py index 1ecb8cea8e..0e4471f4fa 100644 --- a/openpilot/starpilot/ui/tests/test_global_feature_presentation.py +++ b/openpilot/starpilot/ui/tests/test_global_feature_presentation.py @@ -54,7 +54,7 @@ class TestGlobalFeaturePresentation(unittest.TestCase): self.params.put('DistanceButtonControl', 6, block=True) snapshot = ConditionalSettingsOwner(self.params).refresh(NOW) mapping = read_button_map(self.params, include_ioniq_media=True, cp=cp) - self.assertIsNotNone(mapping) + assert mapping is not None event = receipt(settings_fingerprint(snapshot), '' if controller_source else mapping.fingerprint()).as_builder() event.slcState.trafficMode.controllerSource = controller_source if controller_source: @@ -75,6 +75,7 @@ class TestGlobalFeaturePresentation(unittest.TestCase): with mock.patch('openpilot.starpilot.ui.runtime_snapshot.paired_clocks_ns', return_value=(NOW, BOOT, 0)): state = adapter.build(ShellMode.ONROAD, now_ns=NOW).onroad self.assertTrue(state.traffic_mode) + assert state.traffic_display is not None self.assertEqual((state.traffic_display.state, state.traffic_display.label), ('active', 'TRAFFIC')) self.assertFalse(adapter.build(ShellMode.ONROAD, now_ns=NOW + 100_000_001).onroad.traffic_mode) @@ -147,7 +148,7 @@ class TestGlobalFeaturePresentation(unittest.TestCase): rows = owner.snapshot('lane', parked=True, system_long=True, lateral_context=True, metric=False).rows row = next(row for row in rows if row.key == 'LaneCentering') request = row_change(row, 1) - self.assertIsNotNone(request) + assert request is not None assert request is not None self.assertTrue(row.available) self.assertTrue(owner.apply(request)) @@ -218,7 +219,7 @@ class TestGlobalFeaturePresentation(unittest.TestCase): # Use this test's drive identifier in the exact original wire checks. sm['deviceState'].startedMonoTime = DRIVE command = WheelConsumer().accept(event, self.params, cp, sm, now_ns=when) - self.assertIsNotNone(command) + assert command is not None self.assertEqual((command.key, command.action), ('DistanceButtonControl', ACTIONS[option])) self.params.put('DistanceButtonControl', 0, block=True) self.assertIsNone(WheelConsumer().accept(event, self.params, cp, sm, now_ns=when)) diff --git a/openpilot/starpilot/ui/tests/test_home_actions.py b/openpilot/starpilot/ui/tests/test_home_actions.py index 2d744e8776..1da63caa82 100644 --- a/openpilot/starpilot/ui/tests/test_home_actions.py +++ b/openpilot/starpilot/ui/tests/test_home_actions.py @@ -102,9 +102,11 @@ class TestHomeActions(unittest.TestCase): def test_nested_view_data_is_immutable(self): with self.assertRaises(FrozenInstanceError): + assert self.state.stats is not None self.state.stats.all_time.__setattr__("drives", 5) with self.assertRaises(FrozenInstanceError): self.state.__setattr__("experimental_enabled", True) + assert self.state.stats is not None self.assertIsInstance(self.state.stats.records, tuple) diff --git a/openpilot/starpilot/ui/tests/test_home_stats_source.py b/openpilot/starpilot/ui/tests/test_home_stats_source.py index 1b855cf8fa..318a628ee1 100644 --- a/openpilot/starpilot/ui/tests/test_home_stats_source.py +++ b/openpilot/starpilot/ui/tests/test_home_stats_source.py @@ -32,16 +32,27 @@ class TestHomeStatsSource(unittest.TestCase): with patch('openpilot.starpilot.galaxy.drive_stats.DriveHistory.snapshot', side_effect=AssertionError('No log scans')): imperial = read_home_stats(False, store=path, clock=lambda: NOW) metric = read_home_stats(True, store=path, clock=lambda: NOW) + assert imperial is not None self.assertEqual((imperial.all_time.drives, imperial.all_time.distance, imperial.all_time.hours), (3, 3., 3.)) + assert imperial is not None self.assertEqual((imperial.past_week.drives, imperial.this_week.drives), (2, 1)) + assert metric is not None self.assertAlmostEqual(metric.all_time.distance, 4.828032) + assert metric is not None self.assertEqual(metric.all_time.unit, 'kilometers') + assert imperial is not None self.assertEqual(imperial.all_time.unit, 'miles') + assert imperial is not None self.assertEqual(len(imperial.daily_distance), 7) + assert imperial is not None self.assertTrue(imperial.daily_distance[0].is_today) + assert imperial is not None self.assertEqual(imperial.daily_distance[0].distance, 1.) + assert imperial is not None self.assertTrue(imperial.daily_distance[1].is_future) + assert imperial is not None self.assertEqual(imperial.records[0].value, '1.0') + assert imperial is not None self.assertEqual(imperial.records[0].detail, 'miles') self.assertEqual(path.read_bytes(), original) diff --git a/openpilot/starpilot/ui/tests/test_lane_change_feature.py b/openpilot/starpilot/ui/tests/test_lane_change_feature.py index f8162de682..b77aa43800 100644 --- a/openpilot/starpilot/ui/tests/test_lane_change_feature.py +++ b/openpilot/starpilot/ui/tests/test_lane_change_feature.py @@ -10,6 +10,7 @@ from unittest.mock import Mock, patch from opendbc.car.car_helpers import interfaces from opendbc.car.hyundai.values import CAR as HYUNDAI +from openpilot.common.test import require_value from openpilot.common.params import Params from openpilot.starpilot.lateral.lane_change_preferences import KEY, LaneChangePolicy, decode, effective, read_saved, to_value from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner @@ -104,7 +105,7 @@ class LaneChangeFeatureTests(unittest.TestCase): def request(self, row, direction=1): request = row_change(row, direction) - self.assertIsNotNone(request) + assert request is not None return FeatureSettingsRequest(request.key, request.expected, request.value, confirmation=True, vehicle_fingerprint=request.vehicle_fingerprint, capability=request.capability, dependencies=request.dependencies, display_unit=request.display_unit) @@ -138,7 +139,7 @@ class LaneChangeFeatureTests(unittest.TestCase): self.assertEqual(speed.unit, "mph") self.assertEqual(speed.value, "5.0") unconfirmed = row_change(speed) - self.assertIsNotNone(unconfirmed) + assert unconfirmed is not None assert unconfirmed is not None self.assertFalse(self.owner.apply(unconfirmed)) self.assertTrue(self.owner.apply(self.request(speed))) @@ -329,7 +330,7 @@ class LaneChangeFeatureTests(unittest.TestCase): if len(raw) > 512: self.assertFalse(self.row(RESET).available) self.assertEqual(to_value(LaneChangePolicy())["version"], 7) - self.assertFalse(decode(b'{"version":1,"enabled":true,"minimumSpeedMps":8.9408,"onePerSignal":false}').auto_lane_change) + self.assertFalse(require_value(decode(b'{"version":1,"enabled":true,"minimumSpeedMps":8.9408,"onePerSignal":false}')).auto_lane_change) with self.assertRaises(ValueError): to_value(LaneChangePolicy(minimum_speed_mps=int("9" * 350))) diff --git a/openpilot/starpilot/ui/tests/test_lane_strength_native.py b/openpilot/starpilot/ui/tests/test_lane_strength_native.py index 9336f95dd6..94172d6ac1 100644 --- a/openpilot/starpilot/ui/tests/test_lane_strength_native.py +++ b/openpilot/starpilot/ui/tests/test_lane_strength_native.py @@ -3,6 +3,7 @@ from dataclasses import replace import unittest from unittest.mock import Mock, patch +from openpilot.common.test import require_value from openpilot.starpilot.ui.feature_settings_state import ( FeatureRow, lane_strength_level, row_change, row_default, value_reason, value_text, ) @@ -32,7 +33,7 @@ class TestNativeLaneStrength(unittest.TestCase): for percent, direction, expected in ((100, -1, '83'), (100, 1, '120'), (33, 1, '50'), (200, -1, '180')): row = self.row(percent) request = row_change(row, direction) - self.assertIsNotNone(request) + assert request is not None self.assertEqual(request.value, expected) self.assertEqual(request.expected, row.source) self.assertEqual(request.vehicle_fingerprint, row.vehicle_fingerprint) @@ -41,8 +42,8 @@ class TestNativeLaneStrength(unittest.TestCase): self.assertIsNone(row_change(self.row(33), -1)) self.assertIsNone(row_change(self.row(200), 1)) self.assertIsNone(row_change(replace(self.row(), available=False), 1)) - self.assertEqual(row_default(self.row()).value, '100') - self.assertEqual(row_change(replace(self.row(), key='OtherStrength'), 1).value, '101.0') + self.assertEqual(require_value(row_default(self.row())).value, '100') + self.assertEqual(require_value(row_change(replace(self.row(), key='OtherStrength'), 1)).value, '101.0') def test_actual_compact_buttons_display_and_dispatch(self): from openpilot.starpilot.ui import feature_settings_compact as compact diff --git a/openpilot/starpilot/ui/tests/test_layout_preview_renderer.py b/openpilot/starpilot/ui/tests/test_layout_preview_renderer.py index 45933117ec..f6d15c5467 100644 --- a/openpilot/starpilot/ui/tests/test_layout_preview_renderer.py +++ b/openpilot/starpilot/ui/tests/test_layout_preview_renderer.py @@ -174,8 +174,10 @@ class LayoutPreviewRendererTests(unittest.TestCase): with self.subTest(scene=scene): sample = sample_state(scene, document) self.assertTrue(sample.experimental_enabled) + assert sample.visual_preview is not None self.assertEqual(sample.visual_preview.cem_reason, reason) self.assertIsNone(sample.conditional_effective) + assert sample.visual_preview is not None self.assertTrue(sample.visual_preview.layout_sample) # Drawn as the car would, without replay labels. from openpilot.starpilot.ui.onroad_conditional import status # The gauge still reads the real reason, but the mode caption itself is not drawn in the editor. @@ -254,11 +256,17 @@ class LayoutPreviewRendererTests(unittest.TestCase): torque_bar=NS(_torque_filter=NS(x=0.0), _alpha_filter=NS(x=0.0))), create=True)) braking = sample_state("braking", default_document()) canvas._settle(braking) + assert canvas.view is not None self.assertTrue(canvas.view.compact_hud._was_cruise_active) + assert canvas.view is not None self.assertEqual(canvas.view.compact_hud._set_speed_alpha.x, 1.0) + assert canvas.view is not None self.assertGreater(canvas.view.compact_hud._wheel_alpha.x, 200) + assert canvas.view is not None self.assertEqual(canvas.view.compact_hud._wheel_y.x, 0.0) + assert canvas.view is not None self.assertEqual(canvas.view.torque_bar._torque_filter.x, braking.torque_utilization) + assert canvas.view is not None self.assertEqual(canvas.view.torque_bar._alpha_filter.x, 1.0) def test_preview_uses_runtime_monitor_occlusion_for_default_and_moved_widgets(self): @@ -286,6 +294,7 @@ class LayoutPreviewRendererTests(unittest.TestCase): matrix.reset_mock() canvas.monitor.renderer._render.reset_mock() state.customization["layouts"]["compact"]["driver_monitor"].update(x=16, y=10) + assert canvas.view is not None canvas.view.compact_hud._set_speed_alpha.x = 0.0 canvas._render_driver_monitor(rl.Rectangle(), state) canvas.monitor.renderer._render.assert_called_once() diff --git a/openpilot/starpilot/ui/tests/test_long_profile_feature.py b/openpilot/starpilot/ui/tests/test_long_profile_feature.py index 9fb525108e..742d84319e 100644 --- a/openpilot/starpilot/ui/tests/test_long_profile_feature.py +++ b/openpilot/starpilot/ui/tests/test_long_profile_feature.py @@ -7,6 +7,7 @@ import tempfile import unittest from unittest.mock import patch +from openpilot.common.test import require_value from openpilot.common.params import Params from openpilot.starpilot.longitudinal.profile_preferences import SCALARS, read_profile_health from openpilot.starpilot.longitudinal.profile_runtime import read_settings @@ -87,7 +88,7 @@ class LongProfileFeatureTests(unittest.TestCase): master = self.row("profiles", "CustomPersonalities") self.assertTrue(master.available) request = row_change(master) - self.assertIsNotNone(request) + assert request is not None assert request is not None self.assertTrue(self.owner.apply(request)) self.assertIsNotNone(read_settings(self.params)) @@ -144,7 +145,7 @@ class LongProfileFeatureTests(unittest.TestCase): master = self.row("profiles", "CustomPersonalities") self.assertTrue(master.available) request = row_change(master) - self.assertIsNotNone(request) + assert request is not None assert request is not None self.assertTrue(self.owner.apply(request)) self.assertFalse(self.params.get_bool("CustomPersonalities")) @@ -160,7 +161,7 @@ class LongProfileFeatureTests(unittest.TestCase): master = self.row("profiles", "CustomPersonalities") self.assertTrue(master.available) request = row_change(master) - self.assertIsNotNone(request) + assert request is not None assert request is not None self.assertTrue(self.owner.apply(request)) self.assertFalse(self.params.get_bool("CustomPersonalities")) @@ -212,7 +213,7 @@ class LongProfileFeatureTests(unittest.TestCase): state = self.owner.snapshot("aggressive", parked=True, system_long=True, lateral_context=True, metric=False) index = next(i for i, row in enumerate(state.rows) if row.key == "long_repair:AggressiveFollow") state = replace(state, scroll=index) - self.assertEqual(FeatureInput.target(1900, feature_row_top(state) + 77, state).kind, "reset") + self.assertEqual(require_value(FeatureInput.target(1900, feature_row_top(state) + 77, state)).kind, "reset") def test_compact_native_confirmation_routes_captured_request(self): self.path("AggressiveFollow").write_bytes(b"broken") diff --git a/openpilot/starpilot/ui/tests/test_maps.py b/openpilot/starpilot/ui/tests/test_maps.py index 21f0323d32..027330ba08 100644 --- a/openpilot/starpilot/ui/tests/test_maps.py +++ b/openpilot/starpilot/ui/tests/test_maps.py @@ -29,7 +29,7 @@ class TestMaps(unittest.TestCase): self.assertEqual(page.rows[2].value, "3 / 12 groups") self.assertTrue(all(not row.available and not row.page for row in page.rows)) hit = FeatureInput.target(1980, 150, page) - self.assertIsNotNone(hit) + assert hit is not None assert hit is not None self.assertEqual(hit.kind, "details") self.assertIsNone(hit.row) @@ -51,12 +51,14 @@ class TestMaps(unittest.TestCase): try: self.assertEqual(source.snapshot().rows[0].value, "Unavailable") wait.set() + assert source.pending is not None source.pending.result(timeout=1) self.assertEqual(source.snapshot().rows[0].value, "Transferring") self.assertEqual(len(calls), 1) now[0] = source.REFRESH_NS source.snapshot() with self.assertRaises(OSError): + assert source.pending is not None source.pending.result(timeout=1) self.assertEqual(source.snapshot().rows[0].value, "Unavailable") finally: @@ -75,6 +77,7 @@ class TestMaps(unittest.TestCase): session.map_snapshot.assert_not_called() visible.return_value = page compact.refresh_visible(page) + assert page.current is not None self.assertEqual(page.current.rows[0].value, "Transferring") self.assertIn("open galaxy", page._scroller.add_widgets.call_args.args[0][-1][1]) diff --git a/openpilot/starpilot/ui/tests/test_models.py b/openpilot/starpilot/ui/tests/test_models.py index 7e42e6710e..3bf26c0e57 100644 --- a/openpilot/starpilot/ui/tests/test_models.py +++ b/openpilot/starpilot/ui/tests/test_models.py @@ -6,6 +6,7 @@ from types import SimpleNamespace from typing import cast from unittest import mock +from openpilot.common.test import require_value from openpilot.starpilot.models.catalog import BUNDLED_CURRENT, BY_ID from openpilot.starpilot.models.status import ModelHealth, ModelStatus, ModelVariant from openpilot.starpilot.ui.feature_settings_state import (feature_action_rects, feature_page_rows, feature_row_top, feature_scroll, toolbar_rects, @@ -59,7 +60,7 @@ class TestModelPage(unittest.TestCase): self.assertTrue(all(not row.available and not row.page for row in page.rows)) self.assertIsNone(FeatureInput.target(1980, 300, page)) self.assertIsNone(FeatureInput.target(600, 60, page)) - self.assertEqual(FeatureInput.target(100, 60, replace(page, sidebar_expanded=False)).kind, "back") + self.assertEqual(require_value(FeatureInput.target(100, 60, replace(page, sidebar_expanded=False))).kind, "back") def test_missing_receipt_does_not_look_active(self): status = ModelStatus(BUNDLED_CURRENT, None, None, ModelHealth.IDENTITY_UNAVAILABLE, @@ -176,6 +177,8 @@ class TestModelManager(unittest.TestCase): self.assertEqual(state.rows[0].actions, (("Small", True), ("Big", True))) x, y, width, height = feature_action_rects(state.rows[0], feature_row_top(state))[1] action = FeatureInput.target(x + width / 2, y + height / 2, state) + assert action is not None + assert action.row is not None self.assertEqual((action.kind, action.row.key, action.direction), ("action", "models:active", 1)) self.assertEqual([row.label for row in state.rows[:3]], ["Active Models", "Model Randomizer", "Model Catalog"]) self.assertTrue(all(not row.available for row in state.rows[3:])) @@ -220,6 +223,7 @@ class TestModelManager(unittest.TestCase): self.assertEqual(feature_page_rows(catalog), 4) self.assertEqual(feature_scroll(0, 1, 9, feature_page_rows(catalog)), 4) first = FeatureInput.target(1000, feature_row_top(catalog) + 77, catalog) + assert first is not None self.assertEqual((first.kind, first.row), ("details", catalog.rows[0])) self.assertEqual(model_request(self.data, "download", "missing", allow_gpu=True), ("download", {"model": "missing", "allowGpuWithoutGpu": True})) diff --git a/openpilot/starpilot/ui/tests/test_onroad_axes.py b/openpilot/starpilot/ui/tests/test_onroad_axes.py index 99fe013c78..5508aa4335 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_axes.py +++ b/openpilot/starpilot/ui/tests/test_onroad_axes.py @@ -348,7 +348,9 @@ class TestOnroadAxes(unittest.TestCase): self.assertEqual(slowing.e2e_slowdown, 'Lead vehicle') self.assertEqual(driving_mode_description(slowing), 'E2E · Lead vehicle') from openpilot.starpilot.ui.onroad_cem_gauge import IndicatorType, gauge_data - self.assertEqual(gauge_data(slowing).indicator_type, IndicatorType.LEAD) + gauge = gauge_data(slowing) + assert gauge is not None + self.assertEqual(gauge.indicator_type, IndicatorType.LEAD) self.assertEqual(rgba(axis_status_color(slowing)), (218, 111, 37, 255)) self.assertEqual(rgba(axis_status_color(replace(combined, longitudinal_active=False))), (10, 186, 181, 255)) self.assertEqual(rgba(axis_status_color(replace(combined, lateral_active=False))), (255, 105, 180, 255)) diff --git a/openpilot/starpilot/ui/tests/test_onroad_customization.py b/openpilot/starpilot/ui/tests/test_onroad_customization.py index 872c13fe15..429092f2e2 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_customization.py +++ b/openpilot/starpilot/ui/tests/test_onroad_customization.py @@ -31,6 +31,7 @@ def test_lead_marker_color_is_optional_and_kept_per_profile(): assert 'leadMarker' not in saved['roadColors']['compact'] assert saved['roadColors']['large']['leadMarker'] == '#22CCFF80' color = lead_marker_color(saved['roadColors']['large'], .5) + assert color is not None assert (color.r, color.g, color.b, color.a) == (34, 204, 255, 64) doc['roadColors']['large']['leadMarker'] = 'red' with pytest.raises(ValueError): diff --git a/openpilot/starpilot/ui/tests/test_onroad_dm.py b/openpilot/starpilot/ui/tests/test_onroad_dm.py index 997f2e9ecb..3154ef88da 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_dm.py +++ b/openpilot/starpilot/ui/tests/test_onroad_dm.py @@ -256,23 +256,28 @@ class TestDriverMonitor(unittest.TestCase): native = NS(sm=sources, started_frame=10, is_onroad=lambda: True) with patch.object(runtime_app, 'ui_state', native), patch.object(runtime_app.time, 'monotonic_ns', return_value=now): session._render_driver_monitor(None, road()) + assert session._driver_monitor_layer is not None self.assertTrue(session._driver_monitor_layer.render.call_args.kwargs['fresh']) for service in ('driverMonitoringState', 'driverStateV2'): with self.subTest(service=service): sources.recv_frame[service] = 10 session._render_driver_monitor(None, road()) + assert session._driver_monitor_layer is not None self.assertFalse(session._driver_monitor_layer.render.call_args.kwargs['fresh']) sources.recv_frame[service] = 11 sources.logMonoTime[service] = now - 1_000_000_000 session._render_driver_monitor(None, road()) + assert session._driver_monitor_layer is not None self.assertFalse(session._driver_monitor_layer.render.call_args.kwargs['fresh']) sources.logMonoTime[service] = now sources.valid[service] = False session._render_driver_monitor(None, road()) + assert session._driver_monitor_layer is not None self.assertFalse(session._driver_monitor_layer.render.call_args.kwargs['fresh']) sources.valid[service] = True sources.logMonoTime['selfdriveState'] = now - 1_000_000_000 session._render_driver_monitor(None, road()) + assert session._driver_monitor_layer is not None self.assertTrue(session._driver_monitor_layer.render.call_args.kwargs['fresh']) def test_saved_layout_migration_keeps_exact_original_bytes_as_commit_source(self): diff --git a/openpilot/starpilot/ui/tests/test_onroad_favorites.py b/openpilot/starpilot/ui/tests/test_onroad_favorites.py index 3cb25be36d..6a608ea159 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_favorites.py +++ b/openpilot/starpilot/ui/tests/test_onroad_favorites.py @@ -504,10 +504,12 @@ class TestOnroadFavorites(unittest.TestCase): with patch.object(runtime_app, 'ui_state', native), patch.object(runtime_app, '_slc_action_publisher') as publisher: action = session.native_favorite_actions(Mock(), Mock(), experimental)[EXPERIMENTAL] assert action.available and action.invoke() + assert session.conditional_actions is not None args = session.conditional_actions.dispatch.call_args.args assert args == (context, native.sm, native.CP, publisher.return_value) experimental.assert_not_called() assert action.token == session.native_favorite_actions(Mock(), Mock(), experimental)[EXPERIMENTAL].token + assert session.conditional_actions is not None session.conditional_actions.context.return_value = NS(token='changed-settings') assert action.token != session.native_favorite_actions(Mock(), Mock(), experimental)[EXPERIMENTAL].token session._favorite_authority.return_value = False @@ -518,6 +520,7 @@ class TestOnroadFavorites(unittest.TestCase): native.params.get_bool = lambda key: False session._conditional_favorite_active.return_value = False assert not action.invoke() + assert session.conditional_actions is not None assert session.conditional_actions.dispatch.call_count == 1 experimental.assert_not_called() diff --git a/openpilot/starpilot/ui/tests/test_onroad_lane_alerts.py b/openpilot/starpilot/ui/tests/test_onroad_lane_alerts.py index cbe6767de1..cbae9f90b2 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_lane_alerts.py +++ b/openpilot/starpilot/ui/tests/test_onroad_lane_alerts.py @@ -2,7 +2,7 @@ from types import SimpleNamespace as NS import pytest -from openpilot.selfdrive.selfdrived.events import EVENTS, ET, EventName +from openpilot.selfdrive.selfdrived.events import Alert, EVENTS, ET, EventName from openpilot.starpilot.ui.onroad_lane_alerts import lateral_lane_alert from openpilot.starpilot.ui.onroad_state import AlertSize, OnroadAlert @@ -25,6 +25,7 @@ def test_lateral_only_uses_original_warning_text(state, direction, blocked, even data['car'].leftBlindspot = blocked alert = lateral_lane_alert(OnroadAlert(), **data) native = EVENTS[getattr(EventName, event)][ET.WARNING] + assert isinstance(native, Alert) assert (alert.text1, alert.text2, alert.alert_type) == (native.alert_text_1, native.alert_text_2, event + '/warning') diff --git a/openpilot/starpilot/ui/tests/test_onroad_map.py b/openpilot/starpilot/ui/tests/test_onroad_map.py index df1f777daf..92db495f2f 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_map.py +++ b/openpilot/starpilot/ui/tests/test_onroad_map.py @@ -12,6 +12,7 @@ from unittest.mock import Mock, patch import numpy as np import pytest +from openpilot.common.test import require_value from openpilot.starpilot.navigation.offline_roads import TileStore from openpilot.starpilot.navigation.road_tiles import ( DATA_ZOOM, EXTENT, MAJOR, MINOR, MOTORWAY, STREET, TileKey, decode_road_tile, encode_road_tile, lat_lon, world_xy, @@ -49,7 +50,7 @@ def test_line_strip_culls_offscreen_lines_and_caps_spikes(): def test_split_route_at_the_car(): route = np.array([[0, 0], [0, 10], [10, 10]], float) done, ahead = split_route(route, (0.5, 4.0)) - assert done.tolist() == [[0, 0], [0, 4]] and ahead.tolist() == [[0, 4], [0, 10], [10, 10]] + assert require_value(done).tolist() == [[0, 0], [0, 4]] and require_value(ahead).tolist() == [[0, 4], [0, 10], [10, 10]] assert split_route(None, (0, 0)) == (None, None) @@ -383,10 +384,10 @@ def test_map_feed_uses_navigation_gps_choice_with_car_fallback(monkeypatch): assert feed.read().fix is None sm.put("starpilotCarState", now - 200_000_000, latitude=36.2) fix = feed.read().fix - assert fix.latitude == 36.2 and fix.monotonic == (now - 200_000_000) / 1e9, "the car's GPS when no receiver has a fix" + assert require_value(fix).latitude == 36.2 and require_value(fix).monotonic == (now - 200_000_000) / 1e9, "the car's GPS when no receiver has a fix" sm.put("gpsLocationExternal", now - 100_000_000, latitude=36.3, bearingAccuracyDeg=200.0) fix = feed.read().fix - assert fix.latitude == 36.3 and fix.bearing is None, "a receiver wins; an unusable heading is dropped" + assert require_value(fix).latitude == 36.3 and require_value(fix).bearing is None, "a receiver wins; an unusable heading is dropped" nav = sm.ns(version=2, enabled=True, status="guiding", frameMonoTime=now, destinationName="Home", instruction=sm.ns(distanceMeters=120.0), route=[sm.ns(latitude=36.1, longitude=-115.1)]) published = {"starpilotNavigation": sm.ns(navigation=nav)} diff --git a/openpilot/starpilot/ui/tests/test_onroad_navigation.py b/openpilot/starpilot/ui/tests/test_onroad_navigation.py index 786e82d2d0..5f5b649903 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_navigation.py +++ b/openpilot/starpilot/ui/tests/test_onroad_navigation.py @@ -3,6 +3,7 @@ from datetime import datetime from types import SimpleNamespace as NS from unittest.mock import Mock, patch +from openpilot.common.test import require_value from openpilot.starpilot.ui.raylib import rl import pytest @@ -73,7 +74,7 @@ def test_bad_distance_and_empty_instruction_do_not_render(): nav.instruction.text = ' ' assert navigation_display(nav, now_ns=NOW, drive_id=DRIVE) is None nav.status = 'arrived' - assert navigation_display(nav, now_ns=NOW, drive_id=DRIVE).text == 'You have arrived' + assert require_value(navigation_display(nav, now_ns=NOW, drive_id=DRIVE)).text == 'You have arrived' def test_reaching_the_arrive_maneuver_reads_arrived_before_the_car_stops(): @@ -291,7 +292,7 @@ def test_then_maneuver_comes_from_the_next_instruction_and_card_shows_it_when_cl nav = navigation_display(result, now_ns=NOW, drive_id=DRIVE) assert nav is not None assert (nav.then_type, nav.then_modifier, nav.then_distance_m) == ('turn', 'right', 300.) - assert navigation_display(message(), now_ns=NOW, drive_id=DRIVE).then_type == '' + assert require_value(navigation_display(message(), now_ns=NOW, drive_id=DRIVE)).then_type == '' fonts = Mock(profile=Profile.LARGE) fonts.measure.side_effect = lambda text, role, size: NS(width=len(text) * size * .48) card = NavigationCard(fonts, clock=lambda: datetime(2026, 10, 7, 15, 42)) @@ -332,9 +333,9 @@ def test_lanes_are_read_from_the_instruction(): result = message() result.instruction = {**result.instruction.to_dict(), 'lanes': [ {'active': False, 'directions': ['straight']}, {'active': True, 'directions': ['straight', 'right'], 'activeDirection': 'right'}]} - assert navigation_display(result, now_ns=NOW, drive_id=DRIVE).lanes == ( + assert require_value(navigation_display(result, now_ns=NOW, drive_id=DRIVE)).lanes == ( (False, ('straight',), ''), (True, ('straight', 'right'), 'right')) - assert navigation_display(message(), now_ns=NOW, drive_id=DRIVE).lanes == () + assert require_value(navigation_display(message(), now_ns=NOW, drive_id=DRIVE)).lanes == () def test_lane_strip_shows_near_the_turn_and_replaces_the_then_chip(): diff --git a/openpilot/starpilot/ui/tests/test_pip_settings.py b/openpilot/starpilot/ui/tests/test_pip_settings.py index 198abe0bf1..729e8a3d2e 100644 --- a/openpilot/starpilot/ui/tests/test_pip_settings.py +++ b/openpilot/starpilot/ui/tests/test_pip_settings.py @@ -34,7 +34,7 @@ class PiPSettingsTests(unittest.TestCase): def test_absence_is_default_off_and_reader_does_not_write(self): saved = read_pip(self.params) self.assertFalse(saved.enabled) - self.assertIsNotNone(saved.mask) + assert saved.mask is not None self.assertIsNone(saved.source(MASK)[0]) self.assertEqual(self.row(ENABLED).value, "Off") self.assertEqual(self.params.get_type(MASK).name, "JSON") @@ -133,7 +133,9 @@ class PiPSettingsTests(unittest.TestCase): dependencies=row.dependencies) self.assertTrue(self.owner.apply(request)) saved = read_pip(self.params) + assert saved.mask is not None self.assertEqual(saved.mask.center_left, (320.0, 550.0)) + assert saved.mask is not None self.assertIsNone(saved.mask.center_right) self.assertFalse(self.owner.apply(request)) self.assertIsNone(saved.source(ENABLED)[0]) diff --git a/openpilot/starpilot/ui/tests/test_pip_sidecam.py b/openpilot/starpilot/ui/tests/test_pip_sidecam.py index 06f215365b..ca9685ce94 100644 --- a/openpilot/starpilot/ui/tests/test_pip_sidecam.py +++ b/openpilot/starpilot/ui/tests/test_pip_sidecam.py @@ -3,6 +3,7 @@ from dataclasses import dataclass from contextlib import nullcontext from types import SimpleNamespace +from openpilot.common.test import require_value from openpilot.starpilot.ui.onroad_customization import default_document from unittest.mock import patch from unittest.mock import Mock @@ -458,6 +459,7 @@ def test_renderer_close_releases_every_gpu_and_ipc_resource_once(): assert textures == [1, 2, 3] assert shaders == [9] assert images == [first, second] + assert isinstance(renderer.stream, PiPStream) assert not renderer.stream.connected @@ -788,7 +790,7 @@ def test_camera_resolution_adaptation_preserves_saved_crop_and_side_identity(): assert changed is not None and changed.width == 1344 and changed.height == 760 assert changed.center_left == (315 * 1344 / 1928, 548 * 760 / 1208) assert changed.center_right == (1571 * 1344 / 1928, 539 * 760 / 1208) - assert changed.crop('right').x == changed.center_left[0] - changed.crop_size / 2 + assert require_value(changed.crop('right')).x == changed.center_left[0] - changed.crop_size / 2 assert mask.width == 1928 and mask.center_left == (315, 548) assert mask.for_frame(1928, 1208) is mask assert mask.for_frame(640, 480) is None diff --git a/openpilot/starpilot/ui/tests/test_replay_settings.py b/openpilot/starpilot/ui/tests/test_replay_settings.py index 3eb3b790f6..7918a5d702 100644 --- a/openpilot/starpilot/ui/tests/test_replay_settings.py +++ b/openpilot/starpilot/ui/tests/test_replay_settings.py @@ -7,6 +7,7 @@ import time from typing import Any, NoReturn, cast from unittest.mock import Mock +from openpilot.common.test import require_value from openpilot.starpilot.ui.raylib import rl import pytest @@ -1084,7 +1085,7 @@ def test_compact_underlying_buttons_are_disabled_during_overlays_and_back_gestur from openpilot.starpilot.ui import replay_settings as module monkeypatch.setattr(module.gui_app, 'texture', Mock(return_value=NS(width=96, height=48))) page = ReplayCompactPage(NS(fonts=Mock(profile=Profile.COMPACT), profile=Profile.COMPACT), NS(close=Mock())) - assert page.content.enabled and page.content.cards.enabled + assert page.content.enabled and require_value(page.content.cards).enabled page.set_enabled(False) assert not page.content.enabled and not page.content.cards.enabled page.set_enabled(True) diff --git a/openpilot/starpilot/ui/tests/test_runtime_navigation.py b/openpilot/starpilot/ui/tests/test_runtime_navigation.py index c230f40ef8..13c154e876 100644 --- a/openpilot/starpilot/ui/tests/test_runtime_navigation.py +++ b/openpilot/starpilot/ui/tests/test_runtime_navigation.py @@ -94,7 +94,7 @@ class TestExistingToggleOwner(unittest.TestCase): def test_personality_no_op_uses_typed_integer_value(self): owner = TogglesLayout.__new__(TogglesLayout) - owner._long_personality_setting = NS(action_item=NS(enabled=True)) + self.enterContext(patch.object(owner, "_long_personality_setting", NS(action_item=NS(enabled=True)), create=True)) with patch.object(owner, "_params", NS(get=lambda *_args, **_kwargs: 1), create=True), \ patch.object(owner, "_update_toggles"), patch.object(owner, "_set_longitudinal_personality") as write: self.assertTrue(owner.request_personality(1)) @@ -105,7 +105,7 @@ class TestExistingToggleOwner(unittest.TestCase): def test_locked_control_rejects_request_without_write(self): owner = TogglesLayout.__new__(TogglesLayout) owner._toggle_defs = {"IsMetric": (lambda: "title", "description", "icon", False)} - owner._toggles = {"IsMetric": NS(action_item=NS(enabled=False))} + self.enterContext(patch.object(owner, "_toggles", {"IsMetric": NS(action_item=NS(enabled=False))}, create=True)) with patch.object(owner, "_params", NS(get_bool=lambda _: False), create=True), \ patch.object(owner, "_update_toggles"), patch.object(owner, "_toggle_callback") as write: self.assertFalse(owner.request_toggle("IsMetric", True)) @@ -114,7 +114,7 @@ class TestExistingToggleOwner(unittest.TestCase): def test_acknowledged_control_calls_existing_guarded_owner_once(self): owner = TogglesLayout.__new__(TogglesLayout) owner._toggle_defs = {"IsMetric": (lambda: "title", "description", "icon", False)} - owner._toggles = {"IsMetric": NS(action_item=NS(enabled=True))} + self.enterContext(patch.object(owner, "_toggles", {"IsMetric": NS(action_item=NS(enabled=True))}, create=True)) with patch.object(owner, "_params", NS(get_bool=lambda _: False), create=True), \ patch.object(owner, "_update_toggles"), patch.object(owner, "_toggle_callback") as write: self.assertTrue(owner.request_toggle("IsMetric", True)) diff --git a/openpilot/starpilot/ui/tests/test_runtime_onroad_leaf.py b/openpilot/starpilot/ui/tests/test_runtime_onroad_leaf.py index 404a4545c8..70371cfb34 100644 --- a/openpilot/starpilot/ui/tests/test_runtime_onroad_leaf.py +++ b/openpilot/starpilot/ui/tests/test_runtime_onroad_leaf.py @@ -38,6 +38,7 @@ class TestOnroadLeafScope(unittest.TestCase): self.assertEqual(actual.settings, expected.settings) self.assertEqual(actual.device.offroad, expected.device.offroad) self.assertEqual(actual.selected, expected.selected) + assert view.galaxy_access is not None view.galaxy_access.status.assert_not_called() def test_narrow_cache_cannot_replace_default_full_snapshot(self): @@ -56,8 +57,8 @@ class TestOnroadLeafScope(unittest.TestCase): self.assertEqual(narrow.onroad.observed_ns, NOW) self.assertIsNot(live.onroad, narrow.onroad) self.assertFalse(narrow.device.available_actions) - self.assertIsNotNone(adapter._onroad_ancillary) - self.assertIsNotNone(adapter._onroad_view_ancillary) + assert adapter._onroad_ancillary is not None + assert adapter._onroad_view_ancillary is not None def test_settings_and_home_rebuild_immediately_after_onroad(self): ui = ui_fake() @@ -71,7 +72,7 @@ class TestOnroadLeafScope(unittest.TestCase): home = adapter.build(ShellMode.HOME, now_ns=NOW + 2, onroad_view_only=True) self.assertEqual(home.home.commit, "new-commit") adapter.build(ShellMode.ONROAD, now_ns=NOW + 3, onroad_view_only=True) - self.assertIsNotNone(adapter._onroad_view_ancillary) + assert adapter._onroad_view_ancillary is not None def test_onroad_key_change_recomputes_fresh_parked_evidence(self): ui = ui_fake() diff --git a/openpilot/starpilot/ui/tests/test_settings_actions.py b/openpilot/starpilot/ui/tests/test_settings_actions.py index 9677ad6447..f777826baf 100644 --- a/openpilot/starpilot/ui/tests/test_settings_actions.py +++ b/openpilot/starpilot/ui/tests/test_settings_actions.py @@ -3,6 +3,7 @@ from dataclasses import FrozenInstanceError, replace import unittest +from openpilot.common.test import require_value from openpilot.starpilot.ui.device_state import DeviceInput, DeviceRequest, button_rect from openpilot.starpilot.ui.home_state import HomeAction, HomeActionKind, HomeInput from openpilot.starpilot.ui.presentation import Profile @@ -157,7 +158,7 @@ class TestSettingsActions(unittest.TestCase): handler.release(x + width / 2, y + height / 2, router.settings) self.assertEqual(len(router.requests), 1) self.assertEqual(router.requests[0].destination, router.settings.destination(destination)) - self.assertFalse(router.requests[0].destination.available) + self.assertFalse(require_value(router.requests[0].destination).available) self.assertIn("not implemented", router.notice) self.assertTrue(router.in_settings) diff --git a/openpilot/starpilot/ui/tests/test_slc_ui_runtime.py b/openpilot/starpilot/ui/tests/test_slc_ui_runtime.py index b9246a4a92..3851e72631 100644 --- a/openpilot/starpilot/ui/tests/test_slc_ui_runtime.py +++ b/openpilot/starpilot/ui/tests/test_slc_ui_runtime.py @@ -145,6 +145,7 @@ class TestSlcUiRuntime(unittest.TestCase): result = runtime.step(sm, cp, now_ns=START + 50_000_000, request=action) self.assertEqual(result.message.slcState.actionStatus, "accept") self.assertFalse(result.message.slcState.hasPending) + assert result.result.ceiling is not None self.assertGreater(result.result.ceiling.speed_mps, 60.0 / 3.6) self.assertAlmostEqual(sm['carState'].vCruise, 60.0) @@ -165,6 +166,7 @@ class TestSlcUiRuntime(unittest.TestCase): now_ns = START + 50_000_000 sm.advance(now_ns) rejected = runtime.step(sm, cp, now_ns=now_ns, request=action) + assert rejected.result.acceptance is not None self.assertEqual(rejected.result.acceptance.basis, 'driver_reject' if action else 'timeout_reject') self.assertFalse(rejected.message.slcState.hasPending) state = OnroadState(True, False, 20.0, 60.0, speed_limit_from_message(rejected.message.slcState), @@ -177,6 +179,7 @@ class TestSlcUiRuntime(unittest.TestCase): sm.advance(now_ns + 50_000_000) restored = runtime.step(sm, cp, now_ns=now_ns + 50_000_000, request=restore) self.assertEqual(restored.message.slcState.actionStatus, "adopt") + assert restored.result.ceiling is not None self.assertAlmostEqual(restored.result.ceiling.speed_mps, 25.0) def test_adoption_request_still_works_with_lower_selected_cruise(self): @@ -191,7 +194,7 @@ class TestSlcUiRuntime(unittest.TestCase): sm.advance(START + 50_000_000) result = runtime.step(sm, cp, now_ns=START + 50_000_000, request=action) self.assertEqual(result.message.slcState.actionStatus, "adopt") - self.assertIsNotNone(result.result.ceiling) + assert result.result.ceiling is not None def test_projection_does_not_claim_the_removed_use_button(self): from openpilot.starpilot.system.starport.projection_onroad import ProjectionOnroad diff --git a/openpilot/starpilot/ui/tests/test_sounds_settings.py b/openpilot/starpilot/ui/tests/test_sounds_settings.py index 5d71628295..daeb2372e9 100644 --- a/openpilot/starpilot/ui/tests/test_sounds_settings.py +++ b/openpilot/starpilot/ui/tests/test_sounds_settings.py @@ -301,6 +301,7 @@ class SoundsSettingsTests(unittest.TestCase): session._sounds_ui(FeatureUiAction("open", broken)) editor = session.sounds_snapshot() repair = FeatureInput.target(1900, feature_row_top(editor) + 77, editor) + assert repair is not None self.assertEqual(repair.kind, "change") session._sounds_ui(repair) self.assertEqual(self.params.get("WarningSoftVolume"), AUTO) diff --git a/openpilot/starpilot/ui/tests/test_traffic_status.py b/openpilot/starpilot/ui/tests/test_traffic_status.py index 75b23e2795..013e76a5c8 100644 --- a/openpilot/starpilot/ui/tests/test_traffic_status.py +++ b/openpilot/starpilot/ui/tests/test_traffic_status.py @@ -6,6 +6,7 @@ import unittest from types import SimpleNamespace as NS from unittest import mock +from openpilot.common.test import require_value from openpilot.starpilot.ui.raylib import rl from opendbc.car.structs import CarParams @@ -54,7 +55,7 @@ class TestTrafficStatus(unittest.TestCase): self.params = Params(temporary.name) self.params.put('ModeButtonControl', 6, block=True) self.settings_hash = settings_fingerprint(ConditionalSettingsOwner(self.params).refresh(NOW)) - self.map_hash = read_button_map(self.params, include_ioniq_media=True).fingerprint() + self.map_hash = require_value(read_button_map(self.params, include_ioniq_media=True)).fingerprint() self.reader = TrafficDisplayProjector() def project(self, event, **changes): @@ -180,6 +181,7 @@ class TestTrafficStatus(unittest.TestCase): with mock.patch('openpilot.starpilot.ui.runtime_snapshot.paired_clocks_ns', return_value=(NOW, BOOT, 0)): shown = adapter.build(ShellMode.ONROAD, now_ns=NOW).onroad self.assertTrue(shown.traffic_mode) + assert shown.traffic_display is not None self.assertEqual(shown.traffic_display.label, 'TRAFFIC') self.assertEqual(shown.speed_limit.kind.value, 'stale') # Invalid SLC does not veto independent Traffic status. fonts = mock.Mock() diff --git a/openpilot/starpilot/ui/tests/test_ui_started_authority.py b/openpilot/starpilot/ui/tests/test_ui_started_authority.py index 96572376fc..dbabc8b477 100644 --- a/openpilot/starpilot/ui/tests/test_ui_started_authority.py +++ b/openpilot/starpilot/ui/tests/test_ui_started_authority.py @@ -1,6 +1,7 @@ """Exercise the actual UI owner with separately delivered hardware/Panda state.""" from unittest.mock import MagicMock +from openpilot.common.test import require_value from openpilot.cereal.messaging import SubMaster from types import SimpleNamespace as NS from typing import Any @@ -33,7 +34,7 @@ def test_replay_messages_use_clock_sample_after_receipt(): ui.sm.update = receive UIState.update(ui) assert ui.replay_sample.now_ns is not None - assert display_message(ui.sm, 'carControl', ui.replay_sample.now_ns).latActive + assert require_value(display_message(ui.sm, 'carControl', ui.replay_sample.now_ns)).latActive assert ui.sm.replay_sample is ui.replay_sample ui._reset_replay_state.assert_not_called() @@ -177,7 +178,7 @@ def test_epoch_reset_precedes_paused_primer_and_never_drains_socket(): with patch('openpilot.selfdrive.ui.ui_state.messaging.drain_sock_raw') as drain: ui.update() drain.assert_not_called() - assert display_message(ui.sm, 'carControl', NOW, after_frame=ui.started_frame).latActive + assert require_value(display_message(ui.sm, 'carControl', NOW, after_frame=ui.started_frame)).latActive assert ui.sm.alive['carControl'] assert not ui.aol_runtime @@ -205,7 +206,7 @@ def test_straddled_epoch_withholds_frame_but_retains_new_paused_primer(): assert not ui.sm.seen['carState'] # future stamp from the old timeline ui.update() assert ui.replay_sample.valid - assert display_message(ui.sm, 'carControl', NOW).latActive + assert require_value(display_message(ui.sm, 'carControl', NOW)).latActive assert ui.sm.alive['carControl'] # the paused primer remains logically current @@ -298,7 +299,7 @@ def test_paused_primer_is_eligible_in_same_started_receive(): ui._update_status() assert ui.started_frame == 9 assert ui.status == UIStatus.ENGAGED - assert current_message(ui.sm, 'selfdriveState', NOW, after_frame=ui.started_frame).enabled + assert require_value(current_message(ui.sm, 'selfdriveState', NOW, after_frame=ui.started_frame)).enabled def test_replay_boot_time_camera_primer_retention_and_freshness(): @@ -317,7 +318,7 @@ def test_replay_boot_time_camera_primer_retention_and_freshness(): assert ui.sm.alive['cabinCameraState'] ui._reset_replay_state(retain_sample=sample) assert ui.sm.seen['cabinCameraState'] - assert display_message(ui.sm, 'cabinCameraState', NOW).frameId == 42 + assert require_value(display_message(ui.sm, 'cabinCameraState', NOW)).frameId == 42 ui.sm.replay_sample = ClockSample(NOW, None, NOW, epoch=2, paused=True, valid=True) assert display_message(ui.sm, 'cabinCameraState', NOW) is None diff --git a/openpilot/starpilot/ui/tests/test_value_editors.py b/openpilot/starpilot/ui/tests/test_value_editors.py index 1161161853..ad2e2e28f0 100644 --- a/openpilot/starpilot/ui/tests/test_value_editors.py +++ b/openpilot/starpilot/ui/tests/test_value_editors.py @@ -9,6 +9,7 @@ from unittest.mock import Mock, patch from opendbc.car.car_helpers import interfaces from opendbc.car.hyundai.values import CAR +from openpilot.common.test import require_value from openpilot.common.params import Params from openpilot.starpilot.lateral.lane_change_preferences import read_saved from openpilot.starpilot.ui import runtime_app @@ -102,6 +103,7 @@ class ValueEditorTests(unittest.TestCase): self.assertIn((choices[1], choices[1]), current.presets) for choice in choices[1:]: request = value_request(replace(editor, rows=(current,)), FeatureUiAction("change", current, 1)) + assert request is not None self.assertEqual(request.value, choice) current = replace(current, value=choice) self.assertIsNone(value_request(replace(editor, rows=(current,)), FeatureUiAction("change", current, 1))) @@ -194,7 +196,7 @@ class ValueEditorTests(unittest.TestCase): self.session.feature_page = FeaturePage.SLC editor = self.open_feature("slc:offset:2") row = editor.rows[0] - self.assertEqual(value_request(editor, FeatureUiAction("change", row, 1)).direction, 1) + self.assertEqual(require_value(value_request(editor, FeatureUiAction("change", row, 1))).direction, 1) self.tap(editor, value_buttons(editor, row, feature_row_top(editor))[-1][1], self.session._feature_ui) self.assertEqual(float(self.session.feature_snapshot().rows[0].value), 1.) before = Path(self.params.get_param_path("SLCOffsetSchedule")).read_bytes() diff --git a/openpilot/starpilot/ui/tests/test_vision_speed_units.py b/openpilot/starpilot/ui/tests/test_vision_speed_units.py index a43febb4f9..89eb621e40 100644 --- a/openpilot/starpilot/ui/tests/test_vision_speed_units.py +++ b/openpilot/starpilot/ui/tests/test_vision_speed_units.py @@ -80,6 +80,7 @@ def test_vision_sign_and_slc_cap_use_configured_units_without_rewriting_set(prof sm.advance(now) output = runtime.step(sm, cp, now_ns=now, now_boot_ns=now + 4_000_000_000, request=Action('units', 1, state.decisionId, state.presentationId, 'accept')) + assert output.result.ceiling is not None assert output.result.ceiling.speed_mps == pytest.approx(expected_mps) assert car.vCruise == car.vCruiseCluster == 90. texts = render(output.message.slcState, car.vCruise) diff --git a/openpilot/starpilot/ui/tests/test_weather.py b/openpilot/starpilot/ui/tests/test_weather.py index 3367932a61..61af0f2949 100644 --- a/openpilot/starpilot/ui/tests/test_weather.py +++ b/openpilot/starpilot/ui/tests/test_weather.py @@ -9,6 +9,7 @@ from unittest.mock import Mock, patch import pytest +from openpilot.common.test import require_value from openpilot.starpilot.ui.onroad_customization import default_document, validate_document, customization_metadata from openpilot.starpilot.ui.onroad_state import AlertSize, OnroadAlert, OnroadState, SpeedLimitObservation from openpilot.starpilot.ui.weather import WeatherClient, WeatherReading, fetch_weather, valid_location, nearby @@ -84,7 +85,7 @@ def test_failed_request_backs_off_and_keeps_a_still_current_reading(): client._reading, client._position, client._received = WeatherReading(20, 0, True), (0, 0), 900 with patch('openpilot.starpilot.ui.weather.threading.Thread') as thread: thread.return_value.start.side_effect = lambda: client._refresh((0, 0)) - assert client.observe((0, 0)).temperature_c == 20 + assert require_value(client.observe((0, 0))).temperature_c == 20 for _ in range(10): client.observe((0, 0)) assert fetch.call_count == 1 diff --git a/openpilot/starpilot/ui/toggles_state.py b/openpilot/starpilot/ui/toggles_state.py index 22d4c5f11e..032e049f6a 100644 --- a/openpilot/starpilot/ui/toggles_state.py +++ b/openpilot/starpilot/ui/toggles_state.py @@ -65,8 +65,8 @@ class TogglesInput: ToggleKey.DISENGAGE_ACCELERATOR, None, ToggleKey.LANE_DEPARTURE, ToggleKey.ALWAYS_ON_DM, ToggleKey.RIGHT_HAND_DRIVING, ToggleKey.RECORD_FRONT, ToggleKey.RECORD_AUDIO, ToggleKey.METRIC) - if 0 <= row < len(rows) and rows[row] is not None and x >= 1790: - key = rows[row] + key = rows[row] if 0 <= row < len(rows) else None + if key is not None and x >= 1790: if key in state.unavailable: return None return ToggleRequest(key=key, value=not getattr(state, key.value)) diff --git a/openpilot/system/athena/athenad.py b/openpilot/system/athena/athenad.py index a099c76257..8e3d53e2e0 100755 --- a/openpilot/system/athena/athenad.py +++ b/openpilot/system/athena/athenad.py @@ -827,6 +827,7 @@ def startLocalProxy(remote_ws_uri: str, local_port: int) -> dict[str, int]: enable_multithread=True) # Set TOS to keep connection responsive while under load. + assert ws.sock is not None ws.sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, SSH_TOS) ssock, csock = socket.socketpair() diff --git a/openpilot/system/athena/tests/test_upload_preferences.py b/openpilot/system/athena/tests/test_upload_preferences.py index 8fcb21d7d3..5aaaed51fc 100644 --- a/openpilot/system/athena/tests/test_upload_preferences.py +++ b/openpilot/system/athena/tests/test_upload_preferences.py @@ -10,6 +10,7 @@ import threading import unittest from unittest.mock import Mock, patch +from openpilot.common.test import require_value from openpilot.common.params import Params from openpilot.system.athena import athenad @@ -69,7 +70,7 @@ class UploadPreferencesTest(unittest.TestCase): patch.object(athenad, 'network_metered', return_value=True): self.params.put_bool('AlwaysAllowUploads', True, block=True) athenad.cb(master, item, 1, end, 10, 1) - self.assertEqual(athenad.cur_upload_items[1].progress, .1) + self.assertEqual(require_value(athenad.cur_upload_items[1]).progress, .1) self.params.put_bool('AlwaysAllowUploads', False, block=True) with self.assertRaises(athenad.AbortTransferException): athenad.cb(master, item, 1, end, 10, 2) diff --git a/openpilot/system/loggerd/tests/test_legacy_recordings.py b/openpilot/system/loggerd/tests/test_legacy_recordings.py index a7ad37c36d..9c6ebd4e0c 100644 --- a/openpilot/system/loggerd/tests/test_legacy_recordings.py +++ b/openpilot/system/loggerd/tests/test_legacy_recordings.py @@ -122,6 +122,7 @@ class TestLegacyRecordings(unittest.TestCase): 'fcntl.flock(f,fcntl.LOCK_SH); print("ready",flush=True); sys.stdin.read(1); os.close(f)', str(old)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) try: + assert child.stdout is not None self.assertEqual(child.stdout.readline().strip(), 'ready') self.assertEqual(deleter.deleter_step(), (True, None)) self.assertTrue((old / 'qlog.zst').exists()) diff --git a/openpilot/system/loggerd/tests/test_loggerd.py b/openpilot/system/loggerd/tests/test_loggerd.py index ca145dd0ce..29c53b4fa7 100644 --- a/openpilot/system/loggerd/tests/test_loggerd.py +++ b/openpilot/system/loggerd/tests/test_loggerd.py @@ -258,6 +258,8 @@ class TestLoggerd(OpenpilotTestCase): # next one should increment by one bl1 = re.match(RE.LOG_ID_V2, bootlog_path.name) bl2 = re.match(RE.LOG_ID_V2, self._gen_bootlog().name) + assert bl1 is not None + assert bl2 is not None assert bl1.group('uid') != bl2.group('uid') assert int(bl1.group('count')) == 0 and int(bl2.group('count')) == 1 diff --git a/openpilot/system/manager/process.py b/openpilot/system/manager/process.py index 78a0e6bb2b..07f914077a 100644 --- a/openpilot/system/manager/process.py +++ b/openpilot/system/manager/process.py @@ -223,7 +223,7 @@ class DaemonProcess(ManagerProcess): self.params = None @staticmethod - def should_run(started, params, CP): + def should_run(started: bool, params: Params, CP: car.CarParams, /) -> bool: return True def start(self) -> None: diff --git a/openpilot/system/manager/test/test_process_recovery.py b/openpilot/system/manager/test/test_process_recovery.py index 132d23bb06..f8c594fc3c 100644 --- a/openpilot/system/manager/test/test_process_recovery.py +++ b/openpilot/system/manager/test/test_process_recovery.py @@ -111,8 +111,8 @@ class TestProcessRecovery(unittest.TestCase): def test_a_crashed_jetlink_owner_restarts(self): from openpilot.system.manager.process_config import managed_processes configured = managed_processes["jetlinkd"] - self.assertTrue(configured.restart_on_exit) assert isinstance(configured, process.PythonProcess) + self.assertTrue(configured.restart_on_exit) p = process.PythonProcess("jetlinkd", "unused", lambda started, params, cp: True, restart_on_exit=configured.restart_on_exit) self.step(p) old = p.proc @@ -128,12 +128,13 @@ class TestProcessRecovery(unittest.TestCase): def test_learner_recovers_with_backoff_onroad_and_parked(self): from openpilot.system.manager.process_config import managed_processes configured = managed_processes["steerlearnerd"] + assert isinstance(configured, process.PythonProcess) self.assertTrue(configured.restart_on_exit) p = process.PythonProcess(configured.name, configured.module, configured.should_run, restart_on_exit=configured.restart_on_exit) self.step(p) old = p.proc - self.assertIsNotNone(old) + assert old is not None assert isinstance(old, Child) old.exitcode = 1 self.step(p) @@ -148,7 +149,7 @@ class TestProcessRecovery(unittest.TestCase): self.step(p, started=False) self.now += 60 self.step(p, started=False) - self.assertIsNotNone(p.proc) + assert p.proc is not None self.step(p, started=False, ignored=[configured.name]) self.assertTrue(p.shutting_down) assert isinstance(p.proc, Child) @@ -166,6 +167,7 @@ class TestProcessRecovery(unittest.TestCase): def test_sensor_three_recovery_cycles_obey_backoff_and_stop_eligibility(self): from openpilot.system.manager import process_config configured = process_config.managed_processes['sensord'] + assert isinstance(configured, process.PythonProcess) p = process.PythonProcess('sensord', configured.module, configured.should_run, restart_on_exit=configured.restart_on_exit) with patch.object(process_config, 'sentry_enabled', return_value=False): diff --git a/openpilot/system/sensord/tests/test_worker_lifecycle.py b/openpilot/system/sensord/tests/test_worker_lifecycle.py index 3078c2000e..a6e35969fa 100644 --- a/openpilot/system/sensord/tests/test_worker_lifecycle.py +++ b/openpilot/system/sensord/tests/test_worker_lifecycle.py @@ -10,6 +10,7 @@ from openpilot.cereal import log from openpilot.common.test import OpenpilotTestCase from openpilot.system.sensord import sensord +from openpilot.system.manager.process import PythonProcess from openpilot.system.manager.process_config import managed_processes @@ -54,6 +55,7 @@ class TestSensorWorkerLifecycle(OpenpilotTestCase): def test_sensor_manager_recovery_is_enabled_without_changing_onroad_gate(self): process = managed_processes['sensord'] + assert isinstance(process, PythonProcess) self.assertTrue(process.restart_on_exit) self.assertFalse(process.sigkill) diff --git a/openpilot/system/ui/lib/application.py b/openpilot/system/ui/lib/application.py index 04ff1fc355..35137e8d72 100644 --- a/openpilot/system/ui/lib/application.py +++ b/openpilot/system/ui/lib/application.py @@ -438,14 +438,18 @@ class GuiApplication: def _ffmpeg_writer_thread(self): """Background thread that writes frames to ffmpeg.""" + frames, stop, process = self._ffmpeg_queue, self._ffmpeg_stop_event, self._ffmpeg_proc + stdin = process.stdin if process is not None else None + if frames is None or stop is None or stdin is None: + return while True: try: - data = self._ffmpeg_queue.get(timeout=1.0) + data = frames.get(timeout=1.0) if data is None: # Sentinel to stop break - self._ffmpeg_proc.stdin.write(data) + stdin.write(data) except queue.Empty: - if self._ffmpeg_stop_event.is_set(): + if stop.is_set(): break continue except Exception: @@ -604,13 +608,17 @@ class GuiApplication: def close_ffmpeg(self): if self._ffmpeg_thread is not None: # Signal thread to stop, send sentinel, then wait for it to drain - self._ffmpeg_stop_event.set() - self._ffmpeg_queue.put(None) + if self._ffmpeg_stop_event is not None: + self._ffmpeg_stop_event.set() + if self._ffmpeg_queue is not None: + self._ffmpeg_queue.put(None) self._ffmpeg_thread.join(timeout=30) if self._ffmpeg_proc is not None: - self._ffmpeg_proc.stdin.flush() - self._ffmpeg_proc.stdin.close() + stdin = self._ffmpeg_proc.stdin + if stdin is not None: + stdin.flush() + stdin.close() try: self._ffmpeg_proc.wait(timeout=30) except subprocess.TimeoutExpired: @@ -779,7 +787,7 @@ class GuiApplication: (present_end - update_end) * 1000, (present_cpu_end - update_cpu_end) * 1000, ) - if RECORD: + if RECORD and self._render_texture is not None and self._ffmpeg_queue is not None: image = rl.load_image_from_texture(self._render_texture.texture) data_size = image.width * image.height * 4 data = image.to_bytes(data_size) @@ -983,13 +991,16 @@ class GuiApplication: import io import pstats - self._render_profiler.disable() + profiler = self._render_profiler + if profiler is None: + return + profiler.disable() assert self._render_profile_start_time is not None elapsed_ms = (time.monotonic() - self._render_profile_start_time) * 1e3 avg_frame_time = elapsed_ms / self._frame if self._frame > 0 else 0 stats_stream = io.StringIO() - pstats.Stats(self._render_profiler, stream=stats_stream).sort_stats("cumtime").print_stats(PROFILE_STATS) + pstats.Stats(profiler, stream=stats_stream).sort_stats("cumtime").print_stats(PROFILE_STATS) print("\n=== Render loop profile ===") print(stats_stream.getvalue().rstrip()) diff --git a/openpilot/system/ui/widgets/list_view.py b/openpilot/system/ui/widgets/list_view.py index 519aed2d40..1004329f5f 100644 --- a/openpilot/system/ui/widgets/list_view.py +++ b/openpilot/system/ui/widgets/list_view.py @@ -270,10 +270,9 @@ class MultipleButtonAction(ItemAction): self.callback(i) -class ListItem(Widget): +class ListItem[A: ItemAction | None](Widget): def __init__(self, title: str | Callable[[], str] = "", icon: str | None = None, description: str | Callable[[], str] | None = None, - description_visible: bool = False, callback: Callable | None = None, - action_item: ItemAction | None = None): + description_visible: bool = False, callback: Callable | None = None, *, action_item: A): super().__init__() self._title = title self.set_icon(icon) @@ -345,8 +344,8 @@ class ListItem(Widget): return # Don't draw items that are not in parent's viewport - if ((self._rect.y + self.rect.height) <= self._parent_rect.y or - self._rect.y >= (self._parent_rect.y + self._parent_rect.height)): + if self._parent_rect is not None and ((self._rect.y + self.rect.height) <= self._parent_rect.y or + self._rect.y >= (self._parent_rect.y + self._parent_rect.height)): return content_x = self._rect.x + ITEM_PADDING @@ -435,31 +434,31 @@ class ListItem(Widget): # Factory functions def toggle_item(title: str | Callable[[], str], description: str | Callable[[], str] | None = None, initial_state: bool = False, - callback: Callable | None = None, icon: str = "", enabled: bool | Callable[[], bool] = True) -> ListItem: + callback: Callable | None = None, icon: str = "", enabled: bool | Callable[[], bool] = True) -> ListItem[ToggleAction]: action = ToggleAction(initial_state=initial_state, enabled=enabled, callback=callback) return ListItem(title=title, description=description, action_item=action, icon=icon) def button_item(title: str | Callable[[], str], button_text: str | Callable[[], str], description: str | Callable[[], str] | None = None, - callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: + callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem[ButtonAction]: action = ButtonAction(text=button_text, enabled=enabled) return ListItem(title=title, description=description, action_item=action, callback=callback) def text_item(title: str | Callable[[], str], value: str | Callable[[], str], description: str | Callable[[], str] | None = None, - callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: + callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem[TextAction]: action = TextAction(text=value, color=ITEM_TEXT_VALUE_COLOR, enabled=enabled) return ListItem(title=title, description=description, action_item=action, callback=callback) def dual_button_item(left_text: str | Callable[[], str], right_text: str | Callable[[], str], left_callback: Callable | None = None, right_callback: Callable | None = None, - description: str | Callable[[], str] | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: + description: str | Callable[[], str] | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem[DualButtonAction]: action = DualButtonAction(left_text, right_text, left_callback, right_callback, enabled) return ListItem(title="", description=description, action_item=action) def multiple_button_item(title: str | Callable[[], str], description: str | Callable[[], str], buttons: list[str | Callable[[], str]], selected_index: int, - button_width: int = BUTTON_WIDTH, callback: Callable | None = None, icon: str = ""): + button_width: int = BUTTON_WIDTH, callback: Callable | None = None, icon: str = "") -> ListItem[MultipleButtonAction]: action = MultipleButtonAction(buttons, button_width, selected_index, callback=callback) return ListItem(title=title, description=description, icon=icon, action_item=action) diff --git a/openpilot/system/ui/widgets/network.py b/openpilot/system/ui/widgets/network.py index 46b0ef4a7e..938bde2baa 100644 --- a/openpilot/system/ui/widgets/network.py +++ b/openpilot/system/ui/widgets/network.py @@ -290,10 +290,15 @@ class AdvancedNetworkSettings(Widget): gui_app.push_widget(self._keyboard) def _update_state(self): + from openpilot.selfdrive.ui.ui_state import ProjectionPrimeState + self._wifi_manager.process_callbacks() # If not using prime SIM, show GSM settings and enable IPv4 forwarding - show_cell_settings = self._prime_state.get_type() in self._cell_prime_types + prime_state = self._prime_state + if isinstance(prime_state, ProjectionPrimeState): + return + show_cell_settings = prime_state.get_type() in self._cell_prime_types if self._allowed(): self._wifi_manager.set_ipv4_forward(show_cell_settings) self._roaming_btn.set_visible(show_cell_settings) diff --git a/openpilot/system/updated/tests/test_fast_request.py b/openpilot/system/updated/tests/test_fast_request.py index e805ca8f89..dfb0107d03 100644 --- a/openpilot/system/updated/tests/test_fast_request.py +++ b/openpilot/system/updated/tests/test_fast_request.py @@ -133,8 +133,10 @@ class TestFastRequest(unittest.TestCase): def test_long_failure_remains_readable_by_galaxy(self): self.updater.fast_update.side_effect = RuntimeError('download failed: ' + 'é' * 5000) self.run_cycle() - self.assertLessEqual(len(self.values['LastUpdateException'].encode('utf-8')), 4096) - self.assertTrue(self.values['LastUpdateException'].startswith('download failed: ')) + message = self.values['LastUpdateException'] + assert isinstance(message, str) + self.assertLessEqual(len(message.encode('utf-8')), 4096) + self.assertTrue(message.startswith('download failed: ')) self.assertEqual(self.values['UpdaterState'], 'idle') def test_success_waits_for_manager_restart(self): diff --git a/openpilot/system/webrtc/device/video.py b/openpilot/system/webrtc/device/video.py index cb85dff73e..e48c02b7af 100644 --- a/openpilot/system/webrtc/device/video.py +++ b/openpilot/system/webrtc/device/video.py @@ -87,6 +87,7 @@ class LiveStreamVideoStreamTrack(TiciVideoStreamTrack): await asyncio.sleep(0.005) continue + assert self._sock is not None msg = messaging.recv_one_or_none(self._sock) if msg is not None: if not self._seen_keyframe and (getattr(msg, msg.which()).idx.flags & V4L2_BUF_FLAG_KEYFRAME): diff --git a/openpilot/system/webrtc/webrtcd.py b/openpilot/system/webrtc/webrtcd.py index f0f4e382e1..480765e2b1 100755 --- a/openpilot/system/webrtc/webrtcd.py +++ b/openpilot/system/webrtc/webrtcd.py @@ -292,6 +292,7 @@ async def handle_get_stream(state: ServerState, raw_body: bytes, content_type: s stream_dict.pop(session.identifier, None) schedule_teardown(state) + assert session.run_task is not None session.run_task.add_done_callback(remove_finished_session) return _json_response({"sdp": answer.sdp, "type": answer.type}) diff --git a/openpilot/tools/lateral_maneuvers/lateral_maneuversd.py b/openpilot/tools/lateral_maneuvers/lateral_maneuversd.py index ed07c896f9..cc0c633eff 100755 --- a/openpilot/tools/lateral_maneuvers/lateral_maneuversd.py +++ b/openpilot/tools/lateral_maneuvers/lateral_maneuversd.py @@ -133,6 +133,7 @@ def main(): if complete_cnt > 0: complete_cnt -= 1 + assert maneuver is not None alert_msg.alertDebug.alertText1 = 'Completed' alert_msg.alertDebug.alertText2 = maneuver.description elif maneuver is not None: @@ -193,6 +194,7 @@ def main(): plan_send.valid = maneuver is not None and maneuver.active and complete_cnt == 0 if plan_send.valid: + assert maneuver is not None plan_send.lateralManeuverPlan.desiredCurvature = maneuver._baseline_curvature + accel / max(v_ego, MIN_SPEED) ** 2 pm.send('lateralManeuverPlan', plan_send) diff --git a/openpilot/tools/plotjuggler/test_plotjuggler.py b/openpilot/tools/plotjuggler/test_plotjuggler.py index b3a85e7ce9..92762b6d5a 100644 --- a/openpilot/tools/plotjuggler/test_plotjuggler.py +++ b/openpilot/tools/plotjuggler/test_plotjuggler.py @@ -34,7 +34,7 @@ class TestPlotJuggler(OpenpilotTestCase): with Timeout(180): while "Done reading Rlog data" not in output.splitlines(): for key, _ in selector.select(0.1): - chunk = os.read(key.fileobj.fileno(), 65536) + chunk = os.read(key.fd, 65536) if chunk: output += chunk.decode("utf-8", errors="replace") else: @@ -45,7 +45,7 @@ class TestPlotJuggler(OpenpilotTestCase): self.fail(f"PlotJuggler did not report startup within 180 seconds:\n{output}") time.sleep(2) for key, _ in selector.select(0): - chunk = os.read(key.fileobj.fileno(), 65536) + chunk = os.read(key.fd, 65536) output += chunk.decode("utf-8", errors="replace") self.assertIsNone(p.poll(), f"PlotJuggler exited after startup (status {p.returncode}):\n{output}") self.assertNotIn("Raw file read failed", output) diff --git a/openpilot/tools/replay/tests/test_machine.py b/openpilot/tools/replay/tests/test_machine.py index 608680937b..ffe7420cee 100644 --- a/openpilot/tools/replay/tests/test_machine.py +++ b/openpilot/tools/replay/tests/test_machine.py @@ -98,6 +98,7 @@ class Machine: self.process = subprocess.Popen(self.command, env=self.env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.stderr, text=True) def reader(): + assert self.process is not None stdout = self.process.stdout assert stdout is not None for line in stdout: @@ -126,12 +127,17 @@ class Machine: raise AssertionError(f"No matching status; last={last}, stderr={self.stderr.read()[-6000:]}") def command_status(self, op, request, **fields): + assert self.process is not None + assert self.process.stdin is not None self.process.stdin.write(json.dumps(dict(op=op, requestId=request, **fields)) + "\n") + assert self.process is not None + assert self.process.stdin is not None self.process.stdin.flush() return self.wait(lambda status: status["lastRequestId"] == request) def close(self): if self.process: + assert self.process.stdin is not None self.process.stdin.close() if self.process.poll() is None: try: @@ -139,6 +145,7 @@ class Machine: except subprocess.TimeoutExpired: self.process.kill() self.process.wait(timeout=3) + assert self.process.stdout is not None self.process.stdout.close() self.thread.join(timeout=1) self.stderr.close() @@ -273,13 +280,18 @@ os.execv({sys.executable!r}, [{sys.executable!r}, *sys.argv[1:]]) wrapper.chmod(0o700) engine.env['PATH'] = str(engine.root) + os.pathsep + os.environ['PATH'] def rss(): + assert engine.process is not None return int(Path(f'/proc/{engine.process.pid}/statm').read_text().split()[1]) * os.sysconf('SC_PAGESIZE') with engine: engine.wait(lambda value: value['state'] == 'paused') before = rss() enabled.touch() try: + assert engine.process is not None + assert engine.process.stdin is not None engine.process.stdin.write(json.dumps({'op': 'seek', 'requestId': 'b1', 'position': 240.1}) + '\n') + assert engine.process is not None + assert engine.process.stdin is not None engine.process.stdin.flush() deadline = time.monotonic() + 3 while (not opened.exists() or rss() > before - 32 * 1024 * 1024) and time.monotonic() < deadline: @@ -321,7 +333,11 @@ os.execv({sys.executable!r}, [{sys.executable!r}, *sys.argv[1:]]) clock = DisplayClockReader(engine.env) enabled.touch() try: + assert engine.process is not None + assert engine.process.stdin is not None engine.process.stdin.write(json.dumps({'op': 'seek', 'requestId': 'b1', 'position': 60.1}) + '\n') + assert engine.process is not None + assert engine.process.stdin is not None engine.process.stdin.flush() deadline = time.monotonic() + 3 while not opened.exists() and time.monotonic() < deadline: @@ -451,12 +467,12 @@ os.execv({sys.executable!r}, [{sys.executable!r}, *sys.argv[1:]]) messaging.recv_one(socket) engine.command_status("seek", "c0", position=.1) message = messaging.recv_one(socket) - self.assertIsNotNone(message) + assert message is not None self.assertEqual(message.logMonoTime, BOOT + 100_000_000) self.assertEqual(message.narrowRoadEncodeIdx.timestampSof, BOOT + 50_000_000) engine.command_status("seek", "c1", position=.25) message = messaging.recv_one(socket) - self.assertIsNotNone(message) + assert message is not None self.assertEqual(message.logMonoTime, BOOT + 200_000_000) self.assertEqual(message.narrowRoadEncodeIdx.frameId, 1) self.assertEqual(message.narrowRoadEncodeIdx.timestampSof, BOOT + 150_000_000) @@ -489,7 +505,7 @@ os.execv({sys.executable!r}, [{sys.executable!r}, *sys.argv[1:]]) received = messaging.recv_one(socket) while received is not None and received.logMonoTime < stamp: received = messaging.recv_one(socket) - self.assertIsNotNone(received) + assert received is not None self.assertEqual(received.logMonoTime, stamp) sample = clock.sample() self.assertTrue(sample.valid) @@ -571,6 +587,7 @@ os.execv({sys.executable!r}, [{sys.executable!r}, *sys.argv[1:]]) with engine: failed = engine.wait(lambda value: value.get('error') == 'Selected segment has no playable footage') self.assertTrue(failed['paused']) + assert engine.process is not None self.assertEqual(engine.process.wait(timeout=3), 2) def test_legacy_wall_correction_and_backwards_seek_follow_recorded_clock_validity(self): @@ -617,10 +634,12 @@ print(p.pid, flush=True) time.sleep(30) """ parent = subprocess.Popen([os.sys.executable, "-c", script, json.dumps(engine.env), *engine.command], stdout=subprocess.PIPE, text=True) + assert parent.stdout is not None child = int(parent.stdout.readline()) time.sleep(.3) parent.kill() parent.wait(timeout=3) + assert parent.stdout is not None parent.stdout.close() deadline = time.monotonic() + 3 while time.monotonic() < deadline: diff --git a/openpilot/tools/replay/tests/test_onroad_host.py b/openpilot/tools/replay/tests/test_onroad_host.py index d4c72ccccf..5354c14cdd 100644 --- a/openpilot/tools/replay/tests/test_onroad_host.py +++ b/openpilot/tools/replay/tests/test_onroad_host.py @@ -452,42 +452,60 @@ int main() { process = subprocess.Popen([str(binary)], env={**os.environ, **self.env}, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) try: + assert process.stdout is not None self.assertEqual(process.stdout.readline().strip(), 'ready') sample = self.reader.sample() self.assertTrue(sample.valid) assert sample.now_ns is not None assert sample.epoch is not None self.assertLess(abs(sample.now_ns - 30_000_000_000), 250_000_000) + assert process.stdin is not None process.stdin.write('p\n') + assert process.stdin is not None process.stdin.flush() + assert process.stdout is not None self.assertEqual(process.stdout.readline().strip(), 'done') paused = self.reader.sample() time.sleep(.3) self.assertTrue(self.reader.sample().valid) self.assertEqual(self.reader.sample().now_ns, paused.now_ns) + assert process.stdin is not None process.stdin.write('s\n') + assert process.stdin is not None process.stdin.flush() + assert process.stdout is not None self.assertEqual(process.stdout.readline().strip(), 'done') seek = self.reader.sample() self.assertFalse(seek.valid) self.assertEqual(seek.epoch, sample.epoch + 1) + assert process.stdin is not None process.stdin.write('n\n') + assert process.stdin is not None process.stdin.flush() + assert process.stdout is not None self.assertEqual(process.stdout.readline().strip(), 'done') self.assertEqual(self.reader.sample().now_ns, 2_000_000_000) + assert process.stdin is not None process.stdin.write('o\n') + assert process.stdin is not None process.stdin.flush() + assert process.stdout is not None self.assertEqual(process.stdout.readline().strip(), 'done') self.assertFalse(self.reader.sample().valid) + assert process.stdin is not None process.stdin.write('b\n') + assert process.stdin is not None process.stdin.flush() + assert process.stdout is not None self.assertEqual(process.stdout.readline().strip(), 'done') below_overflow = self.reader.sample() self.assertTrue(below_overflow.valid) assert below_overflow.now_ns is not None self.assertGreaterEqual(below_overflow.now_ns, 18_446_462_598_732_840_960) self.assertLess(below_overflow.now_ns, 2**64) + assert process.stdin is not None process.stdin.write('q\n') + assert process.stdin is not None process.stdin.flush() self.assertEqual(process.wait(timeout=3), 0) self.assertFalse(self.reader.sample().valid) diff --git a/prebuilt.json b/prebuilt.json index 36b424ed97..aff0d8275d 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "022e08440e83fcf0365cfec90b501426de27621edbba3ae9a00756266ed8fce9", "schema_version": 1} +{"protected_inventory_sha256": "ea4603dfd15d2c18449e86ded33e9e81af5ea0d5730cbadde6853124ba2353a7", "schema_version": 1} diff --git a/pyproject.toml b/pyproject.toml index b8de02d7e6..62a34e3a15 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -180,8 +180,8 @@ exclude = ["openpilot/starpilot/galaxy_bluetooth/vendor"] # unmodified third-pa extra-paths = ["opendbc_repo", "msgq_repo", "rednose_repo", "tinygrad_repo", "teleoprtc_repo", "jetlink_repo"] [tool.ty.rules] -unresolved-import = "ignore" # Cython-compiled modules (.pyx) -unresolved-attribute = "ignore" # many from capnp and Cython modules +import-not-found = "ignore" # Cython-compiled modules (.pyx) +missing-attribute = "ignore" # many from capnp and Cython modules [[tool.ty.overrides]] # dbus-next declares D-Bus signatures as string annotations ('s', 'ay', 'a{sv}'). diff --git a/uv.lock b/uv.lock index 049c502d32..3fd2c4496d 100644 --- a/uv.lock +++ b/uv.lock @@ -648,8 +648,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/c1/6fd56f7a02a478d54a1a3e6000eccd34b446b1c45cbf0d002fe5d2937126/nanobind-3.1.0-py3-none-any.whl", hash = "sha256:96984dbe8154ffb86e653b1b60aaeed6985c710c5e75ad0279eb87943c66292d", size = 316917, upload-time = "2026-09-18T15:59:37.796Z" }, ] - - [[package]] name = "numpy" version = "2.5.3" @@ -763,9 +761,9 @@ tools = [ { name = "matplotlib" }, ] vendored = [ - { name = "nanobind" }, { name = "jetlink" }, { name = "msgq-ipc", extra = ["build"] }, + { name = "nanobind" }, { name = "opendbc" }, { name = "pandacan" }, { name = "rednose" }, @@ -780,7 +778,6 @@ standalone = [ [package.metadata] requires-dist = [ - { name = "nanobind", marker = "extra == 'vendored'", specifier = "==3.1.0" }, { name = "cffi", marker = "extra == 'safety'" }, { name = "codespell", marker = "extra == 'testing'" }, { name = "comma-deps-acados" }, @@ -802,6 +799,7 @@ requires-dist = [ { name = "jetlink", marker = "extra == 'vendored'", editable = "jetlink_repo" }, { name = "matplotlib", marker = "extra == 'tools'" }, { name = "msgq-ipc", extras = ["build"], marker = "extra == 'vendored'", virtual = "msgq_repo" }, + { name = "nanobind", marker = "extra == 'vendored'", specifier = "==3.1.0" }, { name = "numpy", specifier = ">=2.0" }, { name = "opendbc", marker = "extra == 'vendored'", editable = "opendbc_repo" }, { name = "pandacan", marker = "extra == 'vendored'", editable = "panda" }, @@ -1242,7 +1240,7 @@ requires-dist = [ { name = "mkdocs", marker = "extra == 'docs'" }, { name = "mkdocs-material", marker = "extra == 'docs'" }, { name = "mkdocstrings", extras = ["python"], marker = "extra == 'docs'" }, - { name = "mypy", marker = "extra == 'linting'", specifier = "==1.19.1" }, + { name = "mypy", marker = "extra == 'linting'", specifier = "==2.3.1" }, { name = "networkx", marker = "extra == 'testing'" }, { name = "nibabel", marker = "extra == 'testing'" }, { name = "numba", marker = "extra == 'testing'", specifier = ">=0.55" }, @@ -1263,7 +1261,7 @@ requires-dist = [ { name = "pytest-split", marker = "extra == 'testing-minimal'" }, { name = "pytest-xdist", marker = "extra == 'testing-minimal'" }, { name = "pyyaml", marker = "extra == 'autogen'" }, - { name = "ruff", marker = "extra == 'linting'", specifier = "==0.14.10" }, + { name = "ruff", marker = "extra == 'linting'", specifier = "==0.16.4" }, { name = "safetensors", marker = "extra == 'testing-unit'" }, { name = "sentencepiece", marker = "extra == 'testing'" }, { name = "tabulate", marker = "extra == 'testing-unit'" }, @@ -1276,7 +1274,7 @@ requires-dist = [ { name = "transformers", marker = "extra == 'testing'" }, { name = "typeguard", marker = "extra == 'linting'" }, { name = "typing-extensions", marker = "extra == 'linting'" }, - { name = "z3-solver", marker = "extra == 'testing-minimal'", specifier = "<4.15.4" }, + { name = "z3-solver", marker = "extra == 'testing-minimal'", specifier = "==5.1.0.0" }, ] provides-extras = ["linting", "testing-minimal", "testing-unit", "testing", "docs", "mesa", "autogen"] @@ -1326,27 +1324,27 @@ wheels = [ [[package]] name = "ty" -version = "0.0.80" +version = "0.0.112" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/54/b0/6d1b10e0d422736a3c439e487c950ae785f401d71ff879d5be68bccb6d90/ty-0.0.80.tar.gz", hash = "sha256:fe86bc91327e45ff5e3593b7e306e7f57a44bc0608f38d647b8d97bd99c96013", size = 7183998, upload-time = "2026-09-09T21:18:47.547Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/94/e6c3f8ed304bc5d7ae66ae5cced39b5c48151527b5bc69693e169918b9c0/ty-0.0.112.tar.gz", hash = "sha256:8e7eb8c95fa08b35f7e86eccacaf2be5e1fe34a7c7da164280d292e1180d5907", size = 8459506, upload-time = "2026-11-26T16:23:25.704Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/29/c8/3c93195eca282936ebb574d0ba98843e4b147ee324006f88464777012a92/ty-0.0.80-py3-none-linux_armv6l.whl", hash = "sha256:738d1cfca466c577aea24547c348629c00c63548cf7da2c46b497b3840f85dee", size = 13606509, upload-time = "2026-09-09T21:18:10.476Z" }, - { url = "https://files.pythonhosted.org/packages/e7/48/bbb47f7001c97262a5109bcd92a45bcc8a2fbb21e994c214a9897630bfb7/ty-0.0.80-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:56060164bb8ee43770fa367524fbdba2611fc90f8923a02cc91f80eb37d5a1b0", size = 13203812, upload-time = "2026-09-09T21:18:12.796Z" }, - { url = "https://files.pythonhosted.org/packages/db/8d/fd141160567047b742e466be8ed09a4c4ed80fa045d37f946eb4f4532fee/ty-0.0.80-py3-none-macosx_11_0_arm64.whl", hash = "sha256:da4062e0fbf3923d9b71688157c5753394f243348f00732e9edbb27498397169", size = 13021896, upload-time = "2026-09-09T21:18:15.186Z" }, - { url = "https://files.pythonhosted.org/packages/1e/10/b4177faf9e71bc37bc4d08f512042269660a1ce0ec457c48f96e51fc91d7/ty-0.0.80-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a9eb94b2659f506a3a07a9ea1415d5c18aaa1e554adc1612614d617a0ed320e1", size = 13083881, upload-time = "2026-09-09T21:18:17.616Z" }, - { url = "https://files.pythonhosted.org/packages/7f/c2/192d48b9a9acbbe030fc9a4bd73af75671a5566e731949f77e912a68ce68/ty-0.0.80-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e2f5e39a87da48c1af1a3b3135f02be7a83a93da30b0d6a5f5d27806e7c747ce", size = 13354874, upload-time = "2026-09-09T21:18:19.744Z" }, - { url = "https://files.pythonhosted.org/packages/0a/5b/736dfd31efd98bed9dbe018ff91676e5ea83485b1e24afb635fd0247728f/ty-0.0.80-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4e00149e7779c6b98f3ba12e10a631a861bd7ca1a42bbf064e2677ada7d2c0c2", size = 14204805, upload-time = "2026-09-09T21:18:21.999Z" }, - { url = "https://files.pythonhosted.org/packages/fd/6f/557c726cb53401998e3589bb632c963a6887a70240e0a4386024f3731c81/ty-0.0.80-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a377268f359fb6e7a2cc9026a09223c764f58d020dec8e6baeaba9caba6ff829", size = 14630014, upload-time = "2026-09-09T21:18:24Z" }, - { url = "https://files.pythonhosted.org/packages/e9/19/7a4b18fe27f6b6bd4ffa56b67c8b09ecb76bb4312d1c64b73f65417b4dbd/ty-0.0.80-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4511dbf1b266b9ce5b73e9b28d94468096c2b6da00e2fe205168c32d3b352ca7", size = 14326946, upload-time = "2026-09-09T21:18:26.679Z" }, - { url = "https://files.pythonhosted.org/packages/f8/95/16dd90805fc7e53ec54ae9fdb1a8b74753fb159a55a170f60f49b9417824/ty-0.0.80-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fe95feffa7156800c6f804195acb9fb5846a39671c7192c30fff23351aaf7c31", size = 13705988, upload-time = "2026-09-09T21:18:28.681Z" }, - { url = "https://files.pythonhosted.org/packages/b1/09/4e87992c23ab8a742c7d4914ac5fe66fb9301c8464a69fd2ecbc0be3fbcd/ty-0.0.80-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:ba26b39f06bc8c3c2c5acd3a147239482b36620cdbca1b9d02e915294854f2cc", size = 14233729, upload-time = "2026-09-09T21:18:30.961Z" }, - { url = "https://files.pythonhosted.org/packages/36/e9/b8c11fda8e66a1d1cc1a7160ed719a33f4dc0107b1cef6a14e2673965763/ty-0.0.80-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:2e6167320888c115a6fbe69893b63fd1c848f9121a454e75e5f612674528e3f3", size = 13173523, upload-time = "2026-09-09T21:18:33.266Z" }, - { url = "https://files.pythonhosted.org/packages/73/a7/512083fa540c5be1ac8642658f03bfb5bfa6fd168ea4f55e3c0aabe04166/ty-0.0.80-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:7aecb62b4de70b479eab07d1779ea66da26dd8b068f50a9330867157312f103c", size = 13373014, upload-time = "2026-09-09T21:18:35.339Z" }, - { url = "https://files.pythonhosted.org/packages/5e/63/cd2f0ca81fd9b8cafef93bbcf022bf636bc4de8ee7465c6aafeec1d4d52b/ty-0.0.80-py3-none-musllinux_1_2_i686.whl", hash = "sha256:4fed06adacd16b7e2d722f37449021b1419598d0440769701c0f4827faddde63", size = 13667827, upload-time = "2026-09-09T21:18:37.241Z" }, - { url = "https://files.pythonhosted.org/packages/0d/5d/ebdfdcb2dc099ae74dc4b75511eef0dd398b2fa27006c543543974b4567f/ty-0.0.80-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:09329af6303ce611ec2cfffc995dc1ddf76c9f47194fc1a4d64a984759c25f5b", size = 13963866, upload-time = "2026-09-09T21:18:39.386Z" }, - { url = "https://files.pythonhosted.org/packages/c4/f6/c286d5e1b560cfd16d6e91fdab683718aacf09fc88938ca06dcc9d1c8502/ty-0.0.80-py3-none-win32.whl", hash = "sha256:a81b3b512f7b4c68e42fbd1835633de658809666e9aafd5defa52bbc5197698d", size = 12881806, upload-time = "2026-09-09T21:18:41.507Z" }, - { url = "https://files.pythonhosted.org/packages/fd/c8/3b3a8ac16d47a23ff34bf57c0d99a491860748aea96e0e886b4bfed54f9b/ty-0.0.80-py3-none-win_amd64.whl", hash = "sha256:8043f99878a2ae434781cb881c8a3840dff70c4a5b60bdc5ae84251f35ee063f", size = 13528883, upload-time = "2026-09-09T21:18:43.687Z" }, - { url = "https://files.pythonhosted.org/packages/2e/71/a6c697930fca76596d7d17f8853120f41a298fd9ea632c901cfca8ca869b/ty-0.0.80-py3-none-win_arm64.whl", hash = "sha256:e277ef034331da5319efc839c064968d24f35715b71c70369cf97d36fe4dcbdb", size = 13370135, upload-time = "2026-09-09T21:18:45.758Z" }, + { url = "https://files.pythonhosted.org/packages/fc/b6/4b3ad2ca8c3f6c4515c5959f238fa3d046d909597eaffa9fd2d423e200ef/ty-0.0.112-py3-none-linux_armv6l.whl", hash = "sha256:5957ccc40bc439f275d36a2fad16dab288d2a8a59bad49505d57fdae4ebd1be9", size = 15472467, upload-time = "2026-11-26T16:22:46.434Z" }, + { url = "https://files.pythonhosted.org/packages/9c/1b/f1309df85397d07f80e0fe3943783a7ca82dda3fc9821482dec9711586a7/ty-0.0.112-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:d8536e8b5e3dda22f6d8c124edf34009fc219f11976fe154dac10476fefea9c8", size = 14970128, upload-time = "2026-11-26T16:22:49.283Z" }, + { url = "https://files.pythonhosted.org/packages/d0/e1/cbd91ede3e31069aca010b1204063f3a186781f27e32d3ec03dc970aa232/ty-0.0.112-py3-none-macosx_11_0_arm64.whl", hash = "sha256:235f676a71134225ed80f598414ad9f07240ce5c6c919b6fcb62b19168167559", size = 14369627, upload-time = "2026-11-26T16:22:51.386Z" }, + { url = "https://files.pythonhosted.org/packages/92/fe/4a4eacad1a33e017de4f565cd07874df3af604a1266a7749bc8cba833e7f/ty-0.0.112-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0f86ee4e66e232114821f1782edab57047cb4dbc6d04a8aa6517b167bc604fa0", size = 15277898, upload-time = "2026-11-26T16:22:53.753Z" }, + { url = "https://files.pythonhosted.org/packages/30/a3/c4d14e5921b6e691c9bce8241bd84c267a86af91adc0376c4fb27b56310f/ty-0.0.112-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:48b37c1a4ee05d1b15acae818727bfe8cb4fa78698c18a694be9d586379168c8", size = 15202039, upload-time = "2026-11-26T16:22:55.798Z" }, + { url = "https://files.pythonhosted.org/packages/e8/4d/e05186bcb1d07858af3265f135447630b47d051abb073d91a515c18a0c5b/ty-0.0.112-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ed02c9503fffc4cd20d1b2f6fa45df88c9792d841c1e4ec6c97c6381d704b2de", size = 16185393, upload-time = "2026-11-26T16:22:58.107Z" }, + { url = "https://files.pythonhosted.org/packages/1d/db/202ac6d5c8521c233ecbf372e3891ab36797027dcaf4c99c29e8cffd7e20/ty-0.0.112-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dad0794a2831787db9e8bf100de692d3cbe1cd531793c8298989af933bbdc101", size = 16600242, upload-time = "2026-11-26T16:23:00.365Z" }, + { url = "https://files.pythonhosted.org/packages/de/96/bf8de238e4504acd97519cc33e59bc459fe23b494b0fd45558d0645179af/ty-0.0.112-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cb8582035881a64da63934e61d6fceee16b0996d5dabbaec8037cdcc117e4537", size = 16372340, upload-time = "2026-11-26T16:23:02.506Z" }, + { url = "https://files.pythonhosted.org/packages/90/1e/17775cb8fdfe4f752a35cb9a10634d0a2f95c1c7735a20d4268f0cbcc11a/ty-0.0.112-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:209b4b311aebca8b3f02bd9d3b0b412eadd32eaea96bec123c86b80102f04524", size = 17906885, upload-time = "2026-11-26T16:23:04.952Z" }, + { url = "https://files.pythonhosted.org/packages/07/ad/8cb52ea4cc6c41c1eb7f58044e6a0140d729f5aa21106e4c703965d613fb/ty-0.0.112-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:0e8db878efc52b6906f07d9dce6b2a4510fc9107cad8e9ecee94587d8f20fa62", size = 15999108, upload-time = "2026-11-26T16:23:07.493Z" }, + { url = "https://files.pythonhosted.org/packages/5c/75/77f56a59a87ba1f649b3cc01f836c974e28943b5e9c02074467c66ffa9e5/ty-0.0.112-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:13c22ac69db491129495539ec7786fe51ebc65040a5c237ffee057a55d654c00", size = 14844483, upload-time = "2026-11-26T16:23:09.921Z" }, + { url = "https://files.pythonhosted.org/packages/15/19/ee07bf683bb3de6e087e019a5333f36ce43037b9ba0dc255c6a06c1680ab/ty-0.0.112-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:248d4b6a55e6b1b9cb53ab128112e4257b2e8fdfc9e5af01a714b9844297d750", size = 15208021, upload-time = "2026-11-26T16:23:12.33Z" }, + { url = "https://files.pythonhosted.org/packages/b1/17/e69da867f556922031fd3f5aab21db92e798922a5d649cf49f5be726f7f0/ty-0.0.112-py3-none-musllinux_1_2_i686.whl", hash = "sha256:66a9294f13d43b648aab6c16880cfafc05e3730853ef831cfb65ebfdae98b4d3", size = 15545401, upload-time = "2026-11-26T16:23:14.63Z" }, + { url = "https://files.pythonhosted.org/packages/d2/64/c1dd551ae9982f52e0f0dad5280fdc0dd24fb434ade098168ff1ce0bdb20/ty-0.0.112-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:f3e2bd0b33f6e4da2116a00d9b2b5641ab3d17f19d15741d25d20875e4d07942", size = 15876251, upload-time = "2026-11-26T16:23:16.963Z" }, + { url = "https://files.pythonhosted.org/packages/56/81/7bfd693d17590721d8471dcdd6e3d936c5662f4de56bfca40564e2b6e2f3/ty-0.0.112-py3-none-win32.whl", hash = "sha256:b7b1b9ca3c5acc158f49b1c4d840f7ffa45fcc9e3be7868afd23b2311b630e53", size = 14361337, upload-time = "2026-11-26T16:23:19.083Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9f/547d13c03064f1c3b2236b16bdaefd69814239d7b0af67433e662c2686af/ty-0.0.112-py3-none-win_amd64.whl", hash = "sha256:2db7835130bc4b43259c1ae95b627f89fb79ec653ef2935d1aa27e31d84f15ed", size = 15234850, upload-time = "2026-11-26T16:23:21.126Z" }, + { url = "https://files.pythonhosted.org/packages/55/ba/03fea1e8a545d466f777b385c457c6fa8dd0ca3922572c4cb0b7c3a21957/ty-0.0.112-py3-none-win_arm64.whl", hash = "sha256:61272e3547cb98f027e749bf1feee8da5e1a687ffc55f5c33157ebabf6915f23", size = 14435868, upload-time = "2026-11-26T16:23:23.494Z" }, ] [[package]]