fix(tests): build and run the unit test suite on macOS (#28516)

* fix(tests): use snprintf in test_uart_send

The macOS SDK marks sprintf deprecated, and PX4 builds with -Werror
-Wfatal-errors, so this is a hard build failure on macOS before any
test binary is produced:

  test_uart_send.c:83:7: fatal error: 'sprintf' is deprecated

The return value is used as the write() length and snprintf() returns
the length it would have written rather than what fit, so clamp it to
the buffer.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Saibernard Yogendran <bernie97@seas.upenn.edu>

* fix(navigator): give publish_global_pos a float altitude parameter

The test helper declared its altitude parameter double, but it assigns
to vehicle_global_position_s.alt, which is float32, and all eight call
sites pass a float. Every call therefore promoted a float to double and
converted it straight back, which Apple Clang reports as
-Wdouble-promotion and -Werror turns into a build failure.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Saibernard Yogendran <bernie97@seas.upenn.edu>

* fix(tests): use a double NaN for double latitude and longitude fields

The NAN macro is a float, so using it for a double lat/lon field is an
implicit float to double promotion. Apple Clang reports it under
-Wdouble-promotion and -Werror makes it fatal, so these tests could not
be compiled on macOS. Same class of fix as 25596.

Only genuinely double-typed fields are changed: altitude and the other
float members deliberately keep the plain NAN.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Saibernard Yogendran <bernie97@seas.upenn.edu>

* fix(cmake): link the functional gtest stubs with -force_load on macOS

px4_add_functional_gtest() pulls in the daemon app-map stubs with GNU
ld's --whole-archive. Apple's ld64 has no such option and rejects the
link outright:

  ld: unknown options: --whole-archive --no-whole-archive

so every functional gtest failed to link on macOS. ld64 spells the same
thing -force_load <archive>.

test_stubs stays in the link library list on that path: a $<TARGET_FILE:>
inside a link flag does not make the executable depend on the archive, so
editing a stub would rebuild libtest_stubs.a without relinking the tests
that use it.

This affects the 40 px4_add_functional_gtest definitions across the tree.
Non-Apple platforms keep the existing flags unchanged.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Saibernard Yogendran <bernie97@seas.upenn.edu>

* fix(cdev): take the px4_poll deadline from the semaphore's clock

macOS has no pthread_condattr_setclock(), so px4_sem_init() leaves the
condition variable behind px4_sem_t on its default CLOCK_REALTIME, while
px4_poll() built its absolute deadline from CLOCK_MONOTONIC.

On Darwin CLOCK_MONOTONIC counts from boot and CLOCK_REALTIME is the
epoch, so the deadline lands decades in the past: measured on one
machine the two clocks were about 56 years apart. pthread_cond_timedwait()
therefore returned ETIMEDOUT immediately and every px4_poll() with a
positive timeout returned without waiting. The teardown pass then
overwrote the result, so callers just saw px4_poll() == 0.

Take the deadline from CLOCK_REALTIME on Darwin builds without the
lockstep scheduler, which is the clock the wait actually uses. Lockstep
builds provide their own consistent simulated time and are untouched, as
are all other platforms; px4_poll() is the only POSIX caller of
px4_sem_timedwait().

Fixes the uORB poll timeouts in functional-test_mission_route_cache and
sitl-uorb_tests on macOS.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Saibernard Yogendran <bernie97@seas.upenn.edu>

* test(pure_pursuit): compare bearings across the +-pi branch cut

Two cases asserted an exact -M_PI_F. The bearing there is 180 degrees,
which wrap_pi()'s [-pi, pi) range can legitimately represent as either
end, and on macOS the arithmetic lands 2 ULP below +pi. PX4 also builds
with -fno-signed-zeros, so the sign of an atan2f() result at the cut is
not portable in the first place.

Compare the wrapped difference instead, which treats +pi and -pi as the
same bearing, and give it a tolerance that survives the subtraction.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Saibernard Yogendran <bernie97@seas.upenn.edu>

* fix(gps_blending): accumulate the blended timestamp without truncating

Each weighted timestamp was cast to uint64_t before being added, so
every contributing receiver's term lost its fractional microsecond and
the blended timestamp came out low by up to one microsecond per
receiver. The normalised weights are floats, so their rounding error
biased the result further: two receivers reporting an identical
timestamp did not blend back to that timestamp.

Accumulate in double, divide by the accumulated weight, and round once.
The truncation is platform independent; gps_blending_test caught it on
macOS only because the float weights round differently there.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Saibernard Yogendran <bernie97@seas.upenn.edu>

---------

Signed-off-by: Saibernard Yogendran <bernie97@seas.upenn.edu>
Co-authored-by: Farhang <46557204+farhangnaderi@users.noreply.github.com>
This commit is contained in:
SaibernardandFarhang authored and GitHub committed 2026-09-08 22:25:45 -06:00
1 parent d05e3a4a26
commit 0d2c7058b3
9 files changed
+71 -27

No files matched your search

+9 -1
View File
@@ -153,7 +153,15 @@ function(px4_add_functional_gtest)
endif()
# whole-archive so the daemon app-map stubs link even for small
# test libs, where link order would otherwise drop them
list(APPEND _FUNCTIONAL_GTEST_LIBS -Wl,--whole-archive test_stubs -Wl,--no-whole-archive)
if(APPLE)
# ld64 has no --whole-archive, -force_load takes the archive path instead.
# test_stubs is also listed as a link library so the executable relinks
# when the archive changes: a $<TARGET_FILE:> inside a link flag is only
# an order-only dependency and would leave stale stubs in the binary.
list(APPEND _FUNCTIONAL_GTEST_LIBS test_stubs "-Wl,-force_load,$<TARGET_FILE:test_stubs>")
else()
list(APPEND _FUNCTIONAL_GTEST_LIBS -Wl,--whole-archive test_stubs -Wl,--no-whole-archive)
endif()
target_link_libraries(${TESTNAME} PRIVATE ${_FUNCTIONAL_GTEST_LIBS})
target_compile_definitions(${TESTNAME} PRIVATE MODULE_NAME="${TESTNAME}")
+4 -3
View File
@@ -122,19 +122,20 @@ TEST_F(AdsbConflictTest, RejectsInvalidAircraftState)
detect_and_avoid_s daa_output{};
transponder_report_s report = create_relative_report(valid_traffic);
const float nan = std::numeric_limits<float>::quiet_NaN();
const double nan_d = std::numeric_limits<double>::quiet_NaN();
const float inf = std::numeric_limits<float>::infinity();
// non-finite ownship coordinate
EXPECT_FALSE(adsb_conflict.calculate_daa_output(create_daa_input(matrix::Vector2d(nan, uav_lat_lon_(1)), uav_alt_,
EXPECT_FALSE(adsb_conflict.calculate_daa_output(create_daa_input(matrix::Vector2d(nan_d, uav_lat_lon_(1)), uav_alt_,
stationary_uav_vel_ned_, report), daa_output));
EXPECT_FALSE(adsb_conflict.calculate_daa_output(create_daa_input(matrix::Vector2d(uav_lat_lon_(0), nan), uav_alt_,
EXPECT_FALSE(adsb_conflict.calculate_daa_output(create_daa_input(matrix::Vector2d(uav_lat_lon_(0), nan_d), uav_alt_,
stationary_uav_vel_ned_, report), daa_output));
EXPECT_FALSE(adsb_conflict.calculate_daa_output(create_daa_input(matrix::Vector2d(90.1, uav_lat_lon_(1)), uav_alt_,
stationary_uav_vel_ned_, report), daa_output));
EXPECT_FALSE(adsb_conflict.calculate_daa_output(create_daa_input(matrix::Vector2d(uav_lat_lon_(0), -180.1), uav_alt_,
stationary_uav_vel_ned_, report), daa_output));
report.lat = nan;
report.lat = nan_d;
EXPECT_FALSE(adsb_conflict.calculate_daa_output(create_daa_input(uav_lat_lon_, uav_alt_,
stationary_uav_vel_ned_, report), daa_output));
report = create_relative_report(valid_traffic);
+9
View File
@@ -392,9 +392,18 @@ extern "C" {
if (timeout > 0) {
// Get the current time
struct timespec ts;
#if defined(__PX4_DARWIN) && !defined(ENABLE_LOCKSTEP_SCHEDULER)
// macOS has no pthread_condattr_setclock(), so the condition variable
// behind px4_sem_t waits on CLOCK_REALTIME (see px4_sem_init()). The
// deadline has to be taken from that same clock: CLOCK_MONOTONIC counts
// from boot, so passing it here puts the deadline decades in the past and
// px4_sem_timedwait() returns ETIMEDOUT immediately instead of waiting.
px4_clock_gettime(CLOCK_REALTIME, &ts);
#else
// Note, we can't actually use CLOCK_MONOTONIC on macOS
// but that's hidden and implemented in px4_clock_gettime.
px4_clock_gettime(CLOCK_MONOTONIC, &ts);
#endif
// Calculate an absolute time in the future
const unsigned billion = (1000 * 1000 * 1000);
+5 -2
View File
@@ -150,7 +150,9 @@ TEST(PurePursuitTest, OutOfLookahead)
Vector2f(0.f, 0.f), Vector2f(10.f, 20.f), lookahead_distance);
EXPECT_NEAR(target_bearing1, M_PI_2_F + M_PI_4_F, FLT_EPSILON); // Fallback: Bearing to closest point on path
EXPECT_NEAR(target_bearing2, -M_PI_F, FLT_EPSILON); // Fallback: Bearing to closest point on path
// -pi and +pi are the same bearing, and which side of the branch cut the arithmetic
// lands on is not portable, so compare the wrapped difference instead of the raw value.
EXPECT_NEAR(wrap_pi(target_bearing2 - (-M_PI_F)), 0.f, 1e-6f); // Fallback: Bearing to closest point on path
EXPECT_NEAR(target_bearing3, M_PI_F - atan2f(10, 10), FLT_EPSILON); // Fallback: Bearing to previous waypoint
EXPECT_NEAR(target_bearing4, -M_PI_F + atan2f(10, 10), FLT_EPSILON); // Fallback: Bearing to current waypoint
}
@@ -202,7 +204,8 @@ TEST(PurePursuitTest, CurrAndPrevSameNorthCoordinate)
EXPECT_NEAR(target_bearing1, M_PI_2_F, FLT_EPSILON);
EXPECT_NEAR(target_bearing2, M_PI_2_F + M_PI_4_F, FLT_EPSILON);
EXPECT_NEAR(target_bearing3, -(M_PI_2_F + M_PI_4_F), FLT_EPSILON);
EXPECT_NEAR(target_bearing4, -M_PI_F, FLT_EPSILON); // Fallback: Bearing to closest point on path
// See above: compare across the +-pi branch cut with the wrapped difference.
EXPECT_NEAR(wrap_pi(target_bearing4 - (-M_PI_F)), 0.f, 1e-6f); // Fallback: Bearing to closest point on path
}
TEST(PurePursuitTest, CrosstrackError)
@@ -250,7 +250,7 @@ public:
_vehicle_local_position_pub.publish(l_pos);
}
void publish_global_pos(const double lat, const double lon, const double alt,
void publish_global_pos(const double lat, const double lon, const float alt,
const hrt_abstime timestamp = hrt_absolute_time(), const bool lat_lon_valid = true,
const bool alt_valid = true)
{
@@ -281,8 +281,8 @@ TEST_F(GeofenceAvoidancePlannerTest, NanStartOrDestination)
{
using namespace matrix;
Vector2<double> valid(47.3977, 8.5456);
Vector2<double> nan_lat(NAN, 8.5456);
Vector2<double> nan_lon(47.3977, NAN);
Vector2<double> nan_lat(static_cast<double>(NAN), 8.5456);
Vector2<double> nan_lon(47.3977, static_cast<double>(NAN));
FakeGeofence fake(nullptr, 0, NAV_CMD_FENCE_POLYGON_VERTEX_INCLUSION);
_planner.updateGraphFromGeofence(fake, 0.f);
+16 -15
View File
@@ -71,6 +71,7 @@ namespace
constexpr double kBaseLat = 47.397742;
constexpr double kBaseLon = 8.545594;
constexpr float kAlt = 500.f;
constexpr double kNanDouble = static_cast<double>(NAN);
constexpr float kApproachRadius = 50.f;
mission_item_s makeSafePointItem(double lat, double lon, float altitude, NAV_FRAME frame,
@@ -996,8 +997,8 @@ ExtractValidSafePointPositionCase{
makeSafePointItem(kBaseLat, kBaseLon, 25.f, NAV_FRAME_GLOBAL_RELATIVE_ALT),
NAN,
false,
NAN,
NAN,
kNanDouble,
kNanDouble,
NAN,
},
ExtractValidSafePointPositionCase{
@@ -1005,8 +1006,8 @@ ExtractValidSafePointPositionCase{
makeSafePointItem(kBaseLat, kBaseLon, 510.f, NAV_FRAME_MISSION),
kAlt,
false,
NAN,
NAN,
kNanDouble,
kNanDouble,
NAN,
},
ExtractValidSafePointPositionCase{
@@ -1014,17 +1015,17 @@ ExtractValidSafePointPositionCase{
makeSafePointItem(kBaseLat, kBaseLon, 510.f, NAV_FRAME_GLOBAL, NAV_CMD_WAYPOINT),
kAlt,
false,
NAN,
NAN,
kNanDouble,
kNanDouble,
NAN,
},
ExtractValidSafePointPositionCase{
"NanLatitude",
makeSafePointItem(NAN, kBaseLon, 510.f, NAV_FRAME_GLOBAL),
makeSafePointItem(kNanDouble, kBaseLon, 510.f, NAV_FRAME_GLOBAL),
kAlt,
false,
NAN,
NAN,
kNanDouble,
kNanDouble,
NAN,
},
ExtractValidSafePointPositionCase{
@@ -1032,8 +1033,8 @@ ExtractValidSafePointPositionCase{
makeSafePointItem(0.0, 0.0, 510.f, NAV_FRAME_GLOBAL),
kAlt,
false,
NAN,
NAN,
kNanDouble,
kNanDouble,
NAN,
},
ExtractValidSafePointPositionCase{
@@ -1041,8 +1042,8 @@ ExtractValidSafePointPositionCase{
makeSafePointItem(91.0, kBaseLon, 510.f, NAV_FRAME_GLOBAL),
kAlt,
false,
NAN,
NAN,
kNanDouble,
kNanDouble,
NAN,
},
ExtractValidSafePointPositionCase{
@@ -1050,8 +1051,8 @@ ExtractValidSafePointPositionCase{
makeSafePointItem(kBaseLat, 181.0, 510.f, NAV_FRAME_GLOBAL),
kAlt,
false,
NAN,
NAN,
kNanDouble,
kNanDouble,
NAN,
}),
[](const ::testing::TestParamInfo<ExtractValidSafePointPositionTest::ParamType> &param_info)
@@ -391,6 +391,15 @@ sensor_gps_s GpsBlending::gps_blend_states(float blend_weights[GPS_MAX_RECEIVERS
gps_blended_state.vel_e_m_s = 0;
gps_blended_state.vel_d_m_s = 0;
// Accumulate the blended timestamps in double and round once at the end: casting each
// weighted term to uint64_t truncates it, which biases the result low by up to one
// microsecond per contributing receiver. Dividing by the accumulated weight also removes
// the float rounding error in the normalised weights, so receivers reporting an identical
// timestamp blend back to exactly that timestamp.
double blended_timestamp_us = 0.0;
double blended_timestamp_sample_us = 0.0;
double sum_of_timing_weights = 0.0;
// combine the the GPS states into a blended solution using the weights calculated in calc_blend_weights()
for (uint8_t i = 0; i < GPS_MAX_RECEIVERS_BLEND; i++) {
// Assume blended error magnitude, DOP and sat count is equal to the best value from contributing receivers
@@ -398,8 +407,10 @@ sensor_gps_s GpsBlending::gps_blend_states(float blend_weights[GPS_MAX_RECEIVERS
if (blend_weights[i] > 0.0f) {
// blend the timing data
gps_blended_state.timestamp += (uint64_t)((double)_gps_state[i].timestamp * (double)blend_weights[i]);
gps_blended_state.timestamp_sample += (uint64_t)((double)_gps_state[i].timestamp_sample * (double)blend_weights[i]);
const double timing_weight = (double)blend_weights[i];
blended_timestamp_us += (double)_gps_state[i].timestamp * timing_weight;
blended_timestamp_sample_us += (double)_gps_state[i].timestamp_sample * timing_weight;
sum_of_timing_weights += timing_weight;
// calculate a blended average speed and velocity vector
gps_blended_state.vel_m_s += _gps_state[i].vel_m_s * blend_weights[i];
@@ -451,6 +462,11 @@ sensor_gps_s GpsBlending::gps_blend_states(float blend_weights[GPS_MAX_RECEIVERS
}
if (sum_of_timing_weights > 0.0) {
gps_blended_state.timestamp = (uint64_t)llround(blended_timestamp_us / sum_of_timing_weights);
gps_blended_state.timestamp_sample = (uint64_t)llround(blended_timestamp_sample_us / sum_of_timing_weights);
}
/*
* Calculate the instantaneous weighted average location using available GPS instances and store in _gps_state.
* This is statistically the most likely location, but may not be stable enough for direct use by the EKF.
+7 -1
View File
@@ -80,7 +80,13 @@ int test_uart_send(int argc, char *argv[])
uint64_t start_time = hrt_absolute_time();
for (i = 0; i < 30000; i++) {
n = sprintf(sample_test_uart, "SAMPLE #%d\n", i);
n = snprintf(sample_test_uart, sizeof(sample_test_uart), "SAMPLE #%d\n", i);
// snprintf() returns the length it would have written, clamp to what fit
if (n > (int)sizeof(sample_test_uart) - 1) {
n = (int)sizeof(sample_test_uart) - 1;
}
write(test_uart, sample_test_uart, n);
}