fix: harden firmware builds and runtime reliability
This commit is contained in:
1 parent
66c9e3f73b
commit
bd3a94bddb
71 files changed
+2102
-466
No files matched your search
@@ -66,6 +66,9 @@ does not reflect the GoogleTest count -- run the built binary directly
|
||||
| `test_power_management` | `src/helpers/PowerManagementUtils.h` | median filtering of a brownout outlier and valid-reading requirements for the boot lock |
|
||||
| `test_rx_power_saving` | `src/helpers/radiolib/RXPowerSaving.h` | level-derived timing, tuple-selected 32/64/128-symbol wire preambles, equivalent SF7/BW500, SF6/BW250, and SF5/BW125 profiles, SF5/BW250 and SF6/BW500 level-8/64 timing, SF5/BW500 level-8/128 timing, SF5/BW62.5 with a 16-symbol timing assumption, automatic retuning, and SX1262 TCXO timing thresholds |
|
||||
| `test_region_names` | `src/helpers/RegionNameUtils.h` | canonical public-region markers while preserving distinct private and differently named regions |
|
||||
| `test_datagram_payload_limits` | `src/helpers/DatagramPayloadLimits.h` | encrypted datagram plaintext ceilings, including the anonymous region-reply prefix and worst-case cipher padding |
|
||||
| `test_serial_packet_log` | `src/helpers/SerialPacketLog.h` | bounded USB packet logging and dropped-line reporting |
|
||||
| `test_alert_fault_policy` | `src/helpers/AlertFaultPolicy.h` | coherent WiFi/MQTT outage edges, durations, rate limits, and formatting |
|
||||
| `test_routing_policy` | `src/helpers/RoutingPolicy.h` | scoped/unscoped flood hop limits and selection of direct, path-return, mirrored-scope, default-scope, or unscoped replies |
|
||||
| `test_rs232_uart` | `src/helpers/bridges/RS232UartUtils.h` | stopping the active UART peripheral before reassigning its pins |
|
||||
| `test_security_session_timer` | `src/helpers/nrf52/SecuritySessionTimer.h` | two-minute security-session expiry, cancellation, restart, and `millis()` rollover |
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <limits>
|
||||
|
||||
#include "helpers/AlertFaultPolicy.h"
|
||||
|
||||
namespace Alert = AlertFaultPolicy;
|
||||
|
||||
namespace {
|
||||
|
||||
Alert::Fault okFault() {
|
||||
Alert::Fault fault{};
|
||||
fault.state = Alert::State::OK;
|
||||
return fault;
|
||||
}
|
||||
|
||||
Alert::OutageSnapshot down(uint32_t start, uint8_t reason = 0) {
|
||||
Alert::OutageSnapshot snapshot{};
|
||||
snapshot.down = true;
|
||||
snapshot.started_ms = start;
|
||||
snapshot.reason = reason;
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(AlertFaultPolicy, PreservesFirstOutageReasonAcrossReconnectAttempts) {
|
||||
Alert::OutageSnapshot snapshot{};
|
||||
snapshot = Alert::applyWifiDisconnectEvent(1000, 200, snapshot);
|
||||
snapshot = Alert::applyWifiDisconnectEvent(16000, 8, snapshot);
|
||||
EXPECT_TRUE(snapshot.down);
|
||||
EXPECT_EQ(1000U, snapshot.started_ms);
|
||||
EXPECT_EQ(200U, snapshot.reason);
|
||||
}
|
||||
|
||||
TEST(AlertFaultPolicy, GotIpClosesAnOutageBetweenStatusPolls) {
|
||||
Alert::OutageSnapshot snapshot = down(1000, 200);
|
||||
snapshot = Alert::applyWifiGotIp(snapshot);
|
||||
EXPECT_FALSE(snapshot.down);
|
||||
EXPECT_EQ(0U, snapshot.started_ms);
|
||||
EXPECT_EQ(0U, snapshot.reason);
|
||||
}
|
||||
|
||||
TEST(AlertFaultPolicy, PackedSnapshotRepresentsOutageAtMillisZero) {
|
||||
std::atomic<uint64_t> value{0};
|
||||
value.store(Alert::packOutageSnapshot(down(0, 200)),
|
||||
std::memory_order_release);
|
||||
Alert::OutageSnapshot snapshot = Alert::unpackOutageSnapshot(
|
||||
value.load(std::memory_order_acquire));
|
||||
EXPECT_TRUE(snapshot.down);
|
||||
EXPECT_EQ(0U, snapshot.started_ms);
|
||||
EXPECT_EQ(200U, snapshot.reason);
|
||||
}
|
||||
|
||||
TEST(AlertFaultPolicy, FiresAtThresholdAndFormatsInitiatingReason) {
|
||||
Alert::Fault fault = okFault();
|
||||
const uint32_t threshold = Alert::thresholdMs(30);
|
||||
Alert::OutageSnapshot snapshot = down(1000, 200);
|
||||
Alert::TickResult result = Alert::tick(
|
||||
fault, 1000 + threshold, snapshot, threshold,
|
||||
Alert::minIntervalMs(60));
|
||||
EXPECT_EQ(Alert::Action::FireDown, result.action);
|
||||
|
||||
char text[80];
|
||||
ASSERT_TRUE(Alert::formatWifiAlert(text, sizeof(text), result, snapshot));
|
||||
EXPECT_STREQ("WiFi down 30m (reason 200)", text);
|
||||
}
|
||||
|
||||
TEST(AlertFaultPolicy, RecoveryUsesRememberedOutageStart) {
|
||||
Alert::Fault fault = okFault();
|
||||
Alert::commitDown(fault, 1801000U, 1000U);
|
||||
Alert::OutageSnapshot up{};
|
||||
Alert::TickResult result = Alert::tick(
|
||||
fault, 7501000U, up, Alert::thresholdMs(30),
|
||||
Alert::minIntervalMs(60));
|
||||
EXPECT_EQ(Alert::Action::FireRecovered, result.action);
|
||||
EXPECT_EQ(7500000U, result.duration_ms);
|
||||
}
|
||||
|
||||
TEST(AlertFaultPolicy, FirstAlertIsNotSuppressedByUptime) {
|
||||
Alert::Fault fault = okFault();
|
||||
const uint32_t threshold = Alert::thresholdMs(1);
|
||||
Alert::TickResult result = Alert::tick(
|
||||
fault, threshold, down(0), threshold, Alert::minIntervalMs(60));
|
||||
EXPECT_EQ(Alert::Action::FireDown, result.action);
|
||||
}
|
||||
|
||||
TEST(AlertFaultPolicy, MinimumIntervalHasOneHourFloor) {
|
||||
EXPECT_EQ(3600000U, Alert::minIntervalMs(0));
|
||||
EXPECT_EQ(3600000U, Alert::minIntervalMs(59));
|
||||
EXPECT_EQ(7200000U, Alert::minIntervalMs(120));
|
||||
}
|
||||
|
||||
TEST(AlertFaultPolicy, DurationAndCadenceSurviveMillisRollover) {
|
||||
const uint32_t start = std::numeric_limits<uint32_t>::max() - 999U;
|
||||
EXPECT_EQ(1500U, Alert::elapsedMs(500U, start));
|
||||
EXPECT_TRUE(Alert::checkDue(500U, 400U));
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "helpers/DatagramPayloadLimits.h"
|
||||
|
||||
TEST(DatagramPayloadLimits, MeshDatagramPlaintextLimitIncludesWorstCasePadding) {
|
||||
EXPECT_EQ(167U, DatagramPayloadLimits::maxPlaintext(184, 2, 16));
|
||||
}
|
||||
|
||||
TEST(DatagramPayloadLimits, RegionReplyLeavesRoomForItsEightBytePrefix) {
|
||||
const size_t reply_limit = DatagramPayloadLimits::maxPlaintext(184, 2, 16);
|
||||
ASSERT_GE(reply_limit, 8U);
|
||||
EXPECT_EQ(159U, reply_limit - 8U);
|
||||
}
|
||||
|
||||
TEST(DatagramPayloadLimits, InvalidGeometryFailsClosed) {
|
||||
EXPECT_EQ(0U, DatagramPayloadLimits::maxPlaintext(184, 2, 0));
|
||||
EXPECT_EQ(0U, DatagramPayloadLimits::maxPlaintext(8, 2, 16));
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -179,12 +179,15 @@ assert.strictEqual(v4Full.dedicatedUsbLogging, true);
|
||||
{ installKinds: ["bin"] }
|
||||
);
|
||||
});
|
||||
const classified = picker.applyDualCdcFullCompanionCapabilities(candidates);
|
||||
assert.strictEqual(classified[0].logging, "none");
|
||||
const classified = picker.applyFullCompanionCapabilities(candidates);
|
||||
assert.strictEqual(classified[0].logging, "usb-runtime");
|
||||
assert.deepStrictEqual(classified[0].loggingModes, ["none", "usb"]);
|
||||
assert.strictEqual(classified[0].dedicatedUsbLogging, undefined);
|
||||
assert.strictEqual(
|
||||
picker.omitTransportsReplacedByDualCdcFull(classified).length,
|
||||
candidates.length
|
||||
assert.deepStrictEqual(
|
||||
picker.omitTransportsReplacedByFull(classified).map(function (item) {
|
||||
return item.target;
|
||||
}),
|
||||
[hardware + "_companion_radio_full"]
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -137,6 +137,33 @@ TEST(MQTTConnectionPolicy, SyncedClockRenewsInvalidExpiredOrImminentTokens) {
|
||||
EXPECT_TRUE(Policy::tokenNeedsRenewal(true, expires + 1U, expires, 300U));
|
||||
}
|
||||
|
||||
TEST(MQTTConnectionPolicy, JwtReconnectReusesOnlyProvenValidCredentials) {
|
||||
const uint32_t now = 1735689600U;
|
||||
const uint32_t usable_expiry =
|
||||
now + Policy::kJwtReconnectSafetyMarginSecs + 1U;
|
||||
|
||||
EXPECT_TRUE(Policy::canReuseJwtForReconnect(
|
||||
true, true, false, now, usable_expiry, 0));
|
||||
EXPECT_FALSE(Policy::canReuseJwtForReconnect(
|
||||
true, true, false, now, Policy::kMinimumValidEpoch - 1U, 0));
|
||||
EXPECT_FALSE(Policy::canReuseJwtForReconnect(
|
||||
true, true, false, now, 0U, 0));
|
||||
EXPECT_FALSE(Policy::canReuseJwtForReconnect(
|
||||
true, true, false, now,
|
||||
now + Policy::kJwtReconnectSafetyMarginSecs, 0));
|
||||
EXPECT_FALSE(Policy::canReuseJwtForReconnect(
|
||||
true, false, false, now, usable_expiry, 0));
|
||||
EXPECT_FALSE(Policy::canReuseJwtForReconnect(
|
||||
false, true, false, now, usable_expiry, 0));
|
||||
EXPECT_FALSE(Policy::canReuseJwtForReconnect(
|
||||
true, true, true, now, usable_expiry, 0));
|
||||
|
||||
EXPECT_FALSE(Policy::canReuseJwtForReconnect(
|
||||
true, true, false, now, now + 360U, 300U));
|
||||
EXPECT_TRUE(Policy::canReuseJwtForReconnect(
|
||||
true, true, false, now, now + 361U, 300U));
|
||||
}
|
||||
|
||||
TEST(MQTTConnectionPolicy, RenewalThrottleHasExactBoundaryAndHandlesRollover) {
|
||||
EXPECT_FALSE(Policy::renewalAttemptAllowed(59999U, 0U));
|
||||
EXPECT_TRUE(Policy::renewalAttemptAllowed(60000U, 0U));
|
||||
@@ -242,6 +269,48 @@ TEST(SlotActivation, DisabledAndOutOfRangeSlots) {
|
||||
EXPECT_EQ(SlotActivation::Disabled, Policy::classifySlotActivation(0, nullptr, 3, 2));
|
||||
}
|
||||
|
||||
using Policy::StaleTokenAction;
|
||||
|
||||
TEST(StaleToken, ChoosesSafeLiveAndDisconnectedActions) {
|
||||
EXPECT_EQ(StaleTokenAction::Bounce,
|
||||
Policy::classifyStaleToken(true, true, true));
|
||||
EXPECT_EQ(StaleTokenAction::KeepAlive,
|
||||
Policy::classifyStaleToken(true, true, false));
|
||||
EXPECT_EQ(StaleTokenAction::Reconnect,
|
||||
Policy::classifyStaleToken(true, false, true));
|
||||
EXPECT_EQ(StaleTokenAction::Reconnect,
|
||||
Policy::classifyStaleToken(true, false, false));
|
||||
}
|
||||
|
||||
TEST(StaleToken, FailedMintAlwaysDefers) {
|
||||
EXPECT_EQ(StaleTokenAction::Defer,
|
||||
Policy::classifyStaleToken(false, false, true));
|
||||
EXPECT_EQ(StaleTokenAction::Defer,
|
||||
Policy::classifyStaleToken(false, false, false));
|
||||
EXPECT_EQ(StaleTokenAction::Defer,
|
||||
Policy::classifyStaleToken(false, true, true));
|
||||
EXPECT_EQ(StaleTokenAction::Defer,
|
||||
Policy::classifyStaleToken(false, true, false));
|
||||
}
|
||||
|
||||
using Policy::ClockSource;
|
||||
|
||||
TEST(FallbackClock, PrefersSystemThenRtcAndRejectsInvalidSources) {
|
||||
const uint32_t floor = 1767225600U;
|
||||
const uint32_t old_time = 1715770351U;
|
||||
const uint32_t plausible = 1786000000U;
|
||||
|
||||
EXPECT_EQ(ClockSource::System,
|
||||
Policy::chooseFallbackClock(false, plausible, plausible - 900U,
|
||||
floor));
|
||||
EXPECT_EQ(ClockSource::Rtc,
|
||||
Policy::chooseFallbackClock(false, old_time, plausible, floor));
|
||||
EXPECT_EQ(ClockSource::None,
|
||||
Policy::chooseFallbackClock(false, old_time, old_time, floor));
|
||||
EXPECT_EQ(ClockSource::None,
|
||||
Policy::chooseFallbackClock(true, plausible, plausible, floor));
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
|
||||
@@ -183,6 +183,22 @@ TEST(MQTTPayloadBuilder, RxPacketOmitsUnknownNanScore) {
|
||||
EXPECT_FALSE(parsed["score"].is<JsonVariant>());
|
||||
}
|
||||
|
||||
TEST(MQTTPayloadBuilder, RxPacketOmitsUnknownRadioMetrics) {
|
||||
JsonDocument scratch;
|
||||
char buffer[2048];
|
||||
int len = MQTTPayloadBuilder::buildPacketMessage(
|
||||
scratch, "node", "id", kTimestamp, "rx", "12:34:56", "18/07/2026",
|
||||
42, 4, "D", 20, "A0B1", -999.0f, -999, std::nanf(""), "hash",
|
||||
nullptr, 0, 0, 64, buffer, sizeof(buffer));
|
||||
|
||||
ASSERT_GT(len, 0);
|
||||
JsonDocument parsed;
|
||||
ASSERT_FALSE(deserializeJson(parsed, buffer));
|
||||
EXPECT_FALSE(parsed["SNR"].is<JsonVariant>());
|
||||
EXPECT_FALSE(parsed["RSSI"].is<JsonVariant>());
|
||||
EXPECT_FALSE(parsed["score"].is<JsonVariant>());
|
||||
}
|
||||
|
||||
TEST(MQTTPayloadBuilder, RawMessageHasExactContractAndEscapesData) {
|
||||
char buffer[512];
|
||||
JsonDocument doc;
|
||||
@@ -254,6 +270,8 @@ TEST(MQTTPayloadBuilder, NeighborsMessageRoundTripsSelfAndEntries) {
|
||||
{"0011223344556677", 9.75f, 42, "DEN,APRS", "active"},
|
||||
{"8899AABBCCDDEEFF", -3.5f, 3600, "", "stale"},
|
||||
};
|
||||
neighbors[0].rssi = -87;
|
||||
neighbors[1].rssi = -110;
|
||||
|
||||
JsonDocument scratch;
|
||||
char buffer[1024];
|
||||
@@ -278,10 +296,12 @@ TEST(MQTTPayloadBuilder, NeighborsMessageRoundTripsSelfAndEntries) {
|
||||
ASSERT_EQ(2U, arr.size());
|
||||
EXPECT_STREQ("0011223344556677", arr[0]["pubkey"].as<const char*>());
|
||||
EXPECT_FLOAT_EQ(9.75f, arr[0]["snr"].as<float>());
|
||||
EXPECT_EQ(-87, arr[0]["rssi"].as<int>());
|
||||
EXPECT_EQ(42U, arr[0]["heard_secs_ago"].as<uint32_t>());
|
||||
EXPECT_STREQ("DEN,APRS", arr[0]["scopes"].as<const char*>());
|
||||
EXPECT_STREQ("active", arr[0]["status"].as<const char*>());
|
||||
EXPECT_STREQ("8899AABBCCDDEEFF", arr[1]["pubkey"].as<const char*>());
|
||||
EXPECT_EQ(-110, arr[1]["rssi"].as<int>());
|
||||
EXPECT_STREQ("", arr[1]["scopes"].as<const char*>());
|
||||
EXPECT_STREQ("stale", arr[1]["status"].as<const char*>());
|
||||
}
|
||||
@@ -291,6 +311,8 @@ TEST(MQTTPayloadBuilder, NeighborsMessageMeasurementsMatchCompletePayload) {
|
||||
{"0011223344556677", 9.75f, UINT32_MAX, "DEN,APRS", "responded"},
|
||||
{"8899AABBCCDDEEFF", -3.5f, UINT32_MAX, "", "timeout"},
|
||||
};
|
||||
neighbors[0].rssi = -87;
|
||||
neighbors[1].rssi = -110;
|
||||
|
||||
size_t measured =
|
||||
MQTTPayloadBuilder::measureNeighborsMessageBase(
|
||||
@@ -320,6 +342,7 @@ TEST(MQTTPayloadBuilder, NeighborsMessageMeasuredPrefixStopsBeforeOverflow) {
|
||||
neighbors[i] = {
|
||||
keys[i], static_cast<float>(i), UINT32_MAX,
|
||||
long_scopes, "responded"};
|
||||
neighbors[i].rssi = -90 - i;
|
||||
}
|
||||
|
||||
constexpr size_t kBufferSize = 512;
|
||||
@@ -364,6 +387,8 @@ TEST(MQTTPayloadBuilder, NeighborsMessageFallbackMarksTruncated) {
|
||||
{"0011223344556677", 9.75f, 1, "DEN", "responded"},
|
||||
{"8899AABBCCDDEEFF", -3.5f, 2, "APRS", "responded"},
|
||||
};
|
||||
neighbors[0].rssi = -87;
|
||||
neighbors[1].rssi = -110;
|
||||
size_t first_only_size =
|
||||
MQTTPayloadBuilder::measureNeighborsMessageBase(
|
||||
"node", "id", kTimestamp, "DEN", "*", 2)
|
||||
@@ -386,6 +411,7 @@ TEST(MQTTPayloadBuilder, NeighborsMessageFallbackMarksTruncated) {
|
||||
TEST(MQTTPayloadBuilder, NeighborsMessageFailsCleanlyOnAllocationFailure) {
|
||||
MQTTPayloadBuilder::NeighborsMessageEntry neighbor = {
|
||||
"0011223344556677", 9.75f, 1, "DEN", "responded"};
|
||||
neighbor.rssi = -87;
|
||||
RejectAllJsonAllocations allocator;
|
||||
JsonDocument scratch(&allocator);
|
||||
char buffer[512];
|
||||
@@ -422,6 +448,7 @@ TEST(MQTTPayloadBuilder, NeighborsMessageDropsTailWhenBufferFills) {
|
||||
snprintf(keys[i], sizeof(keys[i]), "%016X", i);
|
||||
neighbors[i].pubkey_hex = keys[i];
|
||||
neighbors[i].snr = static_cast<float>(i);
|
||||
neighbors[i].rssi = -90 - i;
|
||||
neighbors[i].heard_secs_ago = static_cast<uint32_t>(i) * 10U;
|
||||
neighbors[i].heard_unknown = false;
|
||||
neighbors[i].scopes = "DEN";
|
||||
@@ -453,6 +480,8 @@ TEST(MQTTPayloadBuilder, NeighborsMessageRendersUnknownHeardAgeAsNull) {
|
||||
MQTTPayloadBuilder::NeighborsMessageEntry neighbors[2];
|
||||
neighbors[0] = {"0011223344556677", 9.75f, 42, "DEN", "responded"};
|
||||
neighbors[1] = {"8899AABBCCDDEEFF", -3.5f, 0, "DEN", "responded"};
|
||||
neighbors[0].rssi = -87;
|
||||
neighbors[1].rssi = -110;
|
||||
neighbors[1].heard_unknown = true;
|
||||
|
||||
JsonDocument scratch;
|
||||
@@ -480,6 +509,7 @@ TEST(MQTTPayloadBuilder, NeighborsMessageUnknownHeardAgeFitsMeasuredWidth) {
|
||||
// must never serialize wider than what that reserved.
|
||||
MQTTPayloadBuilder::NeighborsMessageEntry measured = {
|
||||
"0011223344556677", 9.75f, UINT32_MAX, "DEN", "responded"};
|
||||
measured.rssi = -87;
|
||||
MQTTPayloadBuilder::NeighborsMessageEntry unknown = measured;
|
||||
unknown.heard_unknown = true;
|
||||
unknown.heard_secs_ago = 0;
|
||||
|
||||
@@ -88,6 +88,13 @@ TEST(ReplyAppendf, NoWritePastBufferAcrossOverflowingChain) {
|
||||
EXPECT_EQ(c.buf()[c.logical - 1], '\0'); // still NUL-terminated
|
||||
}
|
||||
|
||||
TEST(MbedtlsErrorMagnitude, NormalizesEitherSignAndInt32Min) {
|
||||
EXPECT_EQ(0x7F00U, mbedtlsErrorMagnitude(0x7F00));
|
||||
EXPECT_EQ(0x7F00U, mbedtlsErrorMagnitude(-0x7F00));
|
||||
EXPECT_EQ(0U, mbedtlsErrorMagnitude(0));
|
||||
EXPECT_EQ(2147483648U, mbedtlsErrorMagnitude(INT32_MIN));
|
||||
}
|
||||
|
||||
TEST(ReplyAppendf, ExactFitBoundary) {
|
||||
char buf[11]; // room for exactly "0123456789" + NUL
|
||||
int pos = 0;
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include "helpers/SerialPacketLog.h"
|
||||
|
||||
namespace {
|
||||
|
||||
class FakePort : public Stream {
|
||||
public:
|
||||
explicit FakePort(size_t capacity = 64, size_t bytes_per_ms = 64)
|
||||
: _capacity(capacity),
|
||||
_free(capacity),
|
||||
_rate(bytes_per_ms),
|
||||
_last_ms(millis()) {}
|
||||
|
||||
int availableForWrite() override {
|
||||
uint32_t now = millis();
|
||||
_free += (size_t)(now - _last_ms) * _rate;
|
||||
_last_ms = now;
|
||||
if (_free > _capacity) _free = _capacity;
|
||||
return (int)_free;
|
||||
}
|
||||
|
||||
size_t write(const uint8_t* buffer, size_t size) override {
|
||||
if (size > _free) size = _free;
|
||||
_written.append(reinterpret_cast<const char*>(buffer), size);
|
||||
_free -= size;
|
||||
if (_written.size() >= _wedge_after) wedge();
|
||||
return size;
|
||||
}
|
||||
|
||||
void wedge() {
|
||||
availableForWrite();
|
||||
_rate = 0;
|
||||
_free = 0;
|
||||
}
|
||||
void wedgeAfter(size_t bytes) { _wedge_after = bytes; }
|
||||
const std::string& written() const { return _written; }
|
||||
|
||||
private:
|
||||
size_t _capacity;
|
||||
size_t _free;
|
||||
size_t _rate;
|
||||
size_t _wedge_after = (size_t)-1;
|
||||
uint32_t _last_ms;
|
||||
std::string _written;
|
||||
};
|
||||
|
||||
class SerialPacketLogTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
g_mock_millis = 1000;
|
||||
mesh::serialLogDroppedCount() = 0;
|
||||
mesh::serialLogPortSeen() = false;
|
||||
}
|
||||
|
||||
static void primePort() {
|
||||
FakePort port(4096);
|
||||
mesh::SerialLogLine<> line;
|
||||
line.printf("primed");
|
||||
ASSERT_TRUE(line.flush(port));
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(SerialPacketLogTest, WritesWholeLineThroughSmallFifo) {
|
||||
FakePort port;
|
||||
uint8_t raw[40];
|
||||
for (size_t i = 0; i < sizeof(raw); i++) raw[i] = (uint8_t)i;
|
||||
|
||||
mesh::SerialLogLine<> line;
|
||||
line.printf("RAW: ");
|
||||
line.hex(raw, sizeof(raw));
|
||||
EXPECT_TRUE(line.flush(port));
|
||||
EXPECT_NE(std::string::npos, port.written().find("000102"));
|
||||
EXPECT_EQ(0U, mesh::serialLogDroppedCount());
|
||||
}
|
||||
|
||||
TEST_F(SerialPacketLogTest, DropsImmediatelyWhenHostStopsDraining) {
|
||||
primePort();
|
||||
FakePort port;
|
||||
port.wedge();
|
||||
|
||||
uint32_t before = millis();
|
||||
mesh::SerialLogLine<> line;
|
||||
line.printf("RAW: 0102");
|
||||
EXPECT_FALSE(line.flush(port));
|
||||
EXPECT_EQ(before, millis());
|
||||
EXPECT_TRUE(port.written().empty());
|
||||
EXPECT_EQ(1U, mesh::serialLogDroppedCount());
|
||||
}
|
||||
|
||||
TEST_F(SerialPacketLogTest, GivesUpWithinBudgetWhenHostWedgesMidLine) {
|
||||
primePort();
|
||||
FakePort port(64, 64);
|
||||
port.wedgeAfter(64);
|
||||
uint8_t raw[200];
|
||||
memset(raw, 0xA5, sizeof(raw));
|
||||
|
||||
mesh::SerialLogLine<> line;
|
||||
line.hex(raw, sizeof(raw));
|
||||
uint32_t before = millis();
|
||||
EXPECT_FALSE(line.flush(port));
|
||||
uint32_t waited = millis() - before;
|
||||
EXPECT_GE(waited, (uint32_t)SERIAL_LOG_WRITE_BUDGET_MS);
|
||||
EXPECT_LE(waited, (uint32_t)SERIAL_LOG_WRITE_BUDGET_MS + 2);
|
||||
EXPECT_EQ(1U, mesh::serialLogDroppedCount());
|
||||
}
|
||||
|
||||
TEST_F(SerialPacketLogTest, ReportsDropsAfterHostRecovers) {
|
||||
primePort();
|
||||
FakePort wedged;
|
||||
wedged.wedge();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
mesh::SerialLogLine<> line;
|
||||
line.printf("RAW: 00");
|
||||
EXPECT_FALSE(line.flush(wedged));
|
||||
}
|
||||
|
||||
FakePort recovered(4096);
|
||||
mesh::SerialLogLine<> line;
|
||||
line.printf("RAW: 01");
|
||||
EXPECT_TRUE(line.flush(recovered));
|
||||
EXPECT_EQ("DROP:3\r\nRAW: 01\r\n", recovered.written());
|
||||
}
|
||||
|
||||
TEST_F(SerialPacketLogTest, IgnoresDropsBeforeAnyHostConnects) {
|
||||
FakePort unattached;
|
||||
unattached.wedge();
|
||||
mesh::SerialLogLine<> line;
|
||||
line.printf("RAW: 00");
|
||||
EXPECT_FALSE(line.flush(unattached));
|
||||
EXPECT_EQ(0U, mesh::serialLogDroppedCount());
|
||||
}
|
||||
|
||||
TEST_F(SerialPacketLogTest, MarksTruncatedLines) {
|
||||
primePort();
|
||||
FakePort port(4096);
|
||||
uint8_t raw[64];
|
||||
memset(raw, 0x5A, sizeof(raw));
|
||||
|
||||
mesh::SerialLogLine<32> line;
|
||||
line.printf("RAW: ");
|
||||
line.hex(raw, sizeof(raw));
|
||||
EXPECT_FALSE(line.flush(port));
|
||||
EXPECT_LE(port.written().size(), (size_t)32);
|
||||
EXPECT_EQ(1U, mesh::serialLogDroppedCount());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
Reference in new issue
Block a user