Add programmable Companion alerts and trusted DM and room notifications
This commit is contained in:
1 parent
bc8fe0c66c
commit
4bc391ef36
33 files changed
+1846
-24
No files matched your search
@@ -0,0 +1,178 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <helpers/CompanionNotificationPolicy.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
using namespace mesh::notify;
|
||||
struct OutputSink : Sink {
|
||||
bool vibration=false,led=false,gpio=false;
|
||||
int8_t screen_state=-1;
|
||||
std::string tune;
|
||||
uint8_t supported=31;
|
||||
uint8_t capabilities() const override { return supported; }
|
||||
bool gpioAvailable(uint8_t pin) const override { return pin==22; }
|
||||
void pulse(Output o,bool on,int8_t) override {
|
||||
if(o==Vibration)vibration=on;else if(o==Led)led=on;else if(o==Gpio)gpio=on;
|
||||
}
|
||||
void melody(const char* text) override { tune=text?text:""; }
|
||||
void screen(int8_t mode) override { screen_state=mode; }
|
||||
};
|
||||
struct MemoryStore : Store {
|
||||
Settings saved;bool succeeds=true;unsigned writes=0;
|
||||
bool save(const Settings& s) override { ++writes;if(!succeeds)return false;saved=s;return true; }
|
||||
};
|
||||
class Notifications : public ::testing::Test {
|
||||
protected:
|
||||
OutputSink sink;MemoryStore store;Controller c{sink,store};char reply[160]={};
|
||||
std::string cmd(const char* command,uint32_t now=0,bool connected=false) {
|
||||
EXPECT_TRUE(c.handle(command,reply,sizeof(reply),now,connected));return reply;
|
||||
}
|
||||
};
|
||||
|
||||
TEST(NotificationParsing, MillisecondPulseSequenceAndStrictBounds) {
|
||||
Pulse p;ASSERT_TRUE(parsePulse("50,300,40,20,500",p));EXPECT_EQ(910U,p.duration());
|
||||
EXPECT_TRUE(p.level(0));EXPECT_TRUE(p.level(49));EXPECT_FALSE(p.level(50));
|
||||
EXPECT_FALSE(p.level(349));EXPECT_TRUE(p.level(350));EXPECT_FALSE(p.level(390));
|
||||
EXPECT_TRUE(p.level(410));EXPECT_FALSE(p.level(910));
|
||||
for(auto text:{"0","-1","50,","50,,20","60001","42949672950","50 20","1,1,1,1,1,1,1,1,1,1,1,1,1"})EXPECT_FALSE(parsePulse(text,p));
|
||||
ASSERT_TRUE(parsePulse("off",p));EXPECT_EQ(0,p.count);
|
||||
}
|
||||
TEST(NotificationParsing, ValidatesTheActualBuzzerTableAndRtttlSyntax) {
|
||||
uint32_t ms;
|
||||
ASSERT_TRUE(soundDuration("vip:d=8,o=5,b=120:c,c#,16p,4g.6",ms));EXPECT_GT(ms,0U);
|
||||
for(auto text:{"abc","x:d=8,o=3,b=120:c","x:d=8,o=5,b=0:c","x:d=8,o=8,b=120:c",
|
||||
"x:d=3,o=5,b=120:c","x:d=8,o=5,b=120:b#7","x:d=8,o=5,b=120:c,",
|
||||
"x:d=8,o=5,b=120:c..","x:d=8,o=5,b=120:c8","x:d=8,o=5,b=120:p#",
|
||||
"x:d=8,o=5,b=120:c+","x:d=8,o=5,b=120:c, d"})EXPECT_FALSE(soundDuration(text,ms))<<text;
|
||||
}
|
||||
TEST_F(Notifications, ExecutesExactBoundaryPulsesAndReturnsOutputsOff) {
|
||||
EXPECT_EQ("OK",cmd("set notify.led all 50,300,40,20,500"));
|
||||
c.loop(0,false);ASSERT_TRUE(c.message(nullptr,nullptr,false,0));EXPECT_TRUE(sink.led);
|
||||
c.loop(50,false);EXPECT_FALSE(sink.led);c.loop(350,false);EXPECT_TRUE(sink.led);
|
||||
c.loop(390,false);EXPECT_FALSE(sink.led);c.loop(410,false);EXPECT_TRUE(sink.led);
|
||||
c.loop(910,false);EXPECT_FALSE(c.active());EXPECT_FALSE(sink.led);
|
||||
}
|
||||
TEST_F(Notifications, ContactAndChannelOverrideEachOutputAndConditionIndependently) {
|
||||
EXPECT_EQ("OK",cmd("set notify.led all 100"));
|
||||
EXPECT_EQ("OK",cmd("set notify.sound all@connected ping:d=8,o=5,b=120:c"));
|
||||
const char* key="contact:0101010101010101010101010101010101010101010101010101010101010101";
|
||||
std::string command=std::string("set notify.led ")+key+"@connected off";
|
||||
EXPECT_EQ("OK",cmd(command.c_str()));
|
||||
uint8_t contact[32];memset(contact,1,sizeof(contact));
|
||||
c.message(contact,nullptr,true,0);EXPECT_FALSE(sink.led);EXPECT_FALSE(sink.tune.empty());
|
||||
c.message(contact,nullptr,false,0);EXPECT_TRUE(sink.led);EXPECT_TRUE(sink.tune.empty());
|
||||
cmd("set notify.vibration channel:02020202020202020202020202020202 50,20,50");
|
||||
uint8_t channel[16];memset(channel,2,sizeof(channel));
|
||||
c.message(nullptr,channel,false,0);EXPECT_TRUE(sink.led);EXPECT_TRUE(sink.vibration);
|
||||
}
|
||||
TEST_F(Notifications, ButtonConnectedAndNeverStopPolicies) {
|
||||
cmd("set notify.led all 50");cmd("set notify.repeat all forever");
|
||||
c.loop(0,false);c.message(nullptr,nullptr,false,0);EXPECT_TRUE(c.button());EXPECT_FALSE(c.active());
|
||||
cmd("set notify.stop all connected");c.message(nullptr,nullptr,false,0);
|
||||
EXPECT_FALSE(c.button());c.loop(10,true);EXPECT_FALSE(c.active());
|
||||
cmd("set notify.stop all never");c.message(nullptr,nullptr,true,20);
|
||||
c.loop(30,false);c.loop(40,true);EXPECT_TRUE(c.active());EXPECT_FALSE(c.button());
|
||||
EXPECT_EQ("OK - alerts stopped",cmd("notify.stop"));EXPECT_FALSE(c.active());
|
||||
}
|
||||
TEST_F(Notifications, ForeverPulsesAcrossMillisRolloverAndSkipsMissedWindows) {
|
||||
cmd("set notify.led all 50,300,40,20,500");cmd("set notify.repeat all forever");
|
||||
uint32_t start=UINT32_MAX-20;c.message(nullptr,nullptr,false,start);
|
||||
c.loop(start+50,false);EXPECT_FALSE(sink.led);
|
||||
c.loop(start+350,false);EXPECT_TRUE(sink.led);
|
||||
c.loop(start+1410+60,false);EXPECT_FALSE(sink.led);EXPECT_TRUE(c.active());
|
||||
}
|
||||
TEST_F(Notifications, GpioUsesTheRepeaterBoardApprovalAndUnsupportedOutputsFail) {
|
||||
EXPECT_EQ("Error: GPIO reserved or unavailable; use get notify.gpio.pins",cmd("set notify.gpio all 4:50"));
|
||||
EXPECT_EQ("OK",cmd("set notify.gpio all 22:50,300,50"));
|
||||
c.message(nullptr,nullptr,false,0);EXPECT_TRUE(sink.gpio);c.loop(50,false);EXPECT_FALSE(sink.gpio);
|
||||
sink.supported=Led;EXPECT_EQ("Error: output unsupported on this build",cmd("set notify.vibration all 50"));
|
||||
EXPECT_EQ("Error: output unsupported on this build",cmd("set notify.sound on"));
|
||||
EXPECT_EQ("> GPIOs: 22",cmd("get notify.gpio.pins"));
|
||||
}
|
||||
TEST_F(Notifications, FailedSaveRollsBackRuleMasterAndEnableState) {
|
||||
store.succeeds=false;
|
||||
EXPECT_EQ("Error: save failed",cmd("set notify.led all 50"));EXPECT_FALSE(c.settings().enabled);
|
||||
EXPECT_FALSE(c.settings().rules[0].used);
|
||||
EXPECT_EQ("Error: save failed",cmd("set notify.sound off"));EXPECT_EQ(31,c.settings().outputs);
|
||||
}
|
||||
TEST_F(Notifications, PatternRestoresNormalDisplayAndDoesNotMutateDisplayPrefs) {
|
||||
cmd("set notify.screen all on");c.message(nullptr,nullptr,false,0);EXPECT_EQ(1,sink.screen_state);
|
||||
c.loop(1000,false);EXPECT_EQ(-1,sink.screen_state);
|
||||
cmd("set notify.screen all off");c.message(nullptr,nullptr,false,0);EXPECT_EQ(0,sink.screen_state);
|
||||
c.stop();EXPECT_EQ(-1,sink.screen_state);
|
||||
}
|
||||
TEST_F(Notifications, DeleteGetInheritanceAndExplicitTest) {
|
||||
cmd("set notify.led all@disconnected 50,300,50");
|
||||
EXPECT_EQ("50,300,50",cmd("get notify.led all@disconnected"));
|
||||
EXPECT_EQ("OK - alert test started",cmd("notify.test all@disconnected",0,true));EXPECT_TRUE(sink.led);
|
||||
EXPECT_EQ("OK",cmd("notify.delete all@disconnected"));EXPECT_FALSE(c.active());
|
||||
EXPECT_EQ("inherit",cmd("get notify.led all@disconnected"));
|
||||
}
|
||||
TEST_F(Notifications, SettingsValidationRejectsCorruptionAndChangedPinOwnership) {
|
||||
cmd("set notify.gpio all 22:50");ASSERT_TRUE(c.validSettings(store.saved));
|
||||
store.saved.rules[0].pin=4;EXPECT_FALSE(c.validSettings(store.saved));
|
||||
store.saved.rules[0].pin=22;store.saved.rules[0].gpio.count=255;EXPECT_FALSE(c.validSettings(store.saved));
|
||||
}
|
||||
TEST_F(Notifications, FiniteRepeatEndsWithoutPlayingAnExtraCycle) {
|
||||
cmd("set notify.led all 50");cmd("set notify.repeat all 2");cmd("set notify.gap all 100");
|
||||
c.message(nullptr,nullptr,false,0);c.loop(50,false);EXPECT_FALSE(sink.led);EXPECT_TRUE(c.active());
|
||||
c.loop(150,false);EXPECT_TRUE(sink.led);c.loop(200,false);EXPECT_FALSE(c.active());EXPECT_FALSE(sink.led);
|
||||
}
|
||||
|
||||
TEST_F(Notifications, DmRequiresAnExplicitFullContactPermissionAndNeverWritesSettings) {
|
||||
uint8_t contact[32]={};memset(contact,1,sizeof(contact));
|
||||
const char* dm="!notify led=50,300,40,20,500 sound=vip:d=8,o=5,b=180:c,e,g screen=on";
|
||||
EXPECT_FALSE(c.remoteMessage(contact,dm,0));
|
||||
EXPECT_EQ("OK",cmd("set notify.remote contact:0101010101010101010101010101010101010101010101010101010101010101 on"));
|
||||
unsigned writes=store.writes;
|
||||
ASSERT_TRUE(c.remoteMessage(contact,dm,0));EXPECT_TRUE(sink.led);EXPECT_EQ(1,sink.screen_state);
|
||||
EXPECT_EQ(writes,store.writes);
|
||||
uint8_t other[32]={};EXPECT_FALSE(c.remoteMessage(other,dm,0));
|
||||
c.stop();EXPECT_FALSE(c.message(contact,nullptr,false,0)); // permission alone does not replace normal alerts
|
||||
EXPECT_EQ("OK",cmd("set notify.remote contact:0101010101010101010101010101010101010101010101010101010101010101 off"));
|
||||
EXPECT_FALSE(c.remoteMessage(contact,dm,0));
|
||||
}
|
||||
TEST_F(Notifications, DmRejectsGpioStopPermissionAndMalformedMessagesAtomically) {
|
||||
uint8_t contact[32]={};memset(contact,1,sizeof(contact));
|
||||
cmd("set notify.remote contact:0101010101010101010101010101010101010101010101010101010101010101 on");
|
||||
for(auto dm:{"!notify led=50 gpio=22:50","!notify led=50 stop=never","!notify remote=on",
|
||||
"!notify led=50 led=100","!notify led=50 unknown=foo","!notify sound=unsafe",
|
||||
"!notify led=inherit","!notify led=50 ","!notify repeat=forever"}) {
|
||||
EXPECT_FALSE(c.remoteMessage(contact,dm,0))<<dm;EXPECT_FALSE(c.active());EXPECT_FALSE(sink.gpio);
|
||||
}
|
||||
EXPECT_EQ("Error: invalid notification value",cmd("set notify.remote all on"));
|
||||
EXPECT_EQ("Error: invalid notification value",cmd("set notify.remote contact:0101010101010101010101010101010101010101010101010101010101010101@connected on"));
|
||||
}
|
||||
TEST_F(Notifications, RemoteRepeatingAndLongPatternsHaveAHard15SecondLimitIncludingRollover) {
|
||||
uint8_t contact[32]={};memset(contact,1,sizeof(contact));
|
||||
cmd("set notify.remote contact:0101010101010101010101010101010101010101010101010101010101010101 on");
|
||||
uint32_t started=UINT32_MAX-100;
|
||||
ASSERT_TRUE(c.remoteMessage(contact,"!notify led=60000 repeat=forever screen=on",started));
|
||||
c.loop(started+14999,false);EXPECT_TRUE(c.active());EXPECT_TRUE(sink.led);
|
||||
c.loop(started+15000,false);EXPECT_FALSE(c.active());EXPECT_FALSE(sink.led);EXPECT_EQ(-1,sink.screen_state);
|
||||
}
|
||||
TEST_F(Notifications, RoomPermissionUsesTheFullRoomIdentityAndRetryDoesNotExtendTheDeadline) {
|
||||
uint8_t room[32];memset(room,2,sizeof(room));
|
||||
cmd("set notify.remote room:0202020202020202020202020202020202020202020202020202020202020202 on");
|
||||
const char* post="!notify led=60000 repeat=forever";
|
||||
ASSERT_TRUE(c.remoteMessage(room,post,0,100));
|
||||
ASSERT_TRUE(c.remoteMessage(room,post,14000,100));
|
||||
c.loop(15000,false);EXPECT_FALSE(c.active());EXPECT_FALSE(sink.led);
|
||||
ASSERT_TRUE(c.remoteMessage(room,post,16000,100));EXPECT_FALSE(c.active());
|
||||
uint8_t author[32];memset(author,3,sizeof(author));
|
||||
EXPECT_FALSE(c.remoteMessage(author,post,16000,100));
|
||||
ASSERT_TRUE(c.remoteMessage(room,post,16000,101));EXPECT_TRUE(c.active());
|
||||
}
|
||||
|
||||
TEST_F(Notifications, IncomingRoomNotificationHonorsRecipientMastersAndButtonDismissal) {
|
||||
uint8_t room[32];memset(room,2,sizeof(room));
|
||||
cmd("set notify.remote room:0202020202020202020202020202020202020202020202020202020202020202 on");
|
||||
cmd("set notify.led off");cmd("set notify.vibration off");cmd("set notify.sound off");
|
||||
ASSERT_TRUE(c.remoteMessage(room,"!notify led=1000 vibration=1000 sound=vip:d=8,o=5,b=120:c repeat=forever",0,101));
|
||||
EXPECT_FALSE(sink.led);EXPECT_FALSE(sink.vibration);EXPECT_TRUE(sink.tune.empty());
|
||||
EXPECT_TRUE(c.button());EXPECT_FALSE(c.active());
|
||||
cmd("set notify.enabled off");
|
||||
EXPECT_FALSE(c.remoteMessage(room,"!notify led=1000",10,102));
|
||||
}
|
||||
|
||||
int main(int argc,char** argv) { ::testing::InitGoogleTest(&argc,argv);return RUN_ALL_TESTS(); }
|
||||
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
const assert = require("node:assert/strict");
|
||||
const builder = require("../docs/_javascript/notification_builder.js");
|
||||
|
||||
assert.deepEqual(builder.pulse("50,300,40,20,500"), [50,300,40,20,500]);
|
||||
for (const [time, on] of [[0,true],[49,true],[50,false],[349,false],[350,true],[390,false],[410,true],[910,false]])
|
||||
assert.equal(builder.level(builder.pulse("50,300,40,20,500"), time), on);
|
||||
for (const bad of ["0", "50,", "50,,20", "60001", "-5", "50 20", "1,1,1,1,1,1,1,1,1,1,1,1,1"])
|
||||
assert.throws(() => builder.pulse(bad));
|
||||
assert.equal(builder.melody("vip:d=8,o=5,b=120:c,c#,16p,4g.6").length, 4);
|
||||
for (const bad of ["abc", "x:d=8,o=3,b=120:c", "x:d=8,o=5,b=0:c", "x:d=3,o=5,b=120:c",
|
||||
"x:d=8,o=5,b=120:b#7", "x:d=8,o=5,b=120:c,", "x:d=8,o=5,b=120:c..", "x:d=8,o=5,b=120:p#"])
|
||||
assert.throws(() => builder.melody(bad));
|
||||
for (const config of Object.values(builder.EXAMPLES)) {
|
||||
const complete = {...config, id: config.kind === "contact" ? "01".repeat(32) : config.id};
|
||||
const commands = builder.commands(complete);
|
||||
assert.ok(commands.every(cmd => cmd.length + 4 <= 175));
|
||||
const dm = builder.notificationText(complete);
|
||||
assert.ok(dm.startsWith("!notify "));assert.ok(!dm.includes("gpio="));assert.ok(dm.length <= 159);
|
||||
}
|
||||
const vip = {...builder.EXAMPLES.vip, id: "01".repeat(32), remote: "on"};
|
||||
assert.ok(builder.commands(vip).includes("set notify.remote contact:" + vip.id + " on"));
|
||||
const room = {...vip, kind: "room"};
|
||||
assert.ok(builder.commands(room).includes("set notify.remote room:" + room.id + " on"));
|
||||
assert.throws(() => builder.commands({...builder.EXAMPLES.food, remote: "on"}));
|
||||
assert.throws(() => builder.commands({...vip, id: "1234"}));
|
||||
const encoded = builder.encodeCommand("notify.stop", "A7");
|
||||
assert.equal(encoded[0], 60);assert.equal(encoded[3], 0x42);
|
||||
assert.equal(new TextDecoder().decode(encoded.slice(4)), "A7|notify.stop");
|
||||
const decoder = new builder.FrameDecoder();
|
||||
const payload = Buffer.from("A7|OK - alerts stopped");
|
||||
const framed = Uint8Array.from([62,payload.length+1,0,0x1d,...payload]);
|
||||
assert.deepEqual(decoder.push(framed.slice(0, 2)), []);
|
||||
assert.deepEqual(decoder.push(framed.slice(2, 8)), []);
|
||||
const result = decoder.push(framed.slice(8));assert.equal(result.length, 1);
|
||||
assert.equal(new TextDecoder().decode(result[0].slice(1)), "A7|OK - alerts stopped");
|
||||
assert.deepEqual(new builder.FrameDecoder().push(Uint8Array.from([62,255,255,...framed])), [result[0]]);
|
||||
assert.throws(() => builder.encodeCommand("x".repeat(173), "00"));
|
||||
console.log("Notification builder: pulse, melody, examples, permissions, and fragmented USB frame tests passed");
|
||||
|
||||
async function transportTests() {
|
||||
let incoming, requestedSignals, opened;
|
||||
const seen = [];
|
||||
const port = {
|
||||
readable: new ReadableStream({start(controller) { incoming = controller; }}),
|
||||
writable: new WritableStream({write(bytes) {
|
||||
const text = new TextDecoder().decode(bytes.slice(4));
|
||||
const tag = text.slice(0, 2), command = text.slice(3);
|
||||
seen.push(command);
|
||||
const frame = value => {
|
||||
const body = new TextEncoder().encode(value);
|
||||
return Uint8Array.from([62, body.length + 1, 0, 0x1d, ...body]);
|
||||
};
|
||||
incoming.enqueue(frame("zz|ignored unrelated reply"));
|
||||
const reply = frame(tag + "|OK");
|
||||
incoming.enqueue(reply.slice(0, 2));incoming.enqueue(reply.slice(2, 7));incoming.enqueue(reply.slice(7));
|
||||
}}),
|
||||
async open(options) { opened = options; },
|
||||
async setSignals(signals) { requestedSignals = signals; },
|
||||
async close() {}
|
||||
};
|
||||
const client = new builder.SerialClient(port);
|
||||
await client.open();assert.equal(opened.baudRate, 115200);assert.equal(requestedSignals.dataTerminalReady, true);
|
||||
const first = client.command("notify.test room:" + "02".repeat(32));
|
||||
await assert.rejects(client.command("notify.stop"), /Wait for the current command/);
|
||||
assert.equal(await first, "OK");
|
||||
assert.equal(await client.command("notify.stop"), "OK");
|
||||
assert.equal(seen.length, 2);await client.close();
|
||||
// A failed write must reject promptly and clear the pending request.
|
||||
const failed = new builder.SerialClient({
|
||||
...port, readable: new ReadableStream(),
|
||||
writable: new WritableStream({write() { throw new Error("Cable removed"); }})
|
||||
});
|
||||
await failed.open();await assert.rejects(failed.command("get notify"), /Cable removed/);
|
||||
assert.equal(failed.pending, null);await failed.close();
|
||||
}
|
||||
transportTests().then(() => console.log("USB transport: tagged round trips, busy rejection, disconnect failure and clean close passed"), error => { console.error(error);process.exitCode = 1; });
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Run the production notification file format against a fault-injected filesystem."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STUB = r'''#pragma once
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
struct FakeFS;
|
||||
struct File {
|
||||
FakeFS* fs = nullptr;
|
||||
std::string name;
|
||||
size_t cursor = 0;
|
||||
File() = default;
|
||||
explicit File(FakeFS& storage):fs(&storage) {}
|
||||
File(FakeFS* storage,const char* path):fs(storage),name(path) {}
|
||||
explicit operator bool() const { return fs != nullptr; }
|
||||
bool open(const char*,int);
|
||||
size_t size() const;
|
||||
size_t read(uint8_t*,size_t);
|
||||
size_t write(const uint8_t*,size_t);
|
||||
void close() {}
|
||||
};
|
||||
struct FakeFS {
|
||||
std::map<std::string,std::vector<uint8_t>> files;
|
||||
bool fail_write=false,fail_publish=false;
|
||||
bool exists(const char* path) { return files.count(path); }
|
||||
bool remove(const char* path) { files.erase(path);return true; }
|
||||
bool rename(const char* from,const char* to) {
|
||||
if(fail_publish && std::string(from)=="/notify_prefs.tmp")return false;
|
||||
if(!exists(from)||exists(to))return false;
|
||||
files[to]=files[from];files.erase(from);return true;
|
||||
}
|
||||
File open(const char* path,const char* mode,bool=false) {
|
||||
if(*mode=='w')files[path].clear();
|
||||
return exists(path)?File(this,path):File();
|
||||
}
|
||||
};
|
||||
inline bool File::open(const char* path,int mode) {
|
||||
if(mode==2)fs->files[path].clear();
|
||||
if(!fs->exists(path))return false;
|
||||
name=path;cursor=0;return true;
|
||||
}
|
||||
inline size_t File::size() const { return fs->files.at(name).size(); }
|
||||
inline size_t File::read(uint8_t* out,size_t n) {
|
||||
auto& bytes=fs->files[name];n=std::min(n,bytes.size()-cursor);
|
||||
memcpy(out,bytes.data()+cursor,n);cursor+=n;return n;
|
||||
}
|
||||
inline size_t File::write(const uint8_t* in,size_t n) {
|
||||
if(fs->fail_write)return 0;
|
||||
auto& bytes=fs->files[name];bytes.resize(cursor+n);
|
||||
memcpy(bytes.data()+cursor,in,n);cursor+=n;return n;
|
||||
}
|
||||
#define FILESYSTEM FakeFS
|
||||
#define FILE_O_READ 1
|
||||
#define FILE_O_WRITE 2
|
||||
'''
|
||||
PROGRAM = r'''
|
||||
#include <cassert>
|
||||
#include "NotificationSettingsFile.h"
|
||||
using namespace mesh::notify;
|
||||
int main() {
|
||||
FakeFS fs;Settings prefs,loaded;
|
||||
assert(!readSettings(nullptr,"/notify_prefs",loaded));
|
||||
assert(!writeSettings(nullptr,prefs));
|
||||
assert(!readSettings(&fs,"/notify_prefs",loaded));
|
||||
prefs.enabled=1;prefs.outputs=7;
|
||||
auto& rule=prefs.rules[0];rule.used=1;
|
||||
assert(parseSelector(("room:"+std::string(64,'a')).c_str(),rule.selector));
|
||||
assert(setField(rule,FRemote,"on"));
|
||||
assert(setField(rule,FVibe,"50,300,40,20,500"));
|
||||
assert(writeSettings(&fs,prefs));
|
||||
assert(readSettings(&fs,"/notify_prefs",loaded));
|
||||
assert(!memcmp(&prefs,&loaded,sizeof(prefs)));
|
||||
const auto original=fs.files.at("/notify_prefs");
|
||||
prefs.outputs=3;
|
||||
fs.fail_write=true;
|
||||
assert(!writeSettings(&fs,prefs));
|
||||
assert(fs.files.at("/notify_prefs")==original);
|
||||
fs.fail_write=false;fs.fail_publish=true;
|
||||
assert(!writeSettings(&fs,prefs));
|
||||
assert(readSettings(&fs,"/notify_prefs",loaded));
|
||||
assert(loaded.outputs==7);
|
||||
// Preserve the recovery copy if the primary is already damaged.
|
||||
fs.files["/notify_prefs.bak"]=original;
|
||||
fs.files["/notify_prefs"][8]^=1;
|
||||
assert(!readSettings(&fs,"/notify_prefs",loaded));
|
||||
assert(!writeSettings(&fs,prefs));
|
||||
assert(readSettings(&fs,"/notify_prefs",loaded));
|
||||
assert(loaded.outputs==7);
|
||||
fs.fail_publish=false;
|
||||
assert(writeSettings(&fs,prefs));
|
||||
assert(readSettings(&fs,"/notify_prefs",loaded));
|
||||
assert(loaded.outputs==3);
|
||||
const auto good=fs.files["/notify_prefs"];
|
||||
for(size_t index:{size_t(0),size_t(4),size_t(8),good.size()-1}) {
|
||||
fs.files["/notify_prefs"]=good;fs.files["/notify_prefs"][index]^=1;
|
||||
assert(!readSettings(&fs,"/notify_prefs",loaded));
|
||||
}
|
||||
fs.files["/notify_prefs"]=good;fs.files["/notify_prefs"].pop_back();
|
||||
assert(!readSettings(&fs,"/notify_prefs",loaded));
|
||||
fs.files["/notify_prefs"]=good;fs.files["/notify_prefs"].push_back(0);
|
||||
assert(!readSettings(&fs,"/notify_prefs",loaded));
|
||||
// Interrupted publication can load its good backup, then save again.
|
||||
fs.files.erase("/notify_prefs");fs.files["/notify_prefs.bak"]=good;
|
||||
assert(readSettings(&fs,"/notify_prefs.bak",loaded));
|
||||
assert(writeSettings(&fs,loaded));
|
||||
assert(fs.files["/notify_prefs"]==good);
|
||||
}
|
||||
'''
|
||||
|
||||
class NotificationSettingsTests(unittest.TestCase):
|
||||
def test_roundtrip_corruption_and_failed_publication_on_each_fs_api(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
folder=Path(folder)
|
||||
(folder/"helpers").mkdir()
|
||||
(folder/"helpers/IdentityStore.h").write_text(STUB)
|
||||
(folder/"test.cpp").write_text(PROGRAM)
|
||||
for platform in ("ESP32_PLATFORM", "NRF52_PLATFORM", "STM32_PLATFORM"):
|
||||
with self.subTest(platform=platform):
|
||||
binary=folder/platform
|
||||
subprocess.run(["g++","-std=c++17","-Wall","-Wextra","-Werror",
|
||||
"-Wno-misleading-indentation","-D"+platform,"-I"+str(folder),
|
||||
"-I"+str(ROOT/"src"),"-I"+str(ROOT/"examples/companion_radio"),
|
||||
str(folder/"test.cpp"),"-o",str(binary)],check=True)
|
||||
subprocess.run([str(binary)],check=True)
|
||||
|
||||
if __name__=="__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user