Recheck cached immutable paths before resetting the live table after raw I/O failure. Keep accepted RAM mutations, current jobs and save deadlines when reads recover; stronger source or publication uncertainty still forces full recovery. Use the existing recovery byte and a fixed scratch buffer, with no cache allocation or eviction. Cover full-cache transient recovery, persistent I/O and checksum failures, nRF unread-scope restoration, active ESP jobs, real uncertain publication and unchanged lazy deadlines with sanitizer tests and restored-reset negative controls.
487 lines
22 KiB
Python
487 lines
22 KiB
Python
#!/usr/bin/env python3
|
|
"""Integration guards for Companion contact writes across event-only sleep."""
|
|
|
|
from pathlib import Path
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def function_body(source: str, signature: str) -> str:
|
|
start = source.index(signature)
|
|
opening_brace = source.index("{", start)
|
|
depth = 0
|
|
for position in range(opening_brace, len(source)):
|
|
if source[position] == "{":
|
|
depth += 1
|
|
elif source[position] == "}":
|
|
depth -= 1
|
|
if depth == 0:
|
|
return source[opening_brace + 1 : position]
|
|
raise AssertionError(f"unterminated function: {signature}")
|
|
|
|
|
|
class CompanionContactSleepContractTest(unittest.TestCase):
|
|
def test_recovery_resets_at_outer_boundary_and_volatile_saves_stay_truthful(self):
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
store = (ROOT / "examples/companion_radio/DataStore.cpp").read_text()
|
|
loop = function_body(mesh, "void MyMesh::loop()")
|
|
self.assertLess(loop.index("_store->recoverContacts(this)"),
|
|
loop.index("BaseChatMesh::loop()"))
|
|
self.assertIn("contactRecoveryPending() && !mesh::morseTimingActive(_radio)", loop)
|
|
self.assertIn("|| _store->contactRecoveryPending()",
|
|
function_body(mesh, "bool MyMesh::hasPendingWork() const"))
|
|
reset = function_body(mesh, "bool MyMesh::resetContactsForRecovery()")
|
|
self.assertLess(reset.index("stopContactsIterator()"), reset.index("resetContacts()"))
|
|
self.assertIn("MyMesh::onContactCacheFlushed()", reset)
|
|
clear = function_body(mesh, "void MyMesh::onContactCacheFlushed()")
|
|
self.assertIn("mesh::resetLazyPersistenceAfterSuccess(dirty_contacts_expiry, dirty_contacts_failures)", clear)
|
|
recovery = function_body(store, "void DataStore::recoverContacts(")
|
|
self.assertNotIn("format(", recovery)
|
|
self.assertNotIn("reboot(", recovery)
|
|
self.assertNotIn('"/.extrafs.mig"', recovery)
|
|
signatures = (
|
|
"void MyMesh::onContactCacheFlushed()",
|
|
"bool MyMesh::flushContactsBeforeReboot()",
|
|
"bool MyMesh::prepareForUiShutdown()",
|
|
"void MyMesh::rebootNow()",
|
|
"void MyMesh::saveContacts()",
|
|
)
|
|
methods = "\n".join(signature + " {" + function_body(mesh, signature) + "}"
|
|
for signature in signatures)
|
|
recovery_guard = "if (_store->contactRecoveryPending() && !mesh::morseTimingActive(_radio))"
|
|
methods += "\nvoid MyMesh::serviceRecovery() {" + recovery_guard + " {"
|
|
methods += function_body(loop, recovery_guard) + "}}\n"
|
|
fixture = r'''
|
|
#include <cassert>
|
|
#include <cstdint>
|
|
#include <initializer_list>
|
|
#define MESH_DEBUG_PRINTLN(...) do {} while (0)
|
|
namespace mesh {
|
|
void resetLazyPersistenceAfterSuccess(uint32_t& deadline, uint8_t& failures) {
|
|
deadline = 0; failures = 0;
|
|
}
|
|
uint32_t nonzeroLazyPersistenceDeadline(uint32_t value) { return value ? value : 1; }
|
|
bool morseTimingActive(int) { return false; }
|
|
}
|
|
constexpr unsigned CONTACT_PAGE_WRITE_GAP = 10;
|
|
constexpr unsigned LAZY_CONTACTS_WRITE_DELAY = 50;
|
|
bool save_filter(int) { return true; }
|
|
struct Board { unsigned resets = 0; void reboot() { ++resets; } } board;
|
|
struct Store {
|
|
bool vol = false, saved = true, pending = true, recovery = false;
|
|
unsigned writes = 0;
|
|
bool contactsAreVolatile() const { return vol; }
|
|
bool hasPendingContactWrites() const { return pending; }
|
|
bool contactRecoveryPending() const { return recovery; }
|
|
void recoverContacts(void*) { recovery = false; }
|
|
bool flushContactWrites(void*, bool (*)(int)) { ++writes; return saved; }
|
|
bool saveContacts(void*, bool (*)(int)) { ++writes; return saved; }
|
|
};
|
|
struct MyMesh {
|
|
Store store; Store* _store = &store;
|
|
uint32_t dirty_contacts_expiry = 1;
|
|
uint8_t dirty_contacts_failures = 1;
|
|
unsigned retries = 0;
|
|
int _radio = 0;
|
|
void updateGpsTelemetryPolicy() {}
|
|
void serviceRecovery();
|
|
uint32_t futureMillis(unsigned value) { return 100 + value; }
|
|
void scheduleContactWriteRetry() { ++retries; }
|
|
bool flushContactsBeforeReboot(); bool prepareForUiShutdown();
|
|
virtual void onContactCacheFlushed();
|
|
void rebootNow(); void saveContacts();
|
|
};
|
|
@METHODS@
|
|
int main() {
|
|
MyMesh node;
|
|
node.store.vol = true;
|
|
assert(!node.flushContactsBeforeReboot()); // tx.contact must not promise durability
|
|
assert(node.store.writes == 0 && node.retries == 0);
|
|
assert(node.prepareForUiShutdown());
|
|
node.rebootNow(); assert(board.resets == 1);
|
|
node.saveContacts();
|
|
assert(node.dirty_contacts_expiry == 0 && node.dirty_contacts_failures == 0);
|
|
assert(node.store.writes == 0 && node.retries == 0);
|
|
node.store.vol = false; node.store.saved = false;
|
|
node.dirty_contacts_expiry = 1;
|
|
assert(!node.flushContactsBeforeReboot());
|
|
assert(node.store.writes == 1 && node.retries == 1);
|
|
node.rebootNow(); assert(board.resets == 1);
|
|
node.store.saved = true; node.store.pending = false;
|
|
assert(node.flushContactsBeforeReboot());
|
|
assert(node.dirty_contacts_expiry == 0 && node.dirty_contacts_failures == 0);
|
|
node.rebootNow(); assert(board.resets == 2);
|
|
struct Derived : MyMesh {
|
|
unsigned overrides = 0;
|
|
void onContactCacheFlushed() override { ++overrides; }
|
|
} derived;
|
|
derived.store.vol = true;
|
|
derived.saveContacts();
|
|
assert(derived.overrides == 0 && derived.dirty_contacts_expiry == 0);
|
|
assert(derived.dirty_contacts_failures == 0 && derived.store.writes == 0);
|
|
// Execute the actual outer-loop recovery preamble. Fast raw-read recovery
|
|
// must not postpone even an already-overdue accepted mutation deadline.
|
|
for (uint32_t deadline : {1u, 321u}) {
|
|
node.dirty_contacts_expiry = deadline;
|
|
node.dirty_contacts_failures = 3;
|
|
node.store.pending = true; node.store.recovery = true;
|
|
node.serviceRecovery();
|
|
assert(node.dirty_contacts_expiry == deadline);
|
|
assert(node.dirty_contacts_failures == 3 && !node.store.recovery);
|
|
}
|
|
node.dirty_contacts_expiry = 0; node.store.recovery = true;
|
|
node.serviceRecovery();
|
|
assert(node.dirty_contacts_expiry == 100 + LAZY_CONTACTS_WRITE_DELAY);
|
|
}
|
|
'''.replace("@METHODS@", methods)
|
|
with tempfile.TemporaryDirectory(prefix="companion-contact-recovery-") as directory:
|
|
source, binary = Path(directory) / "recovery.cpp", Path(directory) / "recovery"
|
|
source.write_text(fixture, encoding="ascii")
|
|
subprocess.run([os.environ.get("CXX", "g++"), "-std=c++17", "-Wall", "-Wextra",
|
|
"-Werror", "-fsanitize=address,undefined", "-fno-pie", "-no-pie",
|
|
str(source), "-o", str(binary)], check=True, timeout=30)
|
|
subprocess.run([str(binary)], check=True, timeout=5)
|
|
|
|
def test_initial_write_polls_but_failed_backoff_can_sleep(self):
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
body = function_body(mesh, "bool MyMesh::hasPendingWork() const")
|
|
|
|
nrf_start = body.index("#if defined(NRF52_PLATFORM)")
|
|
other_start = body.index("#else", nrf_start)
|
|
conditional_end = body.index("#endif", other_start)
|
|
nrf = body[nrf_start:other_start]
|
|
other = body[other_start:conditional_end]
|
|
|
|
self.assertRegex(
|
|
nrf,
|
|
r"contact_write_needs_polling\s*=\s*"
|
|
r"dirty_contacts_expiry\s*!=\s*0\s*"
|
|
r"&&\s*\(dirty_contacts_failures\s*==\s*0\s*"
|
|
r"\|\|\s*isContactWriteDue\s*\(\s*\)\)",
|
|
)
|
|
self.assertRegex(
|
|
other,
|
|
r"contact_write_needs_polling\s*=\s*isContactWriteDue\s*\(\s*\)",
|
|
)
|
|
self.assertRegex(body, r"\|\|\s*contact_write_needs_polling")
|
|
|
|
def test_contact_write_is_serviced_only_after_its_deadline(self):
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
loop = function_body(mesh, "void MyMesh::loop()")
|
|
self.assertIn("servicePersistence();", loop)
|
|
self.assertLess(loop.index("checkSerialInterface();"), loop.index("servicePersistence();"))
|
|
self.assertIn("#if defined(ESP32_PLATFORM)\n servicePersistence();\n#else", loop)
|
|
self.assertIn("_store->serviceContactWrites(this, save_filter)", loop)
|
|
body = function_body(mesh, "void MyMesh::servicePersistence()")
|
|
|
|
self.assertIn("if (isContactWriteDue())", body)
|
|
self.assertIn("_store->serviceContactWrites(this, save_filter)", body)
|
|
|
|
due = function_body(mesh, "bool MyMesh::isContactWriteDue() const")
|
|
self.assertEqual(due.count("_ms->getMillis()"), 1)
|
|
self.assertIn("(int32_t)(now - dirty_contacts_expiry) >= 0", due)
|
|
|
|
def test_repeated_mutations_do_not_postpone_first_write(self):
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
|
|
for signature in (
|
|
"bool MyMesh::scheduleContactWrite(const ContactInfo& contact)",
|
|
"bool MyMesh::scheduleContactWriteAfterRelease(",
|
|
):
|
|
body = function_body(mesh, signature)
|
|
self.assertIn("mesh::scheduleLazyPersistenceMutation(", body)
|
|
self.assertIn("dirty_contacts_failures", body)
|
|
self.assertIn("futureMillis(LAZY_CONTACTS_WRITE_DELAY)", body)
|
|
self.assertNotRegex(
|
|
body,
|
|
r"dirty_contacts_expiry\s*=\s*"
|
|
r"futureMillis\s*\(\s*LAZY_CONTACTS_WRITE_DELAY\s*\)",
|
|
)
|
|
|
|
def test_every_direct_contact_rearm_preserves_zero_sentinel(self):
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
begin = function_body(mesh, "void MyMesh::begin(")
|
|
save = function_body(mesh, "void MyMesh::saveContacts()")
|
|
loop = function_body(mesh, "void MyMesh::servicePersistence()")
|
|
|
|
for body in (begin, save, loop):
|
|
self.assertIn("mesh::nonzeroLazyPersistenceDeadline(", body)
|
|
|
|
self.assertIn("futureMillis(CONTACT_PAGE_WRITE_GAP)", loop)
|
|
|
|
def test_failed_writes_back_off_until_a_success_resets_state(self):
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
header = (ROOT / "examples/companion_radio/MyMesh.h").read_text()
|
|
save = function_body(mesh, "void MyMesh::saveContacts()")
|
|
loop = function_body(mesh, "void MyMesh::servicePersistence()")
|
|
retry = function_body(mesh, "void MyMesh::scheduleContactWriteRetry()")
|
|
|
|
self.assertIn("uint8_t dirty_contacts_failures;", header)
|
|
self.assertIn("mesh::recordLazyPersistenceSaveFailure(", retry)
|
|
self.assertIn(
|
|
"mesh::LAZY_PERSISTENCE_MAX_RETRY_DELAY_MILLIS", retry
|
|
)
|
|
self.assertIn("LAZY_CONTACTS_WRITE_DELAY", retry)
|
|
self.assertIn("mesh::completeLazyPersistenceSave(", retry)
|
|
self.assertIn("retry in %lu ms", retry)
|
|
for body in (save, loop):
|
|
self.assertIn("scheduleContactWriteRetry();", body)
|
|
self.assertIn("MyMesh::onContactCacheFlushed()", body)
|
|
|
|
def test_main_loop_gates_sleep_on_pending_work(self):
|
|
main = (ROOT / "examples/companion_radio/main.cpp").read_text()
|
|
sleep_start = main.index("bool can_sleep =")
|
|
sleep_end = main.index("if (can_sleep)", sleep_start)
|
|
sleep_gate = main[sleep_start:sleep_end]
|
|
|
|
self.assertIn("!the_mesh.hasPendingWork()", sleep_gate)
|
|
|
|
nrf52 = (ROOT / "src/helpers/NRF52Board.cpp").read_text()
|
|
body = function_body(nrf52, "void NRF52Board::sleep(uint32_t secs)")
|
|
self.assertIn("event-driven sleep instead of timed sleep", body)
|
|
self.assertIn("sd_app_evt_wait();", body)
|
|
|
|
def test_polled_rak_ethernet_holds_event_sleep_through_pending_off(self):
|
|
main = (ROOT / "examples/companion_radio/main.cpp").read_text()
|
|
start = main.index("bool can_sleep =")
|
|
gate = main[start:main.index("if (can_sleep)", start)]
|
|
fixture = r'''
|
|
#include <cassert>
|
|
struct Prefs { bool powersaving_enabled; };
|
|
struct Mesh {
|
|
Prefs prefs; bool pending;
|
|
Prefs* getNodePrefs() { return &prefs; }
|
|
bool hasPendingWork() const { return pending; }
|
|
} the_mesh;
|
|
struct Board { bool usb; bool isUsbHostConnected() const { return usb; } } board;
|
|
struct Ethernet { bool active; bool hardwareActive() const { return active; } } ethernet_interface;
|
|
namespace mesh {
|
|
bool watchdog;
|
|
bool isUsbLoggingWatchdogArmed() { return watchdog; }
|
|
namespace wireless {
|
|
struct Control { bool work; bool pending() const { return work; } } instance;
|
|
Control& control() { return instance; }
|
|
} }
|
|
int main() {
|
|
for (unsigned flags = 0; flags < 128; ++flags) {
|
|
the_mesh.prefs.powersaving_enabled = !(flags & 1);
|
|
the_mesh.pending = flags & 2;
|
|
bool morse_timing = flags & 4;
|
|
mesh::watchdog = flags & 8;
|
|
mesh::wireless::instance.work = flags & 16;
|
|
board.usb = flags & 32;
|
|
ethernet_interface.active = flags & 64; // includes OFF accepted but unreleased
|
|
@GATE@
|
|
#if defined(ETHERNET_USE_RAK13800)
|
|
assert(can_sleep == (flags == 0));
|
|
#else
|
|
assert(can_sleep == ((flags & 63) == 0));
|
|
#endif
|
|
}
|
|
}
|
|
'''.replace('@GATE@', gate)
|
|
with tempfile.TemporaryDirectory(prefix='companion-ethernet-sleep-') as directory:
|
|
source, binary = Path(directory) / 'sleep.cpp', Path(directory) / 'sleep'
|
|
source.write_text(fixture, encoding='ascii')
|
|
for ethernet in (False, True):
|
|
with self.subTest(ethernet=ethernet):
|
|
subprocess.run([os.environ.get('CXX', 'g++'), '-std=c++17',
|
|
'-Wall', '-Wextra', '-Werror', '-DNRF52_PLATFORM=1',
|
|
*(['-DETHERNET_USE_RAK13800=1'] if ethernet else []),
|
|
str(source), '-o', str(binary)], check=True, timeout=30)
|
|
subprocess.run([str(binary)], check=True, timeout=5)
|
|
|
|
def test_all_runtime_reboots_flush_contacts_first(self):
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
header = (ROOT / "examples/companion_radio/MyMesh.h").read_text()
|
|
self.assertIn("bool flushContactsBeforeReboot();", header)
|
|
|
|
flush = function_body(mesh, "bool MyMesh::flushContactsBeforeReboot()")
|
|
self.assertIn("_store->flushContactWrites(this, save_filter)", flush)
|
|
self.assertIn("scheduleContactWriteRetry();", flush)
|
|
self.assertIn("MyMesh::onContactCacheFlushed()", flush)
|
|
|
|
framed = function_body(mesh, "void MyMesh::handleCmdFrame(")
|
|
reboot_at = framed.index("cmd_frame[0] == CMD_REBOOT")
|
|
framed_reboot = framed[reboot_at : framed.index(
|
|
"cmd_frame[0] == CMD_GET_BATT_AND_STORAGE", reboot_at
|
|
)]
|
|
self.assertIn("MyMesh::prepareForUiShutdown()", framed_reboot)
|
|
|
|
rescue = function_body(mesh, "void MyMesh::checkCLIRescueCmd()")
|
|
rescue_reboot = rescue[rescue.index('strcmp(cli_command, "reboot")') :]
|
|
self.assertIn("MyMesh::prepareForUiShutdown()", rescue_reboot)
|
|
|
|
callback = function_body(mesh, "void MyMesh::rebootNow()")
|
|
self.assertIn("MyMesh::prepareForUiShutdown()", callback)
|
|
|
|
loop = function_body(mesh, "void MyMesh::loop()")
|
|
scheduled = loop[: loop.index("#if COMPANION_FEATURE_TEMP_RADIO")]
|
|
self.assertIn("MyMesh::prepareForUiShutdown()", scheduled)
|
|
shutdown = function_body(mesh, "bool MyMesh::prepareForUiShutdown()")
|
|
self.assertIn("_store->contactsAreVolatile() || flushContactsBeforeReboot()", shutdown)
|
|
|
|
pending = function_body(mesh, "bool MyMesh::hasPendingWork() const")
|
|
self.assertIn("|| _scheduled_reboot_at != 0", pending)
|
|
|
|
def test_ota_apply_reboot_uses_companion_persistence_hook(self):
|
|
mesh_base_header = (ROOT / "src/Mesh.h").read_text()
|
|
mesh_base = (ROOT / "src/Mesh.cpp").read_text()
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
header = (ROOT / "examples/companion_radio/MyMesh.h").read_text()
|
|
|
|
self.assertIn(
|
|
"virtual bool prepareForOtaReboot() { return true; }",
|
|
mesh_base_header,
|
|
)
|
|
maintenance = function_body(
|
|
mesh_base, "void __attribute__((noinline)) Mesh::serviceLoopMaintenance()"
|
|
)
|
|
guard_at = maintenance.index("prepareForOtaReboot()")
|
|
apply_at = maintenance.index("ota::ota_reboot_to_apply()")
|
|
self.assertLess(guard_at, apply_at)
|
|
self.assertIn("oc.apply_at = ota::armedDeadline(_ms->getMillis(), 1000)", maintenance)
|
|
|
|
self.assertIn("bool prepareForOtaReboot() override;", header)
|
|
guard = function_body(mesh, "bool MyMesh::prepareForOtaReboot()")
|
|
self.assertIn("dirty_contacts_failures != 0", guard)
|
|
self.assertIn("!isContactWriteDue()", guard)
|
|
self.assertIn("flushContactsBeforeReboot()", guard)
|
|
|
|
def test_deferred_ota_apply_prevents_event_only_sleep(self):
|
|
mesh_base_header = (ROOT / "src/Mesh.h").read_text()
|
|
mesh_base = (ROOT / "src/Mesh.cpp").read_text()
|
|
self.assertIn("bool hasPendingOtaApply() const;", mesh_base_header)
|
|
|
|
pending = function_body(mesh_base, "bool Mesh::hasPendingOtaApply() const")
|
|
source = r'''
|
|
#include <cassert>
|
|
#if defined(ENABLE_OTA) && !defined(OTA_SEEDER_ONLY)
|
|
namespace ota {
|
|
struct OtaContext { bool apply_pending = false; };
|
|
static OtaContext dormant;
|
|
static OtaContext* active = nullptr;
|
|
const OtaContext* ota_context_if_active() { return active; }
|
|
// Catch an idle-work query accidentally acquiring the released OTA context.
|
|
OtaContext& ota_ctx() {
|
|
if (!active) active = &dormant;
|
|
return *active;
|
|
}
|
|
}
|
|
#endif
|
|
struct Mesh {
|
|
bool hasPendingOtaApply() const { @PENDING@ }
|
|
};
|
|
int main() {
|
|
const Mesh mesh;
|
|
assert(!mesh.hasPendingOtaApply());
|
|
#if defined(ENABLE_OTA) && !defined(OTA_SEEDER_ONLY)
|
|
assert(ota::active == nullptr);
|
|
ota::OtaContext context;
|
|
ota::active = &context;
|
|
assert(!mesh.hasPendingOtaApply());
|
|
context.apply_pending = true;
|
|
assert(mesh.hasPendingOtaApply());
|
|
context.apply_pending = false;
|
|
assert(!mesh.hasPendingOtaApply());
|
|
ota::active = nullptr;
|
|
assert(!mesh.hasPendingOtaApply());
|
|
assert(ota::active == nullptr);
|
|
#endif
|
|
}
|
|
'''
|
|
with tempfile.TemporaryDirectory(prefix="meshcore-ota-sleep-") as tmp:
|
|
cpp = Path(tmp) / "test.cpp"
|
|
cpp.write_text(source.replace("@PENDING@", pending))
|
|
for index, defines in enumerate(([], ["ENABLE_OTA"],
|
|
["ENABLE_OTA", "OTA_SEEDER_ONLY"])):
|
|
with self.subTest(defines=defines):
|
|
binary = Path(tmp) / f"test-{index}"
|
|
built = subprocess.run(
|
|
[os.environ.get("CXX", "c++"), "-std=c++17", "-Wall", "-Wextra",
|
|
*(f"-D{define}" for define in defines), str(cpp), "-o", str(binary)],
|
|
capture_output=True, text=True,
|
|
)
|
|
self.assertEqual(built.returncode, 0, built.stderr)
|
|
ran = subprocess.run([str(binary)], capture_output=True, text=True)
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
|
|
role_sources = (
|
|
ROOT / "examples/companion_radio/MyMesh.cpp",
|
|
ROOT / "examples/simple_sensor/SensorMesh.cpp",
|
|
ROOT / "examples/simple_room_server/MyMesh.cpp",
|
|
ROOT / "examples/simple_repeater/MyMesh.cpp",
|
|
)
|
|
for role_source in role_sources:
|
|
role = role_source.read_text()
|
|
signature = (
|
|
"bool SensorMesh::hasPendingWork() const"
|
|
if role_source.name == "SensorMesh.cpp"
|
|
else "bool MyMesh::hasPendingWork() const"
|
|
)
|
|
has_pending_work = function_body(role, signature)
|
|
self.assertIn("hasPendingOtaApply()", has_pending_work, role_source)
|
|
|
|
def test_every_companion_ui_shutdown_uses_persistence_guard(self):
|
|
abstract = (
|
|
ROOT / "examples/companion_radio/AbstractUITask.h"
|
|
).read_text()
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
header = (ROOT / "examples/companion_radio/MyMesh.h").read_text()
|
|
self.assertIn("public UIShutdownGuard", header)
|
|
self.assertIn("virtual bool prepareForUiShutdown() = 0;", abstract)
|
|
self.assertIn("_ui->setShutdownGuard(this)", mesh)
|
|
callback = function_body(mesh, "bool MyMesh::prepareForUiShutdown()")
|
|
self.assertIn("flushContactsBeforeReboot()", callback)
|
|
|
|
for ui_name in ("ui-orig", "ui-new", "ui-tiny"):
|
|
ui = (
|
|
ROOT / "examples/companion_radio" / ui_name / "UITask.cpp"
|
|
).read_text()
|
|
shutdown = function_body(ui, "void UITask::shutdown(bool restart)")
|
|
guard_at = shutdown.index("if (!prepareForShutdown()) return;")
|
|
reboot_at = shutdown.index("_board->reboot()")
|
|
poweroff_at = shutdown.index("_board->powerOff()")
|
|
self.assertLess(guard_at, reboot_at, ui_name)
|
|
self.assertLess(guard_at, poweroff_at, ui_name)
|
|
|
|
def test_identity_import_rearms_page_repairs(self):
|
|
mesh = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
|
framed = function_body(mesh, "void MyMesh::handleCmdFrame(")
|
|
import_at = framed.index("cmd_frame[0] == CMD_IMPORT_PRIVATE_KEY")
|
|
import_end = framed.index("cmd_frame[0] == CMD_SEND_RAW_DATA", import_at)
|
|
identity_import = framed[import_at:import_end]
|
|
flush_at = identity_import.index("flushContactsBeforeReboot()")
|
|
save_identity_at = identity_import.index("_store->saveMainIdentity(")
|
|
load_at = identity_import.index("_store->loadContacts(this)")
|
|
reset_at = identity_import.index(
|
|
"MyMesh::onContactCacheFlushed()", save_identity_at
|
|
)
|
|
rearm_at = identity_import.index(
|
|
"mesh::scheduleLazyPersistenceMutation(", load_at
|
|
)
|
|
self.assertLess(flush_at, save_identity_at)
|
|
self.assertLess(reset_at, load_at)
|
|
self.assertLess(load_at, rearm_at)
|
|
self.assertIn("_store->hasPendingContactWrites()", identity_import)
|
|
|
|
def test_webconfig_reboot_request_is_one_shot_if_flush_fails(self):
|
|
webconfig = (
|
|
ROOT / "src/helpers/esp32/WebConfigServer.cpp"
|
|
).read_text()
|
|
tick = function_body(webconfig, "void WebConfigServer::tick(")
|
|
due_at = tick.index("WebConfigBatch::rebootDue(")
|
|
callback_at = tick.index("_cb->rebootNow()", due_at)
|
|
clear_at = tick.index("_reboot_at = 0", due_at)
|
|
self.assertLess(clear_at, callback_at)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|