bolar_2 backup
This commit is contained in:
268
host_tests/CMakeLists.txt
Normal file
268
host_tests/CMakeLists.txt
Normal file
@@ -0,0 +1,268 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(borla_firmware2_host_tests LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
enable_testing()
|
||||
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(CJSON REQUIRED IMPORTED_TARGET libcjson)
|
||||
|
||||
add_executable(
|
||||
state_reducer_test
|
||||
state_reducer_test.cc
|
||||
../main/core/app_effect.cc
|
||||
../main/core/app_event.cc
|
||||
../main/core/runtime_state.cc
|
||||
../main/core/state_reducer.cc
|
||||
)
|
||||
|
||||
target_include_directories(state_reducer_test PRIVATE ../main)
|
||||
target_compile_options(state_reducer_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME state_reducer_test COMMAND state_reducer_test)
|
||||
|
||||
add_executable(
|
||||
effect_router_test
|
||||
effect_router_test.cc
|
||||
../main/core/app_effect.cc
|
||||
../main/core/runtime_state.cc
|
||||
../main/adapters/effect_router.cc
|
||||
)
|
||||
|
||||
target_include_directories(effect_router_test PRIVATE ../main)
|
||||
target_compile_options(effect_router_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME effect_router_test COMMAND effect_router_test)
|
||||
|
||||
add_executable(
|
||||
playback_controller_test
|
||||
playback_controller_test.cc
|
||||
../main/audio/playback_controller.cc
|
||||
)
|
||||
|
||||
target_include_directories(playback_controller_test PRIVATE ../main)
|
||||
target_compile_options(playback_controller_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME playback_controller_test COMMAND playback_controller_test)
|
||||
|
||||
add_executable(
|
||||
packed_opus_reader_test
|
||||
packed_opus_reader_test.cc
|
||||
../main/audio/packed_opus_reader.cc
|
||||
)
|
||||
|
||||
target_include_directories(packed_opus_reader_test PRIVATE ../main)
|
||||
target_compile_options(packed_opus_reader_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME packed_opus_reader_test COMMAND packed_opus_reader_test)
|
||||
|
||||
add_executable(
|
||||
connectivity_policy_test
|
||||
connectivity_policy_test.cc
|
||||
../main/connectivity/connectivity_policy.cc
|
||||
../main/connectivity/reconnect_backoff.cc
|
||||
)
|
||||
|
||||
target_include_directories(connectivity_policy_test PRIVATE ../main)
|
||||
target_compile_options(connectivity_policy_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME connectivity_policy_test COMMAND connectivity_policy_test)
|
||||
|
||||
add_executable(
|
||||
dual_network_policy_test
|
||||
dual_network_policy_test.cc
|
||||
../main/connectivity/dual_network_policy.cc
|
||||
)
|
||||
|
||||
target_include_directories(dual_network_policy_test PRIVATE ../main)
|
||||
target_compile_options(
|
||||
dual_network_policy_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(
|
||||
NAME dual_network_policy_test
|
||||
COMMAND dual_network_policy_test)
|
||||
|
||||
add_executable(
|
||||
ml307_at_parser_test
|
||||
ml307_at_parser_test.cc
|
||||
../main/connectivity/ml307_at_parser.cc
|
||||
)
|
||||
|
||||
target_include_directories(ml307_at_parser_test PRIVATE ../main)
|
||||
target_compile_options(
|
||||
ml307_at_parser_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(
|
||||
NAME ml307_at_parser_test
|
||||
COMMAND ml307_at_parser_test)
|
||||
|
||||
add_executable(
|
||||
friend_types_test
|
||||
friend_types_test.cc
|
||||
../main/friend/friend_types.cc
|
||||
)
|
||||
|
||||
target_include_directories(friend_types_test PRIVATE ../main)
|
||||
target_compile_options(
|
||||
friend_types_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME friend_types_test COMMAND friend_types_test)
|
||||
|
||||
add_executable(
|
||||
realtime_codec_test
|
||||
realtime_codec_test.cc
|
||||
../main/core/playback_types.cc
|
||||
../main/core/remote_behavior.cc
|
||||
../main/memory/memory_types.cc
|
||||
../main/protocol/protocol_message_builder.cc
|
||||
../main/protocol/server_message_dispatcher.cc
|
||||
)
|
||||
|
||||
target_include_directories(realtime_codec_test PRIVATE ../main)
|
||||
target_link_libraries(realtime_codec_test PRIVATE PkgConfig::CJSON)
|
||||
target_compile_options(realtime_codec_test PRIVATE -Wall -Wextra -Werror)
|
||||
set_source_files_properties(
|
||||
../main/protocol/server_message_dispatcher.cc
|
||||
PROPERTIES COMPILE_OPTIONS "-Wframe-larger-than=1024")
|
||||
|
||||
add_test(NAME realtime_codec_test COMMAND realtime_codec_test)
|
||||
|
||||
add_executable(
|
||||
websocket_uri_test
|
||||
websocket_uri_test.cc
|
||||
../main/protocol/websocket_uri.cc
|
||||
)
|
||||
|
||||
target_include_directories(websocket_uri_test PRIVATE ../main)
|
||||
target_compile_options(websocket_uri_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME websocket_uri_test COMMAND websocket_uri_test)
|
||||
|
||||
add_executable(
|
||||
audio_data_plane_test
|
||||
audio_data_plane_test.cc
|
||||
../main/audio/pcm_rate_converter.cc
|
||||
../main/protocol/binary_audio_protocol.cc
|
||||
)
|
||||
|
||||
target_include_directories(audio_data_plane_test PRIVATE ../main)
|
||||
target_compile_options(audio_data_plane_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME audio_data_plane_test COMMAND audio_data_plane_test)
|
||||
|
||||
add_executable(
|
||||
voice_activity_detector_test
|
||||
voice_activity_detector_test.cc
|
||||
../main/audio/voice_activity_detector.cc
|
||||
)
|
||||
|
||||
target_include_directories(voice_activity_detector_test PRIVATE ../main)
|
||||
target_compile_options(
|
||||
voice_activity_detector_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(
|
||||
NAME voice_activity_detector_test
|
||||
COMMAND voice_activity_detector_test)
|
||||
|
||||
add_executable(
|
||||
ble_provisioning_codec_test
|
||||
ble_provisioning_codec_test.cc
|
||||
../main/provisioning/ble_provisioning_codec.cc
|
||||
)
|
||||
|
||||
target_include_directories(ble_provisioning_codec_test PRIVATE ../main)
|
||||
target_link_libraries(
|
||||
ble_provisioning_codec_test PRIVATE PkgConfig::CJSON)
|
||||
target_compile_options(
|
||||
ble_provisioning_codec_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(
|
||||
NAME ble_provisioning_codec_test
|
||||
COMMAND ble_provisioning_codec_test)
|
||||
|
||||
add_executable(
|
||||
sensor_pipeline_test
|
||||
sensor_pipeline_test.cc
|
||||
../main/sensor/battery_estimator.cc
|
||||
../main/sensor/imu_processor.cc
|
||||
../main/sensor/sensor_message_codec.cc
|
||||
../main/sensor/sensor_types.cc
|
||||
../main/sensor/touch_channel.cc
|
||||
)
|
||||
|
||||
target_include_directories(sensor_pipeline_test PRIVATE ../main)
|
||||
target_compile_options(
|
||||
sensor_pipeline_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(
|
||||
NAME sensor_pipeline_test
|
||||
COMMAND sensor_pipeline_test)
|
||||
|
||||
add_executable(
|
||||
schedule_test
|
||||
schedule_test.cc
|
||||
../main/schedule/alarm_schedule.cc
|
||||
../main/schedule/reminder_schedule.cc
|
||||
)
|
||||
|
||||
target_include_directories(schedule_test PRIVATE ../main)
|
||||
target_compile_options(schedule_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME schedule_test COMMAND schedule_test)
|
||||
|
||||
add_executable(
|
||||
trace_context_test
|
||||
trace_context_test.cc
|
||||
../main/diagnostics/trace_context.cc
|
||||
)
|
||||
|
||||
target_include_directories(trace_context_test PRIVATE ../main)
|
||||
target_compile_options(
|
||||
trace_context_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME trace_context_test COMMAND trace_context_test)
|
||||
|
||||
add_executable(
|
||||
ota_endpoint_test
|
||||
ota_endpoint_test.cc
|
||||
../main/ota/ota_endpoint.cc
|
||||
)
|
||||
|
||||
target_include_directories(ota_endpoint_test PRIVATE ../main)
|
||||
target_compile_options(
|
||||
ota_endpoint_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(NAME ota_endpoint_test COMMAND ota_endpoint_test)
|
||||
|
||||
add_executable(
|
||||
ota_response_parser_test
|
||||
ota_response_parser_test.cc
|
||||
../main/ota/ota_endpoint.cc
|
||||
../main/ota/ota_response_parser.cc
|
||||
../main/ota/ota_types.cc
|
||||
)
|
||||
|
||||
target_include_directories(ota_response_parser_test PRIVATE ../main)
|
||||
target_link_libraries(
|
||||
ota_response_parser_test PRIVATE PkgConfig::CJSON)
|
||||
target_compile_options(
|
||||
ota_response_parser_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(
|
||||
NAME ota_response_parser_test
|
||||
COMMAND ota_response_parser_test)
|
||||
|
||||
add_executable(
|
||||
task_stack_budget_test
|
||||
task_stack_budget_test.cc
|
||||
)
|
||||
|
||||
target_include_directories(task_stack_budget_test PRIVATE ../main)
|
||||
target_compile_options(
|
||||
task_stack_budget_test PRIVATE -Wall -Wextra -Werror)
|
||||
|
||||
add_test(
|
||||
NAME task_stack_budget_test
|
||||
COMMAND task_stack_budget_test)
|
||||
185
host_tests/audio_data_plane_test.cc
Normal file
185
host_tests/audio_data_plane_test.cc
Normal file
@@ -0,0 +1,185 @@
|
||||
#include "audio/downlink_preroll_buffer.h"
|
||||
#include "audio/pcm_rate_converter.h"
|
||||
#include "protocol/binary_audio_protocol.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
class CollectingVisitor final : public IBinaryAudioFrameVisitor {
|
||||
public:
|
||||
bool OnOpusFrame(const uint8_t* data, size_t size) override
|
||||
{
|
||||
frames.emplace_back(data, data + size);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::vector<uint8_t>> frames;
|
||||
};
|
||||
|
||||
void TestExactFrameRateConversion()
|
||||
{
|
||||
std::array<int16_t, Pcm24kTo16kConverter::kInputSamples> input{};
|
||||
std::array<int16_t, Pcm24kTo16kConverter::kOutputSamples> output{};
|
||||
for (size_t index = 0; index < input.size(); ++index) {
|
||||
input[index] = static_cast<int16_t>(index);
|
||||
}
|
||||
|
||||
Pcm24kTo16kConverter converter;
|
||||
assert(converter.Convert(
|
||||
input.data(), input.size(), output.data(), output.size()));
|
||||
assert(output[0] == 0);
|
||||
assert(output[1] == 1);
|
||||
assert(output[2] == 3);
|
||||
assert(output[3] == 4);
|
||||
assert(output.back() == 1438);
|
||||
assert(!converter.Convert(
|
||||
input.data(), input.size() - 1, output.data(), output.size()));
|
||||
}
|
||||
|
||||
void TestBatchRoundTrip()
|
||||
{
|
||||
BinaryAudioBatchBuilder builder;
|
||||
const std::array<uint8_t, 3> first{1, 2, 3};
|
||||
const std::array<uint8_t, 4> second{4, 5, 6, 7};
|
||||
assert(builder.Push(first.data(), first.size()));
|
||||
assert(builder.Push(second.data(), second.size()));
|
||||
|
||||
std::array<uint8_t, kBinaryAudioMaximumPacketBytes> packet{};
|
||||
size_t packet_size = 0;
|
||||
assert(builder.Build(packet.data(), packet.size(), &packet_size));
|
||||
assert(packet[0] == kBinaryAudioTypeOpus);
|
||||
assert(packet[1] == kBinaryAudioFlagBatch);
|
||||
assert(packet_size == 4 + 2 + first.size() + 2 + second.size());
|
||||
|
||||
CollectingVisitor visitor;
|
||||
size_t frames = 0;
|
||||
assert(VisitBinaryAudioPacket(
|
||||
packet.data(), packet_size, visitor, &frames));
|
||||
assert(frames == 2);
|
||||
assert(visitor.frames[0] ==
|
||||
std::vector<uint8_t>(first.begin(), first.end()));
|
||||
assert(visitor.frames[1] ==
|
||||
std::vector<uint8_t>(second.begin(), second.end()));
|
||||
}
|
||||
|
||||
void TestSingleAndMalformedPackets()
|
||||
{
|
||||
const std::array<uint8_t, 3> payload{9, 8, 7};
|
||||
std::array<uint8_t, 16> built{};
|
||||
size_t built_size = 0;
|
||||
assert(BuildBinaryAudioSingleFrame(
|
||||
payload.data(), payload.size(),
|
||||
built.data(), built.size(), &built_size));
|
||||
assert(built_size == 7);
|
||||
assert(built[0] == kBinaryAudioTypeOpus);
|
||||
assert(built[1] == 0);
|
||||
|
||||
const std::array<uint8_t, 7> single{
|
||||
0, 0, 0, 3, 9, 8, 7};
|
||||
assert(std::equal(built.begin(), built.begin() + built_size,
|
||||
single.begin()));
|
||||
CollectingVisitor visitor;
|
||||
assert(VisitBinaryAudioPacket(
|
||||
single.data(), single.size(), visitor));
|
||||
assert(visitor.frames.size() == 1);
|
||||
|
||||
auto malformed = single;
|
||||
malformed[3] = 4;
|
||||
CollectingVisitor invalid_visitor;
|
||||
assert(!VisitBinaryAudioPacket(
|
||||
malformed.data(), malformed.size(), invalid_visitor));
|
||||
|
||||
const std::array<uint8_t, 8> zero_frame{
|
||||
0, 1, 0, 4, 0, 0, 1, 2};
|
||||
assert(!VisitBinaryAudioPacket(
|
||||
zero_frame.data(), zero_frame.size(), invalid_visitor));
|
||||
|
||||
const std::array<uint8_t, 11> valid_then_broken{
|
||||
0, 1, 0, 7, 0, 2, 1, 2, 0, 3, 9};
|
||||
CollectingVisitor atomic_visitor;
|
||||
assert(!VisitBinaryAudioPacket(
|
||||
valid_then_broken.data(),
|
||||
valid_then_broken.size(),
|
||||
atomic_visitor));
|
||||
assert(atomic_visitor.frames.empty());
|
||||
}
|
||||
|
||||
void TestBatchCapacity()
|
||||
{
|
||||
BinaryAudioBatchBuilder builder;
|
||||
std::array<uint8_t, kBinaryAudioMaximumUplinkOpusBytes> frame{};
|
||||
for (size_t index = 0;
|
||||
index < kBinaryAudioBatchFrames;
|
||||
++index) {
|
||||
assert(builder.Push(frame.data(), frame.size()));
|
||||
}
|
||||
assert(builder.Full());
|
||||
assert(!builder.Push(frame.data(), frame.size()));
|
||||
builder.Reset();
|
||||
assert(builder.Empty());
|
||||
}
|
||||
|
||||
void TestDownlinkPrerollPreservesOrderAndSessionIsolation()
|
||||
{
|
||||
DownlinkPrerollBuffer preroll;
|
||||
const std::array<uint8_t, 3> first{1, 2, 3};
|
||||
const std::array<uint8_t, 2> second{4, 5};
|
||||
assert(preroll.Push(41, first.data(), first.size()));
|
||||
assert(preroll.Push(41, second.data(), second.size()));
|
||||
assert(preroll.session_id() == 41);
|
||||
assert(preroll.frame_count() == 2);
|
||||
assert(preroll.FrameSize(0) == first.size());
|
||||
assert(std::memcmp(
|
||||
preroll.FrameData(0), first.data(), first.size()) == 0);
|
||||
assert(std::memcmp(
|
||||
preroll.FrameData(1), second.data(), second.size()) == 0);
|
||||
|
||||
assert(preroll.Push(42, second.data(), second.size()));
|
||||
assert(preroll.session_id() == 42);
|
||||
assert(preroll.frame_count() == 1);
|
||||
assert(preroll.FrameData(1) == nullptr);
|
||||
|
||||
preroll.Reset();
|
||||
assert(preroll.session_id() == 0);
|
||||
assert(preroll.frame_count() == 0);
|
||||
}
|
||||
|
||||
void TestDownlinkPrerollIsBounded()
|
||||
{
|
||||
DownlinkPrerollBuffer preroll;
|
||||
std::array<uint8_t, kBinaryAudioMaximumOpusBytes> frame{};
|
||||
for (size_t index = 0;
|
||||
index < DownlinkPrerollBuffer::kCapacity;
|
||||
++index) {
|
||||
frame[0] = static_cast<uint8_t>(index);
|
||||
assert(preroll.Push(7, frame.data(), frame.size()));
|
||||
}
|
||||
assert(!preroll.Push(7, frame.data(), frame.size()));
|
||||
assert(!preroll.Push(0, frame.data(), frame.size()));
|
||||
assert(!preroll.Push(7, nullptr, frame.size()));
|
||||
std::array<uint8_t, kBinaryAudioMaximumOpusBytes + 1> oversized{};
|
||||
assert(!preroll.Push(7, oversized.data(), oversized.size()));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestExactFrameRateConversion();
|
||||
TestBatchRoundTrip();
|
||||
TestSingleAndMalformedPackets();
|
||||
TestBatchCapacity();
|
||||
TestDownlinkPrerollPreservesOrderAndSessionIsolation();
|
||||
TestDownlinkPrerollIsBounded();
|
||||
std::cout << "audio data plane tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
141
host_tests/ble_provisioning_codec_test.cc
Normal file
141
host_tests/ble_provisioning_codec_test.cc
Normal file
@@ -0,0 +1,141 @@
|
||||
#include "provisioning/ble_provisioning_codec.h"
|
||||
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
class ChunkCollector final : public IBleChunkVisitor {
|
||||
public:
|
||||
bool OnBleChunk(const uint8_t* data, size_t size) override
|
||||
{
|
||||
chunks.emplace_back(data, data + size);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::vector<uint8_t>> chunks;
|
||||
};
|
||||
|
||||
void TestCredentialAssemblyAndValidation()
|
||||
{
|
||||
BleChunkAssembler assembler;
|
||||
const std::string json =
|
||||
R"({"ssid":"Home","password":"secret123"})";
|
||||
const std::array<uint8_t, 12> first{
|
||||
0, 0, '{', '"', 's', 's', 'i', 'd', '"', ':', '"', 'H'};
|
||||
std::vector<uint8_t> second{1, 1};
|
||||
second.insert(
|
||||
second.end(), json.begin() + 10, json.end());
|
||||
|
||||
assert(
|
||||
assembler.Push(first.data(), first.size()) ==
|
||||
BleChunkAssemblyResult::kAccepted);
|
||||
assert(
|
||||
assembler.Push(second.data(), second.size()) ==
|
||||
BleChunkAssemblyResult::kComplete);
|
||||
WifiCredential credential;
|
||||
assert(ParseProvisioningCredential(
|
||||
assembler.data(), assembler.size(), &credential));
|
||||
assert(std::strcmp(credential.ssid.data(), "Home") == 0);
|
||||
assert(std::strcmp(
|
||||
credential.password.data(), "secret123") == 0);
|
||||
|
||||
const std::array<uint8_t, 3> out_of_order{2, 1, 'x'};
|
||||
assert(
|
||||
assembler.Push(
|
||||
out_of_order.data(), out_of_order.size()) ==
|
||||
BleChunkAssemblyResult::kInvalid);
|
||||
}
|
||||
|
||||
void TestChunkRoundTripAtDefaultMtu()
|
||||
{
|
||||
const std::string json(97, 'x');
|
||||
ChunkCollector collector;
|
||||
assert(VisitBleNotificationChunks(
|
||||
json.data(), json.size(), 23, collector));
|
||||
assert(collector.chunks.size() == 6);
|
||||
|
||||
BleChunkAssembler assembler;
|
||||
for (size_t index = 0;
|
||||
index < collector.chunks.size();
|
||||
++index) {
|
||||
const auto& chunk = collector.chunks[index];
|
||||
const auto expected =
|
||||
index + 1 == collector.chunks.size()
|
||||
? BleChunkAssemblyResult::kComplete
|
||||
: BleChunkAssemblyResult::kAccepted;
|
||||
assert(assembler.Push(chunk.data(), chunk.size()) == expected);
|
||||
}
|
||||
assert(assembler.size() == json.size());
|
||||
assert(std::memcmp(
|
||||
assembler.data(), json.data(), json.size()) == 0);
|
||||
}
|
||||
|
||||
void TestJsonContractsHidePasswords()
|
||||
{
|
||||
DeviceIdentity identity;
|
||||
std::strcpy(identity.mac, "AA:BB:CC:DD:EE:FF");
|
||||
std::strcpy(identity.app_version, "2.0.0-dev");
|
||||
std::strcpy(identity.board, "borla_s3");
|
||||
std::array<char, 512> output{};
|
||||
size_t size = 0;
|
||||
assert(BuildProvisioningDeviceInfoJson(
|
||||
identity, output.data(), output.size(), &size));
|
||||
assert(std::strstr(output.data(), "AA:BB:CC:DD:EE:FF"));
|
||||
assert(std::strstr(output.data(), "borla_s3"));
|
||||
|
||||
std::array<WifiCredential, 2> saved{};
|
||||
assert(saved[0].Set("Home", "top-secret"));
|
||||
assert(saved[1].Set("Office", "also-secret"));
|
||||
assert(BuildProvisioningSavedWifiJson(
|
||||
saved.data(), saved.size(),
|
||||
output.data(), output.size(), &size));
|
||||
assert(std::strstr(output.data(), "\"ssid\":\"Home\""));
|
||||
assert(std::strstr(output.data(), "\"index\":1"));
|
||||
assert(std::strstr(output.data(), "secret") == nullptr);
|
||||
assert(std::strstr(output.data(), "password") == nullptr);
|
||||
}
|
||||
|
||||
void TestScanAndResultJson()
|
||||
{
|
||||
std::array<WifiNetwork, 2> networks{};
|
||||
std::strcpy(networks[0].ssid.data(), "Home");
|
||||
networks[0].rssi_dbm = -42;
|
||||
networks[0].auth_mode = 3;
|
||||
std::strcpy(networks[1].ssid.data(), "Guest");
|
||||
networks[1].rssi_dbm = -70;
|
||||
|
||||
std::array<char, 512> output{};
|
||||
size_t size = 0;
|
||||
assert(BuildProvisioningScanJson(
|
||||
networks.data(), networks.size(),
|
||||
output.data(), output.size(), &size));
|
||||
assert(std::strstr(output.data(), "\"rssi\":-42"));
|
||||
assert(std::strstr(output.data(), "\"auth\":3"));
|
||||
|
||||
assert(BuildProvisioningResultJson(
|
||||
false, "password_wrong",
|
||||
output.data(), output.size(), &size));
|
||||
assert(std::strcmp(
|
||||
output.data(),
|
||||
R"({"success":false,"error":"password_wrong"})") == 0);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestCredentialAssemblyAndValidation();
|
||||
TestChunkRoundTripAtDefaultMtu();
|
||||
TestJsonContractsHidePasswords();
|
||||
TestScanAndResultJson();
|
||||
std::cout << "BLE provisioning codec tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
185
host_tests/connectivity_policy_test.cc
Normal file
185
host_tests/connectivity_policy_test.cc
Normal file
@@ -0,0 +1,185 @@
|
||||
#include "connectivity/connectivity_policy.h"
|
||||
#include "connectivity/wifi_types.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
const ConnectivityAction* FindAction(
|
||||
const ConnectivityPolicyResult& result,
|
||||
ConnectivityActionType type)
|
||||
{
|
||||
for (size_t index = 0; index < result.action_count; ++index) {
|
||||
if (result.actions[index].type == type) {
|
||||
return &result.actions[index];
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ReconnectBackoffConfig DeterministicConfig()
|
||||
{
|
||||
return ReconnectBackoffConfig{
|
||||
100,
|
||||
500,
|
||||
2,
|
||||
0,
|
||||
};
|
||||
}
|
||||
|
||||
void TestCredentialValidation()
|
||||
{
|
||||
WifiCredential credential;
|
||||
assert(!credential.Set("", "password"));
|
||||
assert(credential.Set("borla-test", ""));
|
||||
assert(credential.IsValid());
|
||||
|
||||
const char too_long_ssid[] =
|
||||
"123456789012345678901234567890123";
|
||||
assert(!credential.Set(too_long_ssid, "password"));
|
||||
}
|
||||
|
||||
void TestBackoffCapsAndResets()
|
||||
{
|
||||
ReconnectBackoff backoff(DeterministicConfig());
|
||||
assert(backoff.NextDelayMs(0) == 100);
|
||||
assert(backoff.NextDelayMs(0) == 200);
|
||||
assert(backoff.NextDelayMs(0) == 400);
|
||||
assert(backoff.NextDelayMs(0) == 500);
|
||||
assert(backoff.NextDelayMs(0) == 500);
|
||||
assert(backoff.attempt_count() == 5);
|
||||
|
||||
backoff.Reset();
|
||||
assert(backoff.attempt_count() == 0);
|
||||
assert(backoff.NextDelayMs(0) == 100);
|
||||
}
|
||||
|
||||
void TestMissingCredentialsRequestsProvisioning()
|
||||
{
|
||||
ConnectivityPolicy policy(DeterministicConfig());
|
||||
const ConnectivityPolicyResult result = policy.Start(0);
|
||||
assert(
|
||||
policy.state() ==
|
||||
ConnectivityPolicyState::kCredentialsMissing);
|
||||
assert(
|
||||
FindAction(
|
||||
result,
|
||||
ConnectivityActionType::kRequestProvisioning) != nullptr);
|
||||
|
||||
assert(policy.Start(3).action_count == 0);
|
||||
const ConnectivityPolicyResult stop = policy.Stop();
|
||||
assert(
|
||||
FindAction(stop, ConnectivityActionType::kStopTransport) !=
|
||||
nullptr);
|
||||
assert(policy.state() == ConnectivityPolicyState::kStopped);
|
||||
}
|
||||
|
||||
void TestConnectDisconnectAndRecovery()
|
||||
{
|
||||
ConnectivityPolicy policy(DeterministicConfig());
|
||||
|
||||
ConnectivityPolicyResult result = policy.Start(2);
|
||||
assert(
|
||||
FindAction(result, ConnectivityActionType::kStartTransport) !=
|
||||
nullptr);
|
||||
assert(policy.Start(2).action_count == 0);
|
||||
|
||||
result = policy.OnTransportReady();
|
||||
const ConnectivityAction* connect =
|
||||
FindAction(result, ConnectivityActionType::kConnectCredential);
|
||||
assert(connect != nullptr);
|
||||
assert(connect->credential_index == 0);
|
||||
|
||||
result = policy.OnGotIp();
|
||||
assert(
|
||||
FindAction(result, ConnectivityActionType::kPublishConnected) !=
|
||||
nullptr);
|
||||
assert(policy.state() == ConnectivityPolicyState::kOnline);
|
||||
assert(policy.OnGotIp().action_count == 0);
|
||||
|
||||
result = policy.OnDisconnected(201, 0);
|
||||
assert(
|
||||
FindAction(
|
||||
result,
|
||||
ConnectivityActionType::kPublishDisconnected) != nullptr);
|
||||
const ConnectivityAction* retry =
|
||||
FindAction(result, ConnectivityActionType::kScheduleRetry);
|
||||
assert(retry != nullptr);
|
||||
assert(retry->delay_ms == 100);
|
||||
assert(policy.credential_index() == 1);
|
||||
|
||||
assert(policy.OnDisconnected(202, 0).action_count == 0);
|
||||
result = policy.OnRetryElapsed();
|
||||
connect =
|
||||
FindAction(result, ConnectivityActionType::kConnectCredential);
|
||||
assert(connect != nullptr);
|
||||
assert(connect->credential_index == 1);
|
||||
|
||||
result = policy.OnGotIp();
|
||||
assert(
|
||||
FindAction(result, ConnectivityActionType::kPublishConnected) !=
|
||||
nullptr);
|
||||
assert(policy.retry_attempt_count() == 0);
|
||||
assert(policy.last_disconnect_reason() == 201);
|
||||
}
|
||||
|
||||
void TestTransportFailureUsesBackoff()
|
||||
{
|
||||
ConnectivityPolicy policy(DeterministicConfig());
|
||||
policy.Start(1);
|
||||
|
||||
ConnectivityPolicyResult result =
|
||||
policy.OnTransportStartFailed(0);
|
||||
const ConnectivityAction* retry =
|
||||
FindAction(result, ConnectivityActionType::kScheduleRetry);
|
||||
assert(retry != nullptr);
|
||||
assert(retry->delay_ms == 100);
|
||||
assert(!policy.transport_ready());
|
||||
|
||||
result = policy.OnRetryElapsed();
|
||||
assert(
|
||||
FindAction(result, ConnectivityActionType::kStartTransport) !=
|
||||
nullptr);
|
||||
assert(
|
||||
policy.state() ==
|
||||
ConnectivityPolicyState::kStartingTransport);
|
||||
}
|
||||
|
||||
void TestStopRejectsLateDriverEvents()
|
||||
{
|
||||
ConnectivityPolicy policy(DeterministicConfig());
|
||||
policy.Start(1);
|
||||
policy.OnTransportReady();
|
||||
policy.OnGotIp();
|
||||
|
||||
const ConnectivityPolicyResult result = policy.Stop();
|
||||
assert(
|
||||
FindAction(result, ConnectivityActionType::kCancelRetry) !=
|
||||
nullptr);
|
||||
assert(
|
||||
FindAction(result, ConnectivityActionType::kStopTransport) !=
|
||||
nullptr);
|
||||
assert(policy.state() == ConnectivityPolicyState::kStopped);
|
||||
assert(policy.OnGotIp().action_count == 0);
|
||||
assert(policy.OnDisconnected(1, 0).action_count == 0);
|
||||
assert(policy.OnRetryElapsed().action_count == 0);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestCredentialValidation();
|
||||
TestBackoffCapsAndResets();
|
||||
TestMissingCredentialsRequestsProvisioning();
|
||||
TestConnectDisconnectAndRecovery();
|
||||
TestTransportFailureUsesBackoff();
|
||||
TestStopRejectsLateDriverEvents();
|
||||
|
||||
std::cout << "connectivity policy tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
206
host_tests/dual_network_policy_test.cc
Normal file
206
host_tests/dual_network_policy_test.cc
Normal file
@@ -0,0 +1,206 @@
|
||||
#include "connectivity/dual_network_policy.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
bool Has(
|
||||
const DualNetworkPolicyResult& result,
|
||||
DualNetworkActionType type)
|
||||
{
|
||||
for (size_t index = 0; index < result.action_count; ++index) {
|
||||
if (result.actions[index].type == type) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
DualNetworkPolicyConfig Config()
|
||||
{
|
||||
return {30000, -80, 3, 2, 120000};
|
||||
}
|
||||
|
||||
void TestMissingWifiRequestsProvisioning()
|
||||
{
|
||||
DualNetworkPolicy policy(Config());
|
||||
const auto result = policy.Start(false, 0);
|
||||
assert(Has(result, DualNetworkActionType::kRequestProvisioning));
|
||||
assert(policy.selected_bearer() == NetworkBearer::kNone);
|
||||
}
|
||||
|
||||
void TestDisconnectedWifiFailsOver()
|
||||
{
|
||||
DualNetworkPolicy policy(Config());
|
||||
assert(Has(policy.Start(true, 100),
|
||||
DualNetworkActionType::kStartWifi));
|
||||
policy.OnWifiOnline(200);
|
||||
policy.OnWifiDisconnected(1000);
|
||||
|
||||
assert(policy.OnMonitor(
|
||||
30999, -127, ModemPresence::kPresent).action_count == 0);
|
||||
const auto result =
|
||||
policy.OnMonitor(31000, -127, ModemPresence::kPresent);
|
||||
assert(Has(result, DualNetworkActionType::kStopWifi));
|
||||
assert(Has(result, DualNetworkActionType::kStartCellular));
|
||||
assert(Has(result, DualNetworkActionType::kRequestReconnect));
|
||||
assert(policy.selected_bearer() == NetworkBearer::kCellular);
|
||||
}
|
||||
|
||||
void TestWeakWifiRequiresConsecutiveSamples()
|
||||
{
|
||||
DualNetworkPolicy policy(Config());
|
||||
policy.Start(true, 0);
|
||||
policy.OnWifiOnline(100);
|
||||
assert(policy.OnMonitor(
|
||||
1000, -85, ModemPresence::kPresent).action_count == 0);
|
||||
assert(policy.OnMonitor(
|
||||
2000, -85, ModemPresence::kPresent).action_count == 0);
|
||||
policy.OnMonitor(2500, -60, ModemPresence::kPresent);
|
||||
assert(policy.weak_sample_count() == 0);
|
||||
policy.OnMonitor(3000, -90, ModemPresence::kPresent);
|
||||
policy.OnMonitor(4000, -90, ModemPresence::kPresent);
|
||||
const auto result =
|
||||
policy.OnMonitor(5000, -90, ModemPresence::kPresent);
|
||||
assert(Has(result, DualNetworkActionType::kNotifyDisconnected));
|
||||
assert(policy.selected_bearer() == NetworkBearer::kCellular);
|
||||
}
|
||||
|
||||
void TestAbsentModemPreventsAutomaticAndManualSwitch()
|
||||
{
|
||||
DualNetworkPolicy policy(Config());
|
||||
policy.Start(true, 0);
|
||||
policy.OnWifiOnline(100);
|
||||
policy.OnWifiDisconnected(1000);
|
||||
assert(policy.OnMonitor(
|
||||
40000, -127, ModemPresence::kAbsent).action_count == 0);
|
||||
const auto manual =
|
||||
policy.RequestManualSwitch(41000, ModemPresence::kAbsent);
|
||||
assert(Has(
|
||||
manual,
|
||||
DualNetworkActionType::kPromptCellularUnavailable));
|
||||
assert(policy.selected_bearer() == NetworkBearer::kWifi);
|
||||
}
|
||||
|
||||
void TestCellularFailureFallsBackToWifi()
|
||||
{
|
||||
DualNetworkPolicy policy(Config());
|
||||
policy.Start(true, 0);
|
||||
policy.RequestManualSwitch(100, ModemPresence::kPresent);
|
||||
policy.OnCellularOnline(200);
|
||||
const auto result = policy.OnCellularDisconnected(300);
|
||||
assert(Has(result, DualNetworkActionType::kStopCellular));
|
||||
assert(Has(result, DualNetworkActionType::kStartWifi));
|
||||
assert(Has(result, DualNetworkActionType::kRequestReconnect));
|
||||
assert(policy.selected_bearer() == NetworkBearer::kWifi);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void TestModemSwitchSensingAnnouncements()
|
||||
{
|
||||
DualNetworkPolicy policy(Config());
|
||||
policy.Start(true, 0);
|
||||
|
||||
// Unknown probes (UART driver unavailable) must never be read as OFF.
|
||||
assert(policy.OnModemPresence(
|
||||
ModemPresence::kUnknown, 1000).action_count == 0);
|
||||
assert(policy.stable_modem_presence() == ModemPresence::kUnknown);
|
||||
|
||||
// First usable reading with the switch ON -> boot announcement, once.
|
||||
assert(Has(policy.OnModemPresence(ModemPresence::kPresent, 2000),
|
||||
DualNetworkActionType::kPromptCellularBootOn));
|
||||
assert(policy.stable_modem_presence() == ModemPresence::kPresent);
|
||||
assert(policy.OnModemPresence(
|
||||
ModemPresence::kPresent, 5000).action_count == 0);
|
||||
|
||||
// ON -> OFF needs two consecutive misses (UART jitter debounce).
|
||||
assert(policy.OnModemPresence(
|
||||
ModemPresence::kAbsent, 8000).action_count == 0);
|
||||
assert(Has(policy.OnModemPresence(ModemPresence::kAbsent, 11000),
|
||||
DualNetworkActionType::kPromptCellularOff));
|
||||
assert(policy.stable_modem_presence() == ModemPresence::kAbsent);
|
||||
assert(policy.OnModemPresence(
|
||||
ModemPresence::kAbsent, 14000).action_count == 0);
|
||||
|
||||
// A single miss followed by a hit must not announce OFF at all.
|
||||
assert(Has(policy.OnModemPresence(ModemPresence::kPresent, 17000),
|
||||
DualNetworkActionType::kPromptCellularOn));
|
||||
assert(policy.OnModemPresence(
|
||||
ModemPresence::kAbsent, 20000).action_count == 0);
|
||||
assert(policy.OnModemPresence(
|
||||
ModemPresence::kPresent, 23000).action_count == 0);
|
||||
assert(policy.stable_modem_presence() == ModemPresence::kPresent);
|
||||
|
||||
// Booting with the switch already OFF says nothing.
|
||||
DualNetworkPolicy quiet(Config());
|
||||
quiet.Start(true, 0);
|
||||
assert(quiet.OnModemPresence(
|
||||
ModemPresence::kAbsent, 1000).action_count == 0);
|
||||
assert(quiet.stable_modem_presence() == ModemPresence::kAbsent);
|
||||
}
|
||||
|
||||
void TestWifiLostWithoutModemIsRateLimited()
|
||||
{
|
||||
DualNetworkPolicy policy(Config());
|
||||
policy.Start(true, 0);
|
||||
|
||||
// Modem presence is still unknown: stay quiet rather than guess.
|
||||
assert(policy.NotifyWifiLostWithoutModem(1000).action_count == 0);
|
||||
|
||||
policy.OnModemPresence(ModemPresence::kAbsent, 2000);
|
||||
assert(policy.stable_modem_presence() == ModemPresence::kAbsent);
|
||||
|
||||
// WiFi has never been up yet — a booting device must not be told to flip
|
||||
// the 4G switch just because it has not associated yet.
|
||||
assert(policy.NotifyWifiLostWithoutModem(3000).action_count == 0);
|
||||
|
||||
policy.OnWifiOnline(4000);
|
||||
assert(policy.NotifyWifiLostWithoutModem(5000).action_count == 0);
|
||||
|
||||
// Now WiFi drops. The prompt waits for the same 30 s deadline the
|
||||
// automatic failover uses, so brief blips stay silent.
|
||||
policy.OnWifiDisconnected(10000);
|
||||
assert(policy.NotifyWifiLostWithoutModem(15000).action_count == 0);
|
||||
assert(policy.NotifyWifiLostWithoutModem(39999).action_count == 0);
|
||||
assert(Has(policy.NotifyWifiLostWithoutModem(40000),
|
||||
DualNetworkActionType::kPromptCellularUnavailable));
|
||||
|
||||
// The WiFi monitor fires every few seconds; only one prompt per window.
|
||||
assert(policy.NotifyWifiLostWithoutModem(45000).action_count == 0);
|
||||
assert(policy.NotifyWifiLostWithoutModem(159999).action_count == 0);
|
||||
assert(Has(policy.NotifyWifiLostWithoutModem(160000),
|
||||
DualNetworkActionType::kPromptCellularUnavailable));
|
||||
|
||||
// WiFi coming back stops the prompting entirely.
|
||||
policy.OnWifiOnline(170000);
|
||||
assert(policy.NotifyWifiLostWithoutModem(300000).action_count == 0);
|
||||
|
||||
// Flipping the switch on also clears the rate-limit window, so the next
|
||||
// qualifying outage is reported without waiting out the old one.
|
||||
policy.OnWifiDisconnected(310000);
|
||||
policy.OnModemPresence(ModemPresence::kPresent, 311000);
|
||||
assert(policy.NotifyWifiLostWithoutModem(345000).action_count == 0);
|
||||
policy.OnModemPresence(ModemPresence::kAbsent, 346000);
|
||||
policy.OnModemPresence(ModemPresence::kAbsent, 347000);
|
||||
assert(Has(policy.NotifyWifiLostWithoutModem(348000),
|
||||
DualNetworkActionType::kPromptCellularUnavailable));
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
TestMissingWifiRequestsProvisioning();
|
||||
TestDisconnectedWifiFailsOver();
|
||||
TestWeakWifiRequiresConsecutiveSamples();
|
||||
TestAbsentModemPreventsAutomaticAndManualSwitch();
|
||||
TestCellularFailureFallsBackToWifi();
|
||||
TestModemSwitchSensingAnnouncements();
|
||||
TestWifiLostWithoutModemIsRateLimited();
|
||||
std::cout << "dual network policy tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
381
host_tests/effect_router_test.cc
Normal file
381
host_tests/effect_router_test.cc
Normal file
@@ -0,0 +1,381 @@
|
||||
#include "adapters/effect_router.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
class FakeAudio final : public IAudioEngine {
|
||||
public:
|
||||
bool Start() override
|
||||
{
|
||||
started = true;
|
||||
return true;
|
||||
}
|
||||
void Stop() override { started = false; }
|
||||
void ApplyPolicy(AudioPolicy value) override { policy = value; }
|
||||
void SetVolume(uint8_t value) override { volume = value; }
|
||||
void SetWakeWordEnabled(bool value) override
|
||||
{
|
||||
wake_word_enabled = value;
|
||||
}
|
||||
void SetBargeInEnabled(bool value) override
|
||||
{
|
||||
barge_in_enabled = value;
|
||||
}
|
||||
void SetPlaybackPaused(bool value) override
|
||||
{
|
||||
playback_paused = value;
|
||||
}
|
||||
void ReleaseWakeWord() override
|
||||
{
|
||||
wake_word_released = true;
|
||||
}
|
||||
void LogAudioMetrics(const char*) override {}
|
||||
bool LogAudioFrameStats() override { return false; }
|
||||
bool WaitForPlaybackIdle(uint32_t) override { return true; }
|
||||
void CancelPlayback(PlaybackSessionId value) override
|
||||
{
|
||||
cancelled_session = value;
|
||||
}
|
||||
void BeginRemotePlayback(
|
||||
PlaybackSessionId value,
|
||||
PlaybackPriority value_priority) override
|
||||
{
|
||||
remote_session = value;
|
||||
priority = value_priority;
|
||||
}
|
||||
void EndPlaybackInput(PlaybackSessionId value) override
|
||||
{
|
||||
ended_session = value;
|
||||
}
|
||||
bool SubmitOpusFrame(
|
||||
PlaybackSessionId,
|
||||
const uint8_t*,
|
||||
size_t) override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
PlaybackSessionId PlayLocalPrompt(
|
||||
LocalPrompt value,
|
||||
PlaybackPriority value_priority,
|
||||
int16_t value_selector) override
|
||||
{
|
||||
prompt = value;
|
||||
priority = value_priority;
|
||||
selector = value_selector;
|
||||
return 101;
|
||||
}
|
||||
PlaybackSessionId PlayLocalSequence(
|
||||
const LocalPromptSequence&,
|
||||
PlaybackPriority value_priority) override
|
||||
{
|
||||
priority = value_priority;
|
||||
return 102;
|
||||
}
|
||||
PlaybackSessionId PlayDetachedPrompt(
|
||||
LocalPrompt value,
|
||||
PlaybackPriority value_priority) override
|
||||
{
|
||||
detached_prompt = value;
|
||||
detached_priority = value_priority;
|
||||
detached_count++;
|
||||
return 103;
|
||||
}
|
||||
uint8_t OutputVolumePercent() const override { return volume; }
|
||||
|
||||
bool started = false;
|
||||
LocalPrompt detached_prompt = LocalPrompt::kError;
|
||||
PlaybackPriority detached_priority = PlaybackPriority::kBackground;
|
||||
int detached_count = 0;
|
||||
AudioPolicy policy = AudioPolicy::kOff;
|
||||
uint8_t volume = 0;
|
||||
bool wake_word_enabled = true;
|
||||
bool barge_in_enabled = false;
|
||||
bool playback_paused = false;
|
||||
bool wake_word_released = false;
|
||||
PlaybackSessionId cancelled_session = 0;
|
||||
PlaybackSessionId remote_session = 0;
|
||||
PlaybackSessionId ended_session = 0;
|
||||
PlaybackPriority priority = PlaybackPriority::kBackground;
|
||||
LocalPrompt prompt = LocalPrompt::kError;
|
||||
int16_t selector = -1;
|
||||
};
|
||||
|
||||
class FakeConnectivity final : public IConnectivityManager {
|
||||
public:
|
||||
void Start() override { started = true; }
|
||||
void Stop() override { started = false; }
|
||||
void SwitchNetwork() override { switched = true; }
|
||||
bool IsOnline() const override { return online; }
|
||||
ConnectivityDiagnostics GetDiagnostics() const override { return {}; }
|
||||
|
||||
bool started = false;
|
||||
bool switched = false;
|
||||
bool online = false;
|
||||
};
|
||||
|
||||
class FakeRealtime final : public IRealtimeProtocol {
|
||||
public:
|
||||
void Open() override { opened = true; }
|
||||
void Close() override { opened = false; }
|
||||
void SendStartListening() override { start_listening_count++; }
|
||||
void SendStopListening() override { stop_listening_count++; }
|
||||
void SendAbortSpeaking(
|
||||
ConversationInterruptSource source) override
|
||||
{
|
||||
abort_source = source;
|
||||
abort_speaking_count++;
|
||||
}
|
||||
void SendGoodbye() override { goodbye_count++; }
|
||||
void SendAcceptCall() override { accept_call_count++; }
|
||||
void SendHangupCall() override { hangup_call_count++; }
|
||||
void SendButtonClick(uint8_t click_count) override
|
||||
{
|
||||
button_click_count = click_count;
|
||||
}
|
||||
void SendLocalPlaybackState(
|
||||
LocalPrompt prompt,
|
||||
bool started) override
|
||||
{
|
||||
local_prompt = prompt;
|
||||
local_started = started;
|
||||
local_state_count++;
|
||||
}
|
||||
bool SendFriendAdd(
|
||||
const char*,
|
||||
const char*,
|
||||
const char*,
|
||||
const char*) override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
bool SendOtaNotify(const char*, bool) override
|
||||
{
|
||||
ota_notify_count++;
|
||||
return true;
|
||||
}
|
||||
void RequestConnectionErrorPrompt() override
|
||||
{
|
||||
connection_error_prompt_count++;
|
||||
}
|
||||
|
||||
bool opened = false;
|
||||
int ota_notify_count = 0;
|
||||
int connection_error_prompt_count = 0;
|
||||
int start_listening_count = 0;
|
||||
int stop_listening_count = 0;
|
||||
int abort_speaking_count = 0;
|
||||
ConversationInterruptSource abort_source =
|
||||
ConversationInterruptSource::kWakeWordDetected;
|
||||
int goodbye_count = 0;
|
||||
int accept_call_count = 0;
|
||||
int hangup_call_count = 0;
|
||||
uint8_t button_click_count = 0;
|
||||
LocalPrompt local_prompt = LocalPrompt::kError;
|
||||
bool local_started = false;
|
||||
int local_state_count = 0;
|
||||
};
|
||||
|
||||
class FakePlatform final : public IDevicePlatform {
|
||||
public:
|
||||
bool Initialize() override { return true; }
|
||||
const DeviceIdentity& Identity() const override { return identity; }
|
||||
void SetLed(LedPattern value) override { led = value; }
|
||||
void ShowTemporaryLedAlert(uint32_t duration_ms) override
|
||||
{
|
||||
alert_duration_ms = duration_ms;
|
||||
}
|
||||
void ReportError(uint32_t value) override { error_id = value; }
|
||||
void Reboot() override { rebooted = true; }
|
||||
void EnterSoftOff(uint64_t) override { soft_off = true; }
|
||||
SoftOffWakeReason ConsumeSoftOffWakeReason() override
|
||||
{
|
||||
return SoftOffWakeReason::kNone;
|
||||
}
|
||||
|
||||
LedPattern led = LedPattern::kOff;
|
||||
uint32_t error_id = 0;
|
||||
uint32_t alert_duration_ms = 0;
|
||||
bool rebooted = false;
|
||||
bool soft_off = false;
|
||||
DeviceIdentity identity{};
|
||||
};
|
||||
|
||||
class FakeProvisioning final : public IProvisioningService {
|
||||
public:
|
||||
void Start() override { started = true; }
|
||||
void Stop() override { started = false; }
|
||||
bool started = false;
|
||||
};
|
||||
|
||||
class FakeFriend final : public IFriendService {
|
||||
public:
|
||||
void Start() override { started = true; }
|
||||
void Stop() override { started = false; }
|
||||
bool started = false;
|
||||
};
|
||||
|
||||
class FakeOta final : public IOtaService {
|
||||
public:
|
||||
void StartUpgrade(uint32_t value) override { request_id = value; }
|
||||
uint32_t request_id = 0;
|
||||
};
|
||||
|
||||
class FakeAlert final : public IAlertRinger {
|
||||
public:
|
||||
void Start(AlertKind value) override
|
||||
{
|
||||
started = true;
|
||||
kind = value;
|
||||
}
|
||||
void Stop() override { started = false; }
|
||||
bool started = false;
|
||||
AlertKind kind = AlertKind::kReminder;
|
||||
};
|
||||
|
||||
class FakePower final : public IPowerService {
|
||||
public:
|
||||
void EnterSoftOff() override { soft_off = true; }
|
||||
bool soft_off = false;
|
||||
};
|
||||
|
||||
void TestRoutesEffectsWithoutProductLogic()
|
||||
{
|
||||
FakeAudio audio;
|
||||
FakeConnectivity connectivity;
|
||||
FakeRealtime realtime;
|
||||
FakePlatform platform;
|
||||
FakeFriend friend_service;
|
||||
FakeProvisioning provisioning;
|
||||
FakeOta ota;
|
||||
FakeAlert alert;
|
||||
FakePower power;
|
||||
EffectRouter router(
|
||||
audio, connectivity, realtime, platform, friend_service,
|
||||
provisioning, ota, alert, power);
|
||||
RuntimeState state;
|
||||
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kStartConnectivity), state);
|
||||
router.Handle(AppEffect::Simple(AppEffectType::kStartAudio), state);
|
||||
router.Handle(AppEffect::Audio(AudioPolicy::kBargeInDuplex), state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kSetAudioVolume, 72), state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(
|
||||
AppEffectType::kSetWakeWordEnabled, 0),
|
||||
state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(
|
||||
AppEffectType::kSetBargeInEnabled, 1),
|
||||
state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kPausePlayback), state);
|
||||
assert(audio.playback_paused);
|
||||
|
||||
// Provisioning must free the WakeNet instance before NimBLE starts: the BT
|
||||
// controller needs the internal RAM and the wake word is unused there.
|
||||
assert(!audio.wake_word_released);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kEnterProvisioning), state);
|
||||
assert(audio.wake_word_released);
|
||||
assert(provisioning.started);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kResumePlayback), state);
|
||||
assert(!audio.playback_paused);
|
||||
router.Handle(AppEffect::Led(LedPattern::kSpeaking), state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(
|
||||
AppEffectType::kShowTemporaryLedAlert, 5000),
|
||||
state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kStartUpgrade, 99), state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kStartFriendMode), state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kSendAbortSpeaking), state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kSendGoodbye), state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kSendAcceptCall), state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kSendHangupCall), state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(AppEffectType::kSendButtonClick, 4), state);
|
||||
router.Handle(
|
||||
AppEffect::LocalPlaybackState(
|
||||
AppEffectType::kSendLocalPlaybackStarted,
|
||||
LocalPrompt::kSnoreLight),
|
||||
state);
|
||||
router.Handle(
|
||||
AppEffect::LocalPlaybackState(
|
||||
AppEffectType::kSendLocalPlaybackDone,
|
||||
LocalPrompt::kSnoreLight),
|
||||
state);
|
||||
router.Handle(
|
||||
AppEffect::RemotePlayback(
|
||||
AppEffectType::kBeginRemotePlayback,
|
||||
77,
|
||||
PlaybackPriority::kConversation),
|
||||
state);
|
||||
router.Handle(
|
||||
AppEffect::RemotePlayback(
|
||||
AppEffectType::kEndPlaybackInput, 77),
|
||||
state);
|
||||
router.Handle(
|
||||
AppEffect::Prompt(
|
||||
LocalPrompt::kBoot, PlaybackPriority::kSystem, 4),
|
||||
state);
|
||||
router.Handle(
|
||||
AppEffect::DetachedPrompt(LocalPrompt::kWakeResponse),
|
||||
state);
|
||||
router.Handle(
|
||||
AppEffect::Simple(
|
||||
AppEffectType::kRequestConnectionErrorPrompt),
|
||||
state);
|
||||
|
||||
assert(connectivity.started);
|
||||
assert(audio.started);
|
||||
assert(audio.policy == AudioPolicy::kBargeInDuplex);
|
||||
assert(audio.volume == 72);
|
||||
assert(!audio.wake_word_enabled);
|
||||
assert(audio.barge_in_enabled);
|
||||
assert(platform.led == LedPattern::kSpeaking);
|
||||
assert(platform.alert_duration_ms == 5000);
|
||||
assert(ota.request_id == 99);
|
||||
assert(friend_service.started);
|
||||
assert(realtime.abort_speaking_count == 1);
|
||||
assert(realtime.abort_source ==
|
||||
ConversationInterruptSource::kUserInitiated);
|
||||
assert(realtime.goodbye_count == 1);
|
||||
assert(realtime.accept_call_count == 1);
|
||||
assert(realtime.hangup_call_count == 1);
|
||||
assert(realtime.button_click_count == 4);
|
||||
assert(realtime.local_state_count == 2);
|
||||
assert(realtime.local_prompt == LocalPrompt::kSnoreLight);
|
||||
assert(!realtime.local_started);
|
||||
assert(audio.remote_session == 77);
|
||||
assert(audio.ended_session == 77);
|
||||
assert(audio.selector == 4);
|
||||
assert(audio.prompt == LocalPrompt::kBoot);
|
||||
assert(audio.priority == PlaybackPriority::kSystem);
|
||||
// A detached prompt must reach the dedicated engine entry point, not the
|
||||
// lifecycle-publishing one, and must not disturb the normal prompt slot.
|
||||
assert(audio.detached_count == 1);
|
||||
assert(audio.detached_prompt == LocalPrompt::kWakeResponse);
|
||||
assert(audio.detached_priority == PlaybackPriority::kLocalPrompt);
|
||||
assert(audio.prompt == LocalPrompt::kBoot);
|
||||
assert(realtime.connection_error_prompt_count == 1);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestRoutesEffectsWithoutProductLogic();
|
||||
std::cout << "effect router tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
63
host_tests/friend_types_test.cc
Normal file
63
host_tests/friend_types_test.cc
Normal file
@@ -0,0 +1,63 @@
|
||||
#include "friend/friend_types.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
void TestMacNormalizationAndAdvertisingName()
|
||||
{
|
||||
char base[kFriendMacCapacity]{};
|
||||
// Uppercase input on purpose: parsing is case-insensitive, but the output
|
||||
// must be lower case — it is the peer's device_id and the server matches
|
||||
// device ids case-sensitively (same contract as the activation-loop fix).
|
||||
assert(NormalizeBleMacToBaseMac(
|
||||
"3C:DC:75:FA:73:0A", base, sizeof(base)));
|
||||
assert(std::strcmp(base, "3c:dc:75:fa:73:08") == 0);
|
||||
assert(!NormalizeBleMacToBaseMac(
|
||||
"invalid", base, sizeof(base)));
|
||||
|
||||
char name[kFriendAdvertisingNameCapacity]{};
|
||||
assert(BuildFriendAdvertisingName(
|
||||
"3C:DC:75:FA:73:08", name, sizeof(name)));
|
||||
assert(std::strcmp(name, "BorlaF-7308") == 0);
|
||||
}
|
||||
|
||||
void TestCandidateThresholdsAndStaleness()
|
||||
{
|
||||
FriendCandidateSelector selector;
|
||||
FriendPeer peer;
|
||||
constexpr uint64_t kNow = 10000;
|
||||
|
||||
assert(!selector.Observe(
|
||||
"3C:DC:75:FA:73:0A", "Other-7308", -40, kNow));
|
||||
assert(selector.Observe(
|
||||
"3C:DC:75:FA:73:0A", "BorlaF-7308", -70, kNow));
|
||||
assert(!selector.Select(kNow, &peer));
|
||||
assert(selector.Observe(
|
||||
"3C:DC:75:FA:73:0A", "BorlaF-7308", -72, kNow + 100));
|
||||
assert(selector.Select(kNow + 100, &peer));
|
||||
assert(std::strcmp(peer.mac.data(), "3c:dc:75:fa:73:08") == 0);
|
||||
assert(std::strcmp(peer.name.data(), "BorlaF-7308") == 0);
|
||||
|
||||
selector.Reset();
|
||||
assert(selector.Observe(
|
||||
"3C:DC:75:FA:73:0C", "BorlaF-730A", -55, kNow));
|
||||
assert(selector.Select(kNow, &peer));
|
||||
assert(!selector.Select(
|
||||
kNow + FriendCandidateSelector::kStaleAfterMs + 1,
|
||||
&peer));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestMacNormalizationAndAdvertisingName();
|
||||
TestCandidateThresholdsAndStaleness();
|
||||
std::cout << "friend type tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
37
host_tests/ml307_at_parser_test.cc
Normal file
37
host_tests/ml307_at_parser_test.cc
Normal file
@@ -0,0 +1,37 @@
|
||||
#include "connectivity/ml307_at_parser.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
using namespace borla;
|
||||
|
||||
int main()
|
||||
{
|
||||
CellularRegistration registration;
|
||||
assert(ParseMl307Registration(
|
||||
"\r\n+CEREG: 2,1,\"1234\"\r\nOK\r\n",
|
||||
®istration));
|
||||
assert(registration.mode == 2);
|
||||
assert(registration.IsRegistered());
|
||||
assert(ParseMl307Registration(
|
||||
"\r\n+CEREG: 5\r\nOK\r\n", ®istration));
|
||||
assert(registration.IsRegistered());
|
||||
assert(!ParseMl307Registration("ERROR", ®istration));
|
||||
|
||||
int8_t csq = 0;
|
||||
assert(ParseMl307SignalQuality("+CSQ: 18,99\r\n", &csq));
|
||||
assert(csq == 18);
|
||||
assert(ParseMl307SignalQuality("+CSQ: 99,99\r\n", &csq));
|
||||
assert(csq == -1);
|
||||
assert(!ParseMl307SignalQuality("+CSQ: 55,0\r\n", &csq));
|
||||
|
||||
char value[32]{};
|
||||
assert(CopyMl307ResponseLine(
|
||||
"\r\n460011234567890\r\nOK\r\n", "", value, sizeof(value)));
|
||||
assert(std::strcmp(value, "460011234567890") == 0);
|
||||
|
||||
std::cout << "ML307 AT parser tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
144
host_tests/ota_endpoint_test.cc
Normal file
144
host_tests/ota_endpoint_test.cc
Normal file
@@ -0,0 +1,144 @@
|
||||
#include "ota/ota_endpoint.h"
|
||||
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
void TestRolloverEndpointDetection()
|
||||
{
|
||||
// Build/staging defaults must be recognised so a device that once talked
|
||||
// to a retired host recovers instead of retrying it forever.
|
||||
assert(IsRolloverEndpoint("wss://borlaws.lkall.com/v1/ws"));
|
||||
assert(IsRolloverEndpoint("wss://borla-dev.lkall.com/v1/ws"));
|
||||
assert(IsRolloverEndpoint("wss://borla-moe.lkall.com/v1/ws"));
|
||||
assert(IsRolloverEndpoint("https://borla-ota.lkall.com/xiaozhi/ota/"));
|
||||
assert(IsRolloverEndpoint("ws://192.168.1.121:30001/v1/ws"));
|
||||
assert(IsRolloverEndpoint("ws://117.50.44.247:8000/v1/ws"));
|
||||
|
||||
// A genuinely provisioned production endpoint must be preserved.
|
||||
assert(!IsRolloverEndpoint("wss://prod.example.com/v1/ws"));
|
||||
// .lkall.com alone is not enough — only the listed staging hosts roll over.
|
||||
assert(!IsRolloverEndpoint("wss://customer.lkall.com/v1/ws"));
|
||||
assert(!IsRolloverEndpoint(""));
|
||||
assert(!IsRolloverEndpoint(nullptr));
|
||||
}
|
||||
|
||||
void TestWildcardHostSubstitution()
|
||||
{
|
||||
std::array<char, 128> output{};
|
||||
assert(SubstituteWildcardHost(
|
||||
"ws://0.0.0.0:8000/v1/ws",
|
||||
"https://ota.example.com/xiaozhi/ota/",
|
||||
output.data(),
|
||||
output.size()));
|
||||
assert(std::strcmp(
|
||||
output.data(), "ws://ota.example.com:8000/v1/ws") == 0);
|
||||
|
||||
// Host with an explicit port on the OTA side: only the host is taken.
|
||||
output.fill('\0');
|
||||
assert(SubstituteWildcardHost(
|
||||
"ws://0.0.0.0:8000/v1/ws",
|
||||
"http://10.1.2.3:9000/ota/",
|
||||
output.data(),
|
||||
output.size()));
|
||||
assert(std::strcmp(output.data(), "ws://10.1.2.3:8000/v1/ws") == 0);
|
||||
|
||||
// No wildcard in the candidate → nothing to substitute.
|
||||
assert(!SubstituteWildcardHost(
|
||||
"wss://real.example.com/v1/ws",
|
||||
"https://ota.example.com/ota/",
|
||||
output.data(),
|
||||
output.size()));
|
||||
|
||||
// Unusable OTA URLs must not produce a half-rewritten endpoint.
|
||||
assert(!SubstituteWildcardHost(
|
||||
"ws://0.0.0.0:8000/v1/ws", "ota.example.com",
|
||||
output.data(), output.size()));
|
||||
assert(!SubstituteWildcardHost(
|
||||
"ws://0.0.0.0:8000/v1/ws", "https://0.0.0.0/ota/",
|
||||
output.data(), output.size()));
|
||||
assert(!SubstituteWildcardHost(
|
||||
"ws://0.0.0.0:8000/v1/ws", nullptr,
|
||||
output.data(), output.size()));
|
||||
|
||||
// Capacity is respected.
|
||||
std::array<char, 8> tiny{};
|
||||
assert(!SubstituteWildcardHost(
|
||||
"ws://0.0.0.0:8000/v1/ws",
|
||||
"https://ota.example.com/ota/",
|
||||
tiny.data(),
|
||||
tiny.size()));
|
||||
}
|
||||
|
||||
void TestResolveRealtimeUrl()
|
||||
{
|
||||
constexpr const char* kOtaUrl = "https://ota.example.com/xiaozhi/ota/";
|
||||
constexpr const char* kDefault = "wss://borlaws.lkall.com/v1/ws";
|
||||
std::array<char, 128> output{};
|
||||
|
||||
// A real production endpoint passes through untouched.
|
||||
assert(ResolveRealtimeUrl(
|
||||
"wss://prod.example.com/v1/ws", kOtaUrl, kDefault,
|
||||
output.data(), output.size()));
|
||||
assert(std::strcmp(
|
||||
output.data(), "wss://prod.example.com/v1/ws") == 0);
|
||||
|
||||
// A wildcard endpoint is rewritten to the reachable OTA host, and that
|
||||
// result is NOT then treated as a rollover default.
|
||||
output.fill('\0');
|
||||
assert(ResolveRealtimeUrl(
|
||||
"ws://0.0.0.0:8000/v1/ws", kOtaUrl, kDefault,
|
||||
output.data(), output.size()));
|
||||
assert(std::strcmp(
|
||||
output.data(), "ws://ota.example.com:8000/v1/ws") == 0);
|
||||
|
||||
// A retired staging endpoint falls back to the current default.
|
||||
output.fill('\0');
|
||||
assert(ResolveRealtimeUrl(
|
||||
"wss://borla-dev.lkall.com/v1/ws", kOtaUrl, kDefault,
|
||||
output.data(), output.size()));
|
||||
assert(std::strcmp(output.data(), kDefault) == 0);
|
||||
|
||||
// An unresolvable wildcard falls back rather than shipping "0.0.0.0".
|
||||
output.fill('\0');
|
||||
assert(ResolveRealtimeUrl(
|
||||
"ws://0.0.0.0:8000/v1/ws", "not-a-url", kDefault,
|
||||
output.data(), output.size()));
|
||||
assert(std::strcmp(output.data(), kDefault) == 0);
|
||||
|
||||
// Empty/absent candidate falls back.
|
||||
output.fill('\0');
|
||||
assert(ResolveRealtimeUrl(
|
||||
"", kOtaUrl, kDefault, output.data(), output.size()));
|
||||
assert(std::strcmp(output.data(), kDefault) == 0);
|
||||
output.fill('\0');
|
||||
assert(ResolveRealtimeUrl(
|
||||
nullptr, kOtaUrl, kDefault, output.data(), output.size()));
|
||||
assert(std::strcmp(output.data(), kDefault) == 0);
|
||||
|
||||
// No candidate and no default → nothing usable.
|
||||
assert(!ResolveRealtimeUrl(
|
||||
nullptr, kOtaUrl, "", output.data(), output.size()));
|
||||
|
||||
// Too small an output buffer is a failure, not a truncation.
|
||||
std::array<char, 4> tiny{};
|
||||
assert(!ResolveRealtimeUrl(
|
||||
"wss://prod.example.com/v1/ws", kOtaUrl, kDefault,
|
||||
tiny.data(), tiny.size()));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestRolloverEndpointDetection();
|
||||
TestWildcardHostSubstitution();
|
||||
TestResolveRealtimeUrl();
|
||||
std::cout << "ota endpoint tests passed" << std::endl;
|
||||
return 0;
|
||||
}
|
||||
184
host_tests/ota_response_parser_test.cc
Normal file
184
host_tests/ota_response_parser_test.cc
Normal file
@@ -0,0 +1,184 @@
|
||||
#include "ota/ota_response_parser.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
constexpr const char* kSha =
|
||||
"0123456789abcdef0123456789abcdef"
|
||||
"0123456789abcdef0123456789abcdef";
|
||||
|
||||
void TestPolicyParsing()
|
||||
{
|
||||
OtaResponseParser parser;
|
||||
OtaManifest manifest;
|
||||
char json[1024]{};
|
||||
std::snprintf(
|
||||
json,
|
||||
sizeof(json),
|
||||
"{\"firmware\":{\"version\":\"2.1.0\","
|
||||
"\"url\":\"https://cdn.example/fw.bin\","
|
||||
"\"size\":1048576,\"sha256\":\"%s\"},"
|
||||
"\"auto_update\":true,\"force_upgrade\":false}",
|
||||
kSha);
|
||||
assert(parser.Parse(
|
||||
json, std::strlen(json), "2.0.0", false, &manifest) ==
|
||||
OtaParseStatus::kOk);
|
||||
assert(manifest.policy == OtaUpgradePolicy::kAutomatic);
|
||||
assert(manifest.size == 1048576);
|
||||
|
||||
std::snprintf(
|
||||
json,
|
||||
sizeof(json),
|
||||
"{\"firmware\":{\"version\":\"2.2.0\","
|
||||
"\"url\":\"https://cdn.example/fw.bin\","
|
||||
"\"size\":100,\"sha256\":\"%s\"},"
|
||||
"\"auto_update\":false,\"force_upgrade\":true}",
|
||||
kSha);
|
||||
assert(parser.Parse(
|
||||
json, std::strlen(json), "2.0.0", false, &manifest) ==
|
||||
OtaParseStatus::kOk);
|
||||
assert(manifest.policy == OtaUpgradePolicy::kForced);
|
||||
}
|
||||
|
||||
void TestNoUpdateAndStrictValidation()
|
||||
{
|
||||
OtaResponseParser parser;
|
||||
OtaManifest manifest;
|
||||
constexpr char kNone[] = R"({"firmware":null})";
|
||||
assert(parser.Parse(
|
||||
kNone, sizeof(kNone) - 1, "2.0.0", false, &manifest) ==
|
||||
OtaParseStatus::kOk);
|
||||
assert(!manifest.HasUpdate());
|
||||
|
||||
char json[1024]{};
|
||||
std::snprintf(
|
||||
json,
|
||||
sizeof(json),
|
||||
"{\"firmware\":{\"version\":\"2.1.0\","
|
||||
"\"url\":\"http://lan/fw.bin\","
|
||||
"\"size\":100,\"sha256\":\"%s\"}}",
|
||||
kSha);
|
||||
assert(parser.Parse(
|
||||
json, std::strlen(json), "2.0.0", false, &manifest) ==
|
||||
OtaParseStatus::kUnsafeUrl);
|
||||
assert(parser.Parse(
|
||||
json, std::strlen(json), "2.0.0", true, &manifest) ==
|
||||
OtaParseStatus::kOk);
|
||||
|
||||
std::memset(json, 0, sizeof(json));
|
||||
std::snprintf(
|
||||
json,
|
||||
sizeof(json),
|
||||
"{\"firmware\":{\"version\":\"1.9.0\","
|
||||
"\"url\":\"https://cdn/fw.bin\","
|
||||
"\"size\":100,\"sha256\":\"%s\"}}",
|
||||
kSha);
|
||||
assert(parser.Parse(
|
||||
json, std::strlen(json), "2.0.0-dev", false, &manifest) ==
|
||||
OtaParseStatus::kOk);
|
||||
assert(!manifest.HasUpdate());
|
||||
}
|
||||
|
||||
void TestVersionAndDigestHelpers()
|
||||
{
|
||||
assert(OtaResponseParser::CompareVersions("v2.1.0", "2.0.9") > 0);
|
||||
assert(OtaResponseParser::CompareVersions("2.0", "2.0.0") == 0);
|
||||
assert(OtaResponseParser::CompareVersions("1.9.9", "2.0") < 0);
|
||||
uint8_t digest[32]{};
|
||||
assert(OtaResponseParser::DecodeSha256(kSha, digest));
|
||||
assert(digest[0] == 0x01);
|
||||
assert(digest[31] == 0xef);
|
||||
assert(!OtaResponseParser::DecodeSha256("bad", digest));
|
||||
}
|
||||
|
||||
void TestEndpointBlockSurvivesEveryFirmwareOutcome()
|
||||
{
|
||||
OtaResponseParser parser;
|
||||
OtaManifest manifest;
|
||||
OtaEndpointConfig endpoint;
|
||||
char json[1024]{};
|
||||
|
||||
// No firmware block at all — the websocket block must still come through,
|
||||
// this is how a fielded device gets repointed at a new server.
|
||||
const char* endpoint_only =
|
||||
"{\"websocket\":{\"url\":\"wss://a.example/v1/ws\","
|
||||
"\"token\":\"tok-123\"}}";
|
||||
assert(parser.Parse(
|
||||
endpoint_only, std::strlen(endpoint_only), "2.0.0",
|
||||
false, &manifest, &endpoint) == OtaParseStatus::kOk);
|
||||
assert(!manifest.HasUpdate());
|
||||
assert(endpoint.has_url);
|
||||
assert(endpoint.has_token);
|
||||
assert(std::strcmp(
|
||||
endpoint.url.data(),
|
||||
"wss://a.example/v1/ws") == 0);
|
||||
assert(std::strcmp(endpoint.token.data(), "tok-123") == 0);
|
||||
|
||||
// Firmware present but not newer — the "*manifest = {}" reset on that path
|
||||
// must not wipe the endpoint.
|
||||
std::snprintf(
|
||||
json,
|
||||
sizeof(json),
|
||||
"{\"firmware\":{\"version\":\"2.0.0\","
|
||||
"\"url\":\"https://cdn.example/fw.bin\","
|
||||
"\"size\":100,\"sha256\":\"%s\"},"
|
||||
"\"websocket\":{\"url\":\"wss://b.example/v1/ws\"}}",
|
||||
kSha);
|
||||
assert(parser.Parse(
|
||||
json, std::strlen(json), "2.0.0", false, &manifest,
|
||||
&endpoint) == OtaParseStatus::kOk);
|
||||
assert(!manifest.HasUpdate());
|
||||
assert(endpoint.has_url);
|
||||
assert(std::strcmp(
|
||||
endpoint.url.data(),
|
||||
"wss://b.example/v1/ws") == 0);
|
||||
assert(!endpoint.has_token);
|
||||
|
||||
// Firmware newer — endpoint travels alongside the upgrade.
|
||||
std::snprintf(
|
||||
json,
|
||||
sizeof(json),
|
||||
"{\"firmware\":{\"version\":\"2.5.0\","
|
||||
"\"url\":\"https://cdn.example/fw.bin\","
|
||||
"\"size\":100,\"sha256\":\"%s\"},\"auto_update\":true,"
|
||||
"\"websocket\":{\"url\":\"wss://c.example/v1/ws\"}}",
|
||||
kSha);
|
||||
assert(parser.Parse(
|
||||
json, std::strlen(json), "2.0.0", false, &manifest,
|
||||
&endpoint) == OtaParseStatus::kOk);
|
||||
assert(manifest.policy == OtaUpgradePolicy::kAutomatic);
|
||||
assert(std::strcmp(
|
||||
endpoint.url.data(),
|
||||
"wss://c.example/v1/ws") == 0);
|
||||
|
||||
// Absent / malformed websocket block leaves the endpoint unset so the
|
||||
// caller keeps whatever is already stored.
|
||||
const char* no_ws = "{}";
|
||||
assert(parser.Parse(
|
||||
no_ws, std::strlen(no_ws), "2.0.0", false, &manifest,
|
||||
&endpoint) == OtaParseStatus::kOk);
|
||||
assert(!endpoint.HasAny());
|
||||
const char* bad_ws = "{\"websocket\":{\"url\":42}}";
|
||||
assert(parser.Parse(
|
||||
bad_ws, std::strlen(bad_ws), "2.0.0", false, &manifest,
|
||||
&endpoint) == OtaParseStatus::kOk);
|
||||
assert(!endpoint.HasAny());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestPolicyParsing();
|
||||
TestNoUpdateAndStrictValidation();
|
||||
TestVersionAndDigestHelpers();
|
||||
TestEndpointBlockSurvivesEveryFirmwareOutcome();
|
||||
std::cout << "OTA response parser tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
76
host_tests/packed_opus_reader_test.cc
Normal file
76
host_tests/packed_opus_reader_test.cc
Normal file
@@ -0,0 +1,76 @@
|
||||
#include "audio/packed_opus_reader.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
void TestReadsCompletePayload()
|
||||
{
|
||||
const uint8_t packed[] = {
|
||||
0x02, 0x00,
|
||||
0x03, 0x00, 0x11, 0x22, 0x33,
|
||||
0x02, 0x00, 0x44, 0x55,
|
||||
};
|
||||
PackedOpusReader reader(packed, sizeof(packed));
|
||||
assert(reader.valid());
|
||||
assert(reader.frame_count() == 2);
|
||||
|
||||
const uint8_t* frame = nullptr;
|
||||
size_t size = 0;
|
||||
assert(reader.Next(&frame, &size));
|
||||
assert(size == 3);
|
||||
assert(frame[0] == 0x11 && frame[2] == 0x33);
|
||||
assert(reader.Next(&frame, &size));
|
||||
assert(size == 2);
|
||||
assert(frame[0] == 0x44 && frame[1] == 0x55);
|
||||
assert(!reader.Next(&frame, &size));
|
||||
assert(reader.complete());
|
||||
}
|
||||
|
||||
void TestRejectsTruncatedFrame()
|
||||
{
|
||||
const uint8_t packed[] = {
|
||||
0x01, 0x00,
|
||||
0x04, 0x00, 0x11, 0x22,
|
||||
};
|
||||
PackedOpusReader reader(packed, sizeof(packed));
|
||||
const uint8_t* frame = nullptr;
|
||||
size_t size = 0;
|
||||
assert(!reader.Next(&frame, &size));
|
||||
assert(!reader.valid());
|
||||
assert(!reader.complete());
|
||||
}
|
||||
|
||||
void TestRejectsZeroFramesAndTrailingBytes()
|
||||
{
|
||||
const uint8_t empty[] = {0x00, 0x00};
|
||||
PackedOpusReader empty_reader(empty, sizeof(empty));
|
||||
assert(!empty_reader.valid());
|
||||
|
||||
const uint8_t trailing[] = {
|
||||
0x01, 0x00,
|
||||
0x01, 0x00, 0x77,
|
||||
0x99,
|
||||
};
|
||||
PackedOpusReader trailing_reader(trailing, sizeof(trailing));
|
||||
const uint8_t* frame = nullptr;
|
||||
size_t size = 0;
|
||||
assert(trailing_reader.Next(&frame, &size));
|
||||
assert(!trailing_reader.complete());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestReadsCompletePayload();
|
||||
TestRejectsTruncatedFrame();
|
||||
TestRejectsZeroFramesAndTrailingBytes();
|
||||
|
||||
std::cout << "packed Opus reader tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
178
host_tests/playback_controller_test.cc
Normal file
178
host_tests/playback_controller_test.cc
Normal file
@@ -0,0 +1,178 @@
|
||||
#include "audio/playback_controller.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
void TestPendingProducerCannotDrain()
|
||||
{
|
||||
PlaybackController controller;
|
||||
const PlaybackStartResult start = controller.StartSession(
|
||||
PlaybackSource::kLocalPrompt,
|
||||
PlaybackPriority::kSystem,
|
||||
0,
|
||||
100);
|
||||
assert(start.status == PlaybackStartStatus::kStarted);
|
||||
assert(controller.EndInput(start.session_id, 110));
|
||||
assert(controller.TryComplete() == 0);
|
||||
assert(controller.snapshot().active);
|
||||
assert(!controller.snapshot().producer_started);
|
||||
|
||||
assert(controller.QueueFrame(start.session_id, 120));
|
||||
assert(controller.BeginFrame(start.session_id, 121));
|
||||
assert(controller.FinishFrame(start.session_id, true, 180));
|
||||
assert(controller.TryComplete() == start.session_id);
|
||||
assert(!controller.snapshot().active);
|
||||
}
|
||||
|
||||
void TestOldProducerCannotRefillAfterPreemption()
|
||||
{
|
||||
PlaybackController controller;
|
||||
const PlaybackStartResult old_session = controller.StartSession(
|
||||
PlaybackSource::kRemoteTts,
|
||||
PlaybackPriority::kConversation,
|
||||
10,
|
||||
0);
|
||||
assert(controller.QueueFrame(old_session.session_id, 10));
|
||||
|
||||
const PlaybackStartResult replacement = controller.StartSession(
|
||||
PlaybackSource::kLocalPrompt,
|
||||
PlaybackPriority::kSystem,
|
||||
20,
|
||||
20);
|
||||
assert(replacement.status == PlaybackStartStatus::kStarted);
|
||||
assert(replacement.preempted_session_id == old_session.session_id);
|
||||
assert(!controller.QueueFrame(old_session.session_id, 30));
|
||||
assert(controller.QueueFrame(replacement.session_id, 30));
|
||||
assert(controller.metrics().sessions_preempted == 1);
|
||||
}
|
||||
|
||||
void TestStaleDrainCannotCompleteNewSession()
|
||||
{
|
||||
PlaybackController controller;
|
||||
const PlaybackStartResult old_session = controller.StartSession(
|
||||
PlaybackSource::kRemoteTts,
|
||||
PlaybackPriority::kConversation,
|
||||
31,
|
||||
0);
|
||||
assert(controller.QueueFrame(old_session.session_id, 1));
|
||||
|
||||
const PlaybackStartResult current = controller.StartSession(
|
||||
PlaybackSource::kRemoteTts,
|
||||
PlaybackPriority::kConversation,
|
||||
32,
|
||||
2);
|
||||
assert(!controller.EndInput(old_session.session_id, 3));
|
||||
assert(controller.TryComplete() == 0);
|
||||
assert(controller.snapshot().id == current.session_id);
|
||||
assert(controller.snapshot().active);
|
||||
}
|
||||
|
||||
void TestPriorityPreventsLocalRemoteMixing()
|
||||
{
|
||||
PlaybackController controller;
|
||||
const PlaybackStartResult remote = controller.StartSession(
|
||||
PlaybackSource::kRemoteTts,
|
||||
PlaybackPriority::kConversation,
|
||||
41,
|
||||
0);
|
||||
const PlaybackStartResult local = controller.StartSession(
|
||||
PlaybackSource::kLocalPrompt,
|
||||
PlaybackPriority::kSystem,
|
||||
0,
|
||||
1);
|
||||
assert(local.status == PlaybackStartStatus::kStarted);
|
||||
assert(local.preempted_session_id == remote.session_id);
|
||||
|
||||
const PlaybackStartResult rejected = controller.StartSession(
|
||||
PlaybackSource::kRemoteTts,
|
||||
PlaybackPriority::kConversation,
|
||||
42,
|
||||
2);
|
||||
assert(rejected.status ==
|
||||
PlaybackStartStatus::kRejectedLowerPriority);
|
||||
assert(controller.snapshot().id == local.session_id);
|
||||
assert(controller.metrics().lower_priority_rejections == 1);
|
||||
}
|
||||
|
||||
void TestProducerAndStallTimeouts()
|
||||
{
|
||||
PlaybackController controller;
|
||||
PlaybackStartResult start = controller.StartSession(
|
||||
PlaybackSource::kLocalPrompt,
|
||||
PlaybackPriority::kSystem,
|
||||
0,
|
||||
100);
|
||||
PlaybackTimeoutResult timeout =
|
||||
controller.CheckTimeout(2099, 2000, 10000);
|
||||
assert(timeout.reason == PlaybackTimeoutReason::kNone);
|
||||
timeout = controller.CheckTimeout(2100, 2000, 10000);
|
||||
assert(timeout.reason == PlaybackTimeoutReason::kProducerStart);
|
||||
assert(timeout.session_id == start.session_id);
|
||||
|
||||
start = controller.StartSession(
|
||||
PlaybackSource::kRemoteTts,
|
||||
PlaybackPriority::kConversation,
|
||||
52,
|
||||
3000);
|
||||
assert(controller.QueueFrame(start.session_id, 3100));
|
||||
timeout = controller.CheckTimeout(13099, 2000, 10000);
|
||||
assert(timeout.reason == PlaybackTimeoutReason::kNone);
|
||||
timeout = controller.CheckTimeout(13100, 2000, 10000);
|
||||
assert(timeout.reason == PlaybackTimeoutReason::kStalled);
|
||||
assert(timeout.session_id == start.session_id);
|
||||
}
|
||||
|
||||
void TestSessionNamespacesAndIdempotency()
|
||||
{
|
||||
PlaybackController controller;
|
||||
const PlaybackStartResult invalid = controller.StartSession(
|
||||
PlaybackSource::kRemoteTts,
|
||||
PlaybackPriority::kConversation,
|
||||
0x80000000U,
|
||||
0);
|
||||
assert(invalid.status ==
|
||||
PlaybackStartStatus::kRejectedInvalidSessionId);
|
||||
|
||||
const PlaybackStartResult remote = controller.StartSession(
|
||||
PlaybackSource::kRemoteTts,
|
||||
PlaybackPriority::kConversation,
|
||||
7,
|
||||
1);
|
||||
const PlaybackStartResult duplicate = controller.StartSession(
|
||||
PlaybackSource::kRemoteTts,
|
||||
PlaybackPriority::kConversation,
|
||||
7,
|
||||
2);
|
||||
assert(duplicate.status == PlaybackStartStatus::kAlreadyActive);
|
||||
assert(duplicate.session_id == remote.session_id);
|
||||
assert(duplicate.generation == remote.generation);
|
||||
assert(controller.metrics().sessions_started == 1);
|
||||
|
||||
assert(controller.Cancel(remote.session_id) == remote.session_id);
|
||||
const PlaybackStartResult local = controller.StartSession(
|
||||
PlaybackSource::kLocalPrompt,
|
||||
PlaybackPriority::kLocalPrompt,
|
||||
0,
|
||||
3);
|
||||
assert(local.session_id >= 0x80000000U);
|
||||
assert(local.generation != remote.generation);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestPendingProducerCannotDrain();
|
||||
TestOldProducerCannotRefillAfterPreemption();
|
||||
TestStaleDrainCannotCompleteNewSession();
|
||||
TestPriorityPreventsLocalRemoteMixing();
|
||||
TestProducerAndStallTimeouts();
|
||||
TestSessionNamespacesAndIdempotency();
|
||||
|
||||
std::cout << "playback controller tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
626
host_tests/realtime_codec_test.cc
Normal file
626
host_tests/realtime_codec_test.cc
Normal file
@@ -0,0 +1,626 @@
|
||||
#include "protocol/protocol_message_builder.h"
|
||||
#include "protocol/server_message_dispatcher.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include <cJSON.h>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
cJSON* BuildAndParse(
|
||||
bool result,
|
||||
const char* output,
|
||||
size_t output_size)
|
||||
{
|
||||
assert(result);
|
||||
assert(output_size == std::strlen(output));
|
||||
cJSON* root = cJSON_ParseWithLength(output, output_size);
|
||||
assert(cJSON_IsObject(root));
|
||||
return root;
|
||||
}
|
||||
|
||||
const char* StringField(const cJSON* root, const char* name)
|
||||
{
|
||||
const cJSON* field =
|
||||
cJSON_GetObjectItemCaseSensitive(root, name);
|
||||
assert(cJSON_IsString(field));
|
||||
return field->valuestring;
|
||||
}
|
||||
|
||||
ServerCommand ParseCommand(
|
||||
const ServerMessageDispatcher& dispatcher,
|
||||
const char* json,
|
||||
size_t size)
|
||||
{
|
||||
ServerCommand command;
|
||||
assert(dispatcher.ParseInto(json, size, &command));
|
||||
return command;
|
||||
}
|
||||
|
||||
void TestMessageBuilder()
|
||||
{
|
||||
ProtocolMessageBuilder builder;
|
||||
char output[768]{};
|
||||
size_t size = 0;
|
||||
|
||||
cJSON* root = BuildAndParse(
|
||||
builder.BuildHello(
|
||||
3, output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "type"), "hello") == 0);
|
||||
assert(cJSON_GetObjectItem(root, "version")->valueint == 3);
|
||||
const cJSON* audio = cJSON_GetObjectItem(root, "audio_params");
|
||||
assert(cJSON_IsObject(audio));
|
||||
assert(cJSON_GetObjectItem(audio, "sample_rate")->valueint == 16000);
|
||||
assert(cJSON_GetObjectItem(audio, "frame_duration")->valueint == 60);
|
||||
const cJSON* features = cJSON_GetObjectItem(root, "features");
|
||||
assert(cJSON_IsTrue(cJSON_GetObjectItem(features, "local_audio")));
|
||||
assert(cJSON_IsTrue(
|
||||
cJSON_GetObjectItem(features, "play_local_sequence")));
|
||||
assert(cJSON_IsTrue(
|
||||
cJSON_GetObjectItem(features, "barge_in_two_phase")));
|
||||
assert(cJSON_IsTrue(cJSON_GetObjectItem(features, "mcp")));
|
||||
cJSON_Delete(root);
|
||||
|
||||
MemorySnapshot memory;
|
||||
std::strcpy(memory.child_name.data(), "小明");
|
||||
std::strcpy(memory.brain_text.data(), "喜欢星星");
|
||||
memory.interaction_count = 42;
|
||||
root = BuildAndParse(
|
||||
builder.BuildHello(
|
||||
3, &memory, output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
const cJSON* cache =
|
||||
cJSON_GetObjectItem(root, "memory_cache");
|
||||
assert(cJSON_IsObject(cache));
|
||||
assert(std::strcmp(
|
||||
StringField(cache, "child_name"), "小明") == 0);
|
||||
assert(cJSON_GetObjectItem(
|
||||
cache, "interaction_count")->valueint == 42);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildStartListening(
|
||||
"session-a", output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "session_id"), "session-a") == 0);
|
||||
assert(std::strcmp(StringField(root, "type"), "listen") == 0);
|
||||
assert(std::strcmp(StringField(root, "state"), "start") == 0);
|
||||
assert(std::strcmp(StringField(root, "mode"), "auto") == 0);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildStatus(
|
||||
85, 3875, false, "2.0.0", 64,
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "type"), "status") == 0);
|
||||
assert(cJSON_GetObjectItem(root, "battery")->valueint == 85);
|
||||
assert(cJSON_GetObjectItem(
|
||||
root, "battery_voltage_mv")->valueint == 3875);
|
||||
assert(cJSON_GetObjectItem(root, "volume")->valueint == 64);
|
||||
cJSON_Delete(root);
|
||||
|
||||
// A negative volume means "unknown": the field is omitted rather than
|
||||
// reported as 0, which the parent app would render as muted.
|
||||
root = BuildAndParse(
|
||||
builder.BuildStatus(
|
||||
85, 3875, true, "2.0.0", -1,
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(cJSON_GetObjectItem(root, "volume") == nullptr);
|
||||
assert(cJSON_IsTrue(cJSON_GetObjectItem(root, "charging")));
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildButton(
|
||||
3, output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "type"), "button") == 0);
|
||||
assert(cJSON_GetObjectItem(root, "count")->valueint == 3);
|
||||
cJSON_Delete(root);
|
||||
assert(!builder.BuildButton(
|
||||
2, output, sizeof(output), &size));
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildLocalPlaybackState(
|
||||
"snore_light", true,
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "type"), "play_local") == 0);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "state"), "start") == 0);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "group"), "snore_light") == 0);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildGoodbye(
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "type"), "goodbye") == 0);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildLocalPlaybackState(
|
||||
"snore_light", false,
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "state"), "done") == 0);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildAlarmFired(
|
||||
42, 1744123460,
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "type"), "alarm_fired") == 0);
|
||||
assert(cJSON_GetObjectItem(root, "id")->valueint == 42);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildCallAction(
|
||||
"accept", "call-42",
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "type"), "call") == 0);
|
||||
assert(std::strcmp(StringField(root, "state"), "accept") == 0);
|
||||
assert(std::strcmp(StringField(root, "call_id"), "call-42") == 0);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildFriendAdd(
|
||||
"3c:dc:75:fb:12:fc",
|
||||
"黑马",
|
||||
"3c:dc:75:fa:73:08",
|
||||
"BorlaF-7308",
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "type"), "friend_add") == 0);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "remote_name"),
|
||||
"BorlaF-7308") == 0);
|
||||
cJSON_Delete(root);
|
||||
|
||||
// A mandatory upgrade announcement must omit "optional" entirely: the
|
||||
// server contract treats an absent field as "device is going to install".
|
||||
root = BuildAndParse(
|
||||
builder.BuildOtaNotify(
|
||||
"当前有最新版本,即将开始升级!请耐心等候",
|
||||
false,
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "type"), "ota_notify") == 0);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "text"),
|
||||
"当前有最新版本,即将开始升级!请耐心等候") == 0);
|
||||
assert(cJSON_GetObjectItem(root, "optional") == nullptr);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildOtaNotify(
|
||||
"当前设备有最新版本,是否进行升级?",
|
||||
true,
|
||||
output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(cJSON_IsTrue(cJSON_GetObjectItem(root, "optional")));
|
||||
cJSON_Delete(root);
|
||||
|
||||
assert(!builder.BuildOtaNotify(
|
||||
"", false, output, sizeof(output), &size));
|
||||
assert(!builder.BuildOtaNotify(
|
||||
nullptr, false, output, sizeof(output), &size));
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildStopListening(
|
||||
"session-a", output, sizeof(output), &size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "state"), "stop") == 0);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildAbort(
|
||||
"session-a",
|
||||
ConversationInterruptSource::kUserInitiated,
|
||||
nullptr,
|
||||
output,
|
||||
sizeof(output),
|
||||
&size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "type"), "abort") == 0);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "reason"),
|
||||
"user_initiated") == 0);
|
||||
// Nothing was playing, so the field must be absent rather than empty.
|
||||
assert(cJSON_GetObjectItem(root, "playback_text") == nullptr);
|
||||
cJSON_Delete(root);
|
||||
|
||||
root = BuildAndParse(
|
||||
builder.BuildAbort(
|
||||
"session-a",
|
||||
ConversationInterruptSource::kWakeWordDetected,
|
||||
"在很久很久以前",
|
||||
output,
|
||||
sizeof(output),
|
||||
&size),
|
||||
output,
|
||||
size);
|
||||
assert(std::strcmp(StringField(root, "type"), "abort") == 0);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "reason"),
|
||||
"wake_word_detected") == 0);
|
||||
assert(std::strcmp(
|
||||
StringField(root, "playback_text"),
|
||||
"在很久很久以前") == 0);
|
||||
cJSON_Delete(root);
|
||||
|
||||
// A sentence longer than the 100-byte cap must be cut on a character
|
||||
// boundary. The previous firmware cut on a byte boundary here and the
|
||||
// server closed the connection with 1007 (invalid frame payload data),
|
||||
// which showed up as stories stopping halfway through.
|
||||
{
|
||||
std::string long_sentence;
|
||||
while (long_sentence.size() < 300) {
|
||||
long_sentence += "小"; // 3 bytes each
|
||||
}
|
||||
root = BuildAndParse(
|
||||
builder.BuildAbort(
|
||||
"session-a",
|
||||
ConversationInterruptSource::kUserInitiated,
|
||||
long_sentence.c_str(),
|
||||
output,
|
||||
sizeof(output),
|
||||
&size),
|
||||
output,
|
||||
size);
|
||||
const char* truncated =
|
||||
StringField(root, "playback_text");
|
||||
const size_t truncated_size = std::strlen(truncated);
|
||||
assert(truncated_size <=
|
||||
ProtocolMessageBuilder::kPlaybackTextBytes);
|
||||
// 100 / 3 = 33 whole characters, so 99 bytes — never 100, which would
|
||||
// mean the last character was split.
|
||||
assert(truncated_size % 3 == 0);
|
||||
assert(std::strncmp(
|
||||
truncated,
|
||||
long_sentence.c_str(),
|
||||
truncated_size) == 0);
|
||||
cJSON_Delete(root);
|
||||
}
|
||||
|
||||
char too_small[4]{};
|
||||
assert(!builder.BuildPing(
|
||||
too_small, sizeof(too_small), &size));
|
||||
}
|
||||
|
||||
void TestServerHello()
|
||||
{
|
||||
ServerMessageDispatcher dispatcher;
|
||||
constexpr char kValid[] =
|
||||
R"({"type":"hello","session_id":"session-a",)"
|
||||
R"("transport":"websocket","audio_params":{)"
|
||||
R"("sample_rate":24000,"channels":1,)"
|
||||
R"("format":"opus","frame_duration":60},)"
|
||||
R"("server_time":1744123456,"tz_offset":28800,)"
|
||||
R"("button_map":{"3":"network_switch","4":"nothing"},)"
|
||||
R"("connection_error_prompts":{)"
|
||||
R"("server_unreachable":"error","no_network":"no_network"},)"
|
||||
R"("device_name":"黑马"})";
|
||||
ServerCommand command = ParseCommand(
|
||||
dispatcher, kValid, sizeof(kValid) - 1);
|
||||
assert(command.type == ServerCommandType::kHello);
|
||||
assert(std::strcmp(command.session_id.data(), "session-a") == 0);
|
||||
assert(command.output_sample_rate == 24000);
|
||||
assert(command.frame_duration_ms == 60);
|
||||
assert(command.server_time_seconds == 1744123456);
|
||||
assert(command.timezone_offset_seconds == 28800);
|
||||
assert(std::strcmp(command.device_name.data(), "黑马") == 0);
|
||||
assert(command.triple_click_action ==
|
||||
ButtonAction::kNetworkSwitch);
|
||||
assert(command.quadruple_click_action ==
|
||||
ButtonAction::kNothing);
|
||||
assert(command.has_server_unreachable_prompt);
|
||||
assert(command.server_unreachable_prompt == LocalPrompt::kError);
|
||||
assert(command.has_no_network_prompt);
|
||||
assert(command.no_network_prompt == LocalPrompt::kNoNetwork);
|
||||
|
||||
ServerCommand in_place;
|
||||
assert(dispatcher.ParseInto(
|
||||
kValid, sizeof(kValid) - 1, &in_place));
|
||||
assert(in_place.type == ServerCommandType::kHello);
|
||||
assert(std::strcmp(
|
||||
in_place.session_id.data(), "session-a") == 0);
|
||||
assert(!dispatcher.ParseInto(
|
||||
kValid, sizeof(kValid) - 1, nullptr));
|
||||
|
||||
constexpr char kWrongRate[] =
|
||||
R"({"type":"hello","session_id":"x",)"
|
||||
R"("audio_params":{"sample_rate":16000,)"
|
||||
R"("frame_duration":60}})";
|
||||
command = ParseCommand(
|
||||
dispatcher, kWrongRate, sizeof(kWrongRate) - 1);
|
||||
assert(command.type == ServerCommandType::kInvalid);
|
||||
|
||||
constexpr char kWrongVersion[] =
|
||||
R"({"type":"hello","version":2,"session_id":"x",)"
|
||||
R"("audio_params":{"sample_rate":24000,)"
|
||||
R"("frame_duration":60}})";
|
||||
command = ParseCommand(
|
||||
dispatcher, kWrongVersion, sizeof(kWrongVersion) - 1);
|
||||
assert(command.type == ServerCommandType::kInvalid);
|
||||
}
|
||||
|
||||
void TestServerCommands()
|
||||
{
|
||||
ServerMessageDispatcher dispatcher;
|
||||
auto parse = [&dispatcher](const char* json) {
|
||||
return ParseCommand(dispatcher, json, std::strlen(json));
|
||||
};
|
||||
|
||||
assert(parse("{").type == ServerCommandType::kInvalid);
|
||||
assert(parse("{}").type == ServerCommandType::kInvalid);
|
||||
assert(parse(R"({"type":"ping"})").type ==
|
||||
ServerCommandType::kPing);
|
||||
assert(parse(R"({"type":"pong"})").type ==
|
||||
ServerCommandType::kPong);
|
||||
assert(parse(R"({"type":"tts","state":"start"})").type ==
|
||||
ServerCommandType::kTtsStart);
|
||||
assert(parse(R"({"type":"tts","state":"stop"})").type ==
|
||||
ServerCommandType::kTtsStop);
|
||||
ServerCommand command = parse(
|
||||
R"({"type":"stt","text":"今天天气怎么样"})");
|
||||
assert(command.type == ServerCommandType::kSttText);
|
||||
assert(std::strcmp(
|
||||
command.conversation_text.data(),
|
||||
"今天天气怎么样") == 0);
|
||||
ServerCommand reused;
|
||||
assert(dispatcher.ParseInto(
|
||||
R"({"type":"stt","text":"复用缓冲区"})",
|
||||
std::strlen(R"({"type":"stt","text":"复用缓冲区"})"),
|
||||
&reused));
|
||||
assert(reused.type == ServerCommandType::kSttText);
|
||||
assert(dispatcher.ParseInto(
|
||||
R"({"type":"ping"})",
|
||||
std::strlen(R"({"type":"ping"})"),
|
||||
&reused));
|
||||
assert(reused.type == ServerCommandType::kPing);
|
||||
assert(reused.conversation_text[0] == '\0');
|
||||
command = parse(
|
||||
R"({"type":"tts","state":"sentence_start",)"
|
||||
R"("text":"今天是晴天"})");
|
||||
assert(command.type == ServerCommandType::kTtsSentenceStart);
|
||||
assert(std::strcmp(
|
||||
command.conversation_text.data(),
|
||||
"今天是晴天") == 0);
|
||||
assert(parse(R"({"type":"stt","text":""})").type ==
|
||||
ServerCommandType::kInvalid);
|
||||
|
||||
// llm/emotion is advisory. It must be recognised (not counted as an
|
||||
// unsupported message) and must survive a missing/blank emotion field.
|
||||
command = parse(R"({"type":"llm","emotion":"happy"})");
|
||||
assert(command.type == ServerCommandType::kLlmEmotion);
|
||||
assert(std::strcmp(
|
||||
command.conversation_text.data(), "happy") == 0);
|
||||
command = parse(R"({"type":"llm"})");
|
||||
assert(command.type == ServerCommandType::kLlmEmotion);
|
||||
assert(command.conversation_text[0] == '\0');
|
||||
|
||||
assert(parse(
|
||||
R"({"type":"tts","state":"sentence_start"})")
|
||||
.type == ServerCommandType::kInvalid);
|
||||
assert(parse(R"({"type":"future"})").type ==
|
||||
ServerCommandType::kUnsupported);
|
||||
assert(parse(R"({"type":"wifi_config"})").type ==
|
||||
ServerCommandType::kEnterProvisioning);
|
||||
|
||||
command =
|
||||
parse(R"({"type":"control","action":"volume","volume":135})");
|
||||
assert(command.type == ServerCommandType::kControl);
|
||||
assert(command.control_action == RemoteControlAction::kVolume);
|
||||
assert(command.control_value == 100);
|
||||
command = parse(
|
||||
R"({"type":"control","action":"wake_word","enabled":false})");
|
||||
assert(command.type == ServerCommandType::kControl);
|
||||
assert(command.control_action == RemoteControlAction::kWakeWord);
|
||||
assert(command.control_value == 0);
|
||||
command = parse(
|
||||
R"({"type":"control","action":"barge_in","enabled":true})");
|
||||
assert(command.type == ServerCommandType::kControl);
|
||||
assert(command.control_action == RemoteControlAction::kBargeIn);
|
||||
assert(command.control_value == 1);
|
||||
command = parse(
|
||||
R"({"type":"control","action":"light_sleep",)"
|
||||
R"("mode":"idle_sleep"})");
|
||||
assert(command.type == ServerCommandType::kControl);
|
||||
assert(command.control_action == RemoteControlAction::kLightSleep);
|
||||
command = parse(
|
||||
R"({"type":"control","action":"led","state":"alert",)"
|
||||
R"("color":"red","duration_ms":70000})");
|
||||
assert(command.type == ServerCommandType::kControl);
|
||||
assert(command.control_action == RemoteControlAction::kLedAlert);
|
||||
assert(command.control_value == 60000);
|
||||
assert(parse(
|
||||
R"({"type":"control","action":"future"})")
|
||||
.type == ServerCommandType::kUnsupported);
|
||||
assert(parse(
|
||||
R"({"type":"control","action":"barge_in","enabled":1})")
|
||||
.type == ServerCommandType::kInvalid);
|
||||
|
||||
command = parse(R"({"type":"barge_in","state":"candidate"})");
|
||||
assert(command.type == ServerCommandType::kBargeIn);
|
||||
assert(command.barge_in_state == BargeInDecisionState::kCandidate);
|
||||
command = parse(R"({"type":"barge_in","state":"rejected"})");
|
||||
assert(command.barge_in_state == BargeInDecisionState::kRejected);
|
||||
command = parse(R"({"type":"barge_in","state":"confirmed"})");
|
||||
assert(command.barge_in_state == BargeInDecisionState::kConfirmed);
|
||||
assert(parse(R"({"type":"barge_in","state":"unknown"})").type ==
|
||||
ServerCommandType::kInvalid);
|
||||
|
||||
command =
|
||||
parse(R"({"type":"play_local","group":"alarm_wake",)"
|
||||
R"("index":2})");
|
||||
assert(command.type == ServerCommandType::kPlayLocal);
|
||||
assert(command.local_prompt == LocalPrompt::kAlarmWake);
|
||||
assert(command.playback_priority == PlaybackPriority::kAlarm);
|
||||
assert(command.prompt_index == 2);
|
||||
assert(!command.soft_off_after_playback);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"play_local","group":"snore_light"})");
|
||||
assert(command.type == ServerCommandType::kPlayLocal);
|
||||
assert(command.local_prompt == LocalPrompt::kSnoreLight);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"play_local","group":"shutdown"})");
|
||||
assert(command.type == ServerCommandType::kPlayLocal);
|
||||
assert(command.soft_off_after_playback);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"play_local","group":"shutdown",)"
|
||||
R"("block_reconnect":false})");
|
||||
assert(command.type == ServerCommandType::kPlayLocal);
|
||||
assert(!command.soft_off_after_playback);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"play_local","group":"shutdown",)"
|
||||
R"("post_action":"enter_soft_off"})");
|
||||
assert(command.soft_off_after_playback);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"play_local","group":"not-installed"})");
|
||||
assert(command.type == ServerCommandType::kUnsupported);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"play_local_sequence","sequence":[)"
|
||||
R"({"group":"activation_prompt"},)"
|
||||
R"({"group":"digit_4","index":0},)"
|
||||
R"({"group":"unknown"}]})");
|
||||
assert(command.type == ServerCommandType::kPlayLocalSequence);
|
||||
assert(command.local_sequence.count == 2);
|
||||
assert(command.local_sequence.items[0].prompt ==
|
||||
LocalPrompt::kActivationDevice);
|
||||
assert(command.local_sequence.items[1].prompt ==
|
||||
LocalPrompt::kDigit4);
|
||||
assert(command.local_sequence.items[1].selector == 0);
|
||||
assert(parse(
|
||||
R"({"type":"play_local_sequence","sequence":[]})")
|
||||
.type == ServerCommandType::kUnsupported);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"memory_sync","child_name":"小明",)"
|
||||
R"("brain_text":"喜欢星星","interaction_count":43})");
|
||||
assert(command.type == ServerCommandType::kMemorySync);
|
||||
assert(std::strcmp(
|
||||
command.memory.child_name.data(), "小明") == 0);
|
||||
assert(command.memory.interaction_count == 43);
|
||||
assert(parse(
|
||||
R"({"type":"memory_sync","interaction_count":-1})")
|
||||
.type == ServerCommandType::kInvalid);
|
||||
|
||||
command = parse(R"({"type":"error","code":4512})");
|
||||
assert(command.type == ServerCommandType::kError);
|
||||
assert(command.error_id == 4512);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"set_timer","duration":300})");
|
||||
assert(command.type == ServerCommandType::kSetTimer);
|
||||
assert(command.duration_seconds == 300);
|
||||
assert(parse(
|
||||
R"({"type":"set_timer","duration":0})")
|
||||
.type == ServerCommandType::kInvalid);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"cancel_timer","scope":"all"})");
|
||||
assert(command.type == ServerCommandType::kCancelTimer);
|
||||
assert(command.timer_cancel_scope == TimerCancelScope::kAll);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"set_alarm","alarm":{"id":42,)"
|
||||
R"("hour":7,"minute":30,"repeat_mask":62,)"
|
||||
R"("fire_epoch":0,"label":"wake","enabled":true}})");
|
||||
assert(command.type == ServerCommandType::kSetAlarm);
|
||||
assert(command.alarm.id == 42);
|
||||
assert(command.alarm.repeat_mask == 62);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"sync_alarms","alarms":[)"
|
||||
R"({"id":9,"hour":20,"minute":30,)"
|
||||
R"("repeat_mask":127,"enabled":true}]})");
|
||||
assert(command.type == ServerCommandType::kSyncAlarms);
|
||||
assert(command.alarms.count == 1);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"delete_alarm","id":-203000})");
|
||||
assert(command.type == ServerCommandType::kDeleteAlarm);
|
||||
assert(command.alarm_id == kBuiltInFirstDayAlarmId);
|
||||
assert(parse(
|
||||
R"({"type":"delete_alarm","id":-1})")
|
||||
.type == ServerCommandType::kInvalid);
|
||||
assert(parse(
|
||||
R"({"type":"delete_alarm","id":0})")
|
||||
.type == ServerCommandType::kInvalid);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"alarm_config","set_tone_index":2,)"
|
||||
R"("wake_tone_index":1})");
|
||||
assert(command.type == ServerCommandType::kAlarmConfig);
|
||||
assert(command.wake_tone_index == 1);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"call","state":"invite",)"
|
||||
R"("call_id":"call-42","caller_name":"白马"})");
|
||||
assert(command.type == ServerCommandType::kCall);
|
||||
assert(command.call_state == CallSignalState::kInvite);
|
||||
assert(std::strcmp(command.call_id.data(), "call-42") == 0);
|
||||
assert(std::strcmp(command.peer_name.data(), "白马") == 0);
|
||||
|
||||
command = parse(
|
||||
R"({"type":"call","state":"connected",)"
|
||||
R"("call_id":"call-42","peer_name":"白马"})");
|
||||
assert(command.type == ServerCommandType::kCall);
|
||||
assert(command.call_state == CallSignalState::kConnected);
|
||||
|
||||
assert(parse(
|
||||
R"({"type":"call","state":"invite"})")
|
||||
.type == ServerCommandType::kInvalid);
|
||||
assert(parse(
|
||||
R"({"type":"call","state":"unknown",)"
|
||||
R"("call_id":"call-42"})")
|
||||
.type == ServerCommandType::kInvalid);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestMessageBuilder();
|
||||
TestServerHello();
|
||||
TestServerCommands();
|
||||
std::cout << "realtime codec tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
90
host_tests/schedule_test.cc
Normal file
90
host_tests/schedule_test.cc
Normal file
@@ -0,0 +1,90 @@
|
||||
#include "schedule/alarm_schedule.h"
|
||||
#include "schedule/reminder_schedule.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
AlarmEntry Alarm(
|
||||
int32_t id,
|
||||
uint8_t hour,
|
||||
uint8_t minute,
|
||||
uint8_t repeat_mask,
|
||||
int64_t fire_epoch = 0)
|
||||
{
|
||||
AlarmEntry alarm;
|
||||
alarm.id = id;
|
||||
alarm.hour = hour;
|
||||
alarm.minute = minute;
|
||||
alarm.repeat_mask = repeat_mask;
|
||||
alarm.fire_epoch = fire_epoch;
|
||||
std::strcpy(alarm.label.data(), "test");
|
||||
return alarm;
|
||||
}
|
||||
|
||||
void TestReminderOrderingAndCancellation()
|
||||
{
|
||||
ReminderSchedule schedule;
|
||||
assert(schedule.Add(3000));
|
||||
assert(schedule.Add(1000));
|
||||
assert(schedule.Add(2000));
|
||||
assert(schedule.next_deadline_ms() == 1000);
|
||||
assert(schedule.CancelNext());
|
||||
assert(schedule.next_deadline_ms() == 2000);
|
||||
assert(schedule.PopDue(2500) == 1);
|
||||
assert(schedule.count() == 1);
|
||||
schedule.CancelAll();
|
||||
assert(schedule.count() == 0);
|
||||
}
|
||||
|
||||
void TestAlarmMatchingAndBuiltIn()
|
||||
{
|
||||
AlarmSchedule schedule;
|
||||
assert(schedule.EnsureBuiltInFirstDay(false));
|
||||
assert(schedule.list().count == 1);
|
||||
assert(schedule.Upsert(Alarm(42, 7, 30, 1U << 2)));
|
||||
|
||||
CalendarMinute calendar{
|
||||
.week_day = 2,
|
||||
.hour = 7,
|
||||
.minute = 30,
|
||||
};
|
||||
AlarmFireBatch due = schedule.TakeDue(calendar, 1744126200);
|
||||
assert(due.count == 1);
|
||||
assert(due.ids[0] == 42);
|
||||
assert(due.play_audio);
|
||||
assert(schedule.TakeDue(calendar, 1744126220).count == 0);
|
||||
|
||||
calendar.week_day = 3;
|
||||
calendar.hour = 20;
|
||||
due = schedule.TakeDue(calendar, 1744173000);
|
||||
assert(due.built_in_first_day);
|
||||
assert(!due.play_audio);
|
||||
assert(schedule.first_day_consumed());
|
||||
}
|
||||
|
||||
void TestOneShotWindowAndValidation()
|
||||
{
|
||||
const AlarmEntry one_shot = Alarm(7, 8, 15, 0, 2000);
|
||||
CalendarMinute calendar{.hour = 8, .minute = 15};
|
||||
assert(AlarmSchedule::Matches(one_shot, calendar, 2059));
|
||||
assert(!AlarmSchedule::Matches(one_shot, calendar, 2060));
|
||||
AlarmEntry invalid = one_shot;
|
||||
invalid.hour = 24;
|
||||
assert(!AlarmSchedule::Validate(invalid));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestReminderOrderingAndCancellation();
|
||||
TestAlarmMatchingAndBuiltIn();
|
||||
TestOneShotWindowAndValidation();
|
||||
std::cout << "schedule tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
219
host_tests/sensor_pipeline_test.cc
Normal file
219
host_tests/sensor_pipeline_test.cc
Normal file
@@ -0,0 +1,219 @@
|
||||
#include "sensor/battery_estimator.h"
|
||||
#include "sensor/imu_processor.h"
|
||||
#include "sensor/sensor_message_codec.h"
|
||||
#include "sensor/touch_channel.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using borla::GravityAction;
|
||||
using borla::BatteryEstimator;
|
||||
using borla::ImuBatch;
|
||||
using borla::ImuProcessor;
|
||||
using borla::ImuSample;
|
||||
using borla::SensorMessageCodec;
|
||||
using borla::TouchAction;
|
||||
using borla::TouchChannel;
|
||||
using borla::TouchEvent;
|
||||
using borla::TouchTransition;
|
||||
using borla::TouchZone;
|
||||
|
||||
void TestTouchTransitionsArePaired()
|
||||
{
|
||||
TouchChannel channel;
|
||||
for (uint32_t value :
|
||||
{1000U, 1010U, 990U, 1005U, 995U, 1000U, 1002U, 998U}) {
|
||||
channel.AddCalibrationSample(value);
|
||||
}
|
||||
assert(channel.FinishCalibration());
|
||||
assert(channel.threshold() >= 1290.0F);
|
||||
|
||||
TouchTransition transition{};
|
||||
bool down = false;
|
||||
uint64_t down_at_ms = 0;
|
||||
for (uint64_t now_ms = 0; now_ms <= 400; now_ms += 50) {
|
||||
if (channel.Process(1800, now_ms, &transition)) {
|
||||
down = true;
|
||||
down_at_ms = now_ms;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert(down);
|
||||
assert(transition.action == TouchAction::kDown);
|
||||
assert(transition.timestamp_ms == down_at_ms);
|
||||
assert(down_at_ms <= 400);
|
||||
assert(channel.pressed());
|
||||
|
||||
assert(channel.Process(1000, down_at_ms + 500, &transition));
|
||||
assert(transition.action == TouchAction::kUp);
|
||||
assert(transition.duration_ms == 500);
|
||||
assert(!channel.pressed());
|
||||
}
|
||||
|
||||
void TestImuBatchAndStillness()
|
||||
{
|
||||
ImuProcessor processor;
|
||||
size_t full_batches = 0;
|
||||
size_t partial_batches = 0;
|
||||
for (uint64_t i = 0; i < 50; ++i) {
|
||||
const auto output = processor.Process(
|
||||
ImuSample{0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F},
|
||||
i * 20);
|
||||
if (output.has_batch) {
|
||||
if (output.batch.count == 5) {
|
||||
full_batches++;
|
||||
} else {
|
||||
partial_batches++;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert(processor.still());
|
||||
assert(full_batches == 9);
|
||||
assert(partial_batches == 1);
|
||||
|
||||
const auto wake = processor.Process(
|
||||
ImuSample{0.0F, 0.0F, 1.5F, 0.0F, 0.0F, 0.0F},
|
||||
1000);
|
||||
assert(!processor.still());
|
||||
assert(!wake.has_batch);
|
||||
for (uint64_t i = 1; i <= 4; ++i) {
|
||||
const auto output = processor.Process(
|
||||
ImuSample{0.0F, 0.0F, 1.5F, 0.0F, 0.0F, 0.0F},
|
||||
1000 + i * 20);
|
||||
if (i < 4) {
|
||||
assert(!output.has_batch);
|
||||
} else {
|
||||
assert(output.has_batch);
|
||||
assert(output.batch.count == 5);
|
||||
assert(output.batch.sample_rate_hz == 50);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TestGravityStateMachine()
|
||||
{
|
||||
ImuProcessor processor;
|
||||
processor.Process(ImuSample{0.0F, 0.0F, 0.1F}, 1000);
|
||||
processor.Process(ImuSample{0.0F, 0.0F, 0.1F}, 1020);
|
||||
processor.Process(ImuSample{0.0F, 0.0F, 0.1F}, 1040);
|
||||
const auto freefall =
|
||||
processor.Process(ImuSample{0.0F, 0.0F, 0.1F}, 1060);
|
||||
assert(freefall.has_gravity_event);
|
||||
assert(
|
||||
freefall.gravity_event.action == GravityAction::kFreefall);
|
||||
assert(freefall.gravity_event.duration_ms == 60);
|
||||
|
||||
const auto dropped =
|
||||
processor.Process(ImuSample{0.0F, 0.0F, 5.0F}, 1080);
|
||||
assert(dropped.has_gravity_event);
|
||||
assert(dropped.gravity_event.action == GravityAction::kDropped);
|
||||
assert(std::fabs(dropped.gravity_event.peak_g - 5.0F) < 0.001F);
|
||||
|
||||
ImuProcessor impact_processor;
|
||||
const auto impact = impact_processor.Process(
|
||||
ImuSample{0.0F, 0.0F, 7.2F}, 3000);
|
||||
assert(impact.has_gravity_event);
|
||||
assert(
|
||||
impact.gravity_event.action ==
|
||||
GravityAction::kSevereImpact);
|
||||
}
|
||||
|
||||
void TestProtocolMessages()
|
||||
{
|
||||
char buffer[768]{};
|
||||
size_t size = 0;
|
||||
const TouchEvent touch{
|
||||
.zone = TouchZone::kBelly,
|
||||
.action = TouchAction::kUp,
|
||||
.timestamp_ms = 123456,
|
||||
.duration_ms = 800,
|
||||
};
|
||||
assert(SensorMessageCodec::BuildTouch(
|
||||
touch, buffer, sizeof(buffer), &size));
|
||||
assert(std::strstr(buffer, "\"event\":\"touch\"") != nullptr);
|
||||
assert(std::strstr(buffer, "\"touch_zone\":\"touch_5\"") != nullptr);
|
||||
assert(std::strstr(buffer, "\"duration_ms\":800") != nullptr);
|
||||
|
||||
ImuBatch batch{};
|
||||
batch.sequence = 42;
|
||||
batch.timestamp_ms_base = 9000;
|
||||
batch.count = 5;
|
||||
for (size_t i = 0; i < batch.count; ++i) {
|
||||
batch.samples[i] = ImuSample{
|
||||
0.1F * static_cast<float>(i),
|
||||
-0.2F,
|
||||
1.0F,
|
||||
2.0F,
|
||||
3.0F,
|
||||
4.0F,
|
||||
};
|
||||
}
|
||||
assert(SensorMessageCodec::BuildImu(
|
||||
batch, buffer, sizeof(buffer), &size));
|
||||
assert(std::strstr(buffer, "\"event\":\"imu\"") != nullptr);
|
||||
assert(std::strstr(buffer, "\"seq\":42") != nullptr);
|
||||
assert(std::strstr(buffer, "\"hz\":50") != nullptr);
|
||||
assert(!SensorMessageCodec::BuildImu(
|
||||
batch, buffer, 32, &size));
|
||||
|
||||
const borla::GravityEvent gravity{
|
||||
.action = GravityAction::kFreefall,
|
||||
.sequence = 12,
|
||||
.timestamp_ms = 123500,
|
||||
.duration_ms = 60,
|
||||
.magnitude_g = 0.22F,
|
||||
.peak_g = 0.22F,
|
||||
};
|
||||
assert(SensorMessageCodec::BuildGravity(
|
||||
gravity, buffer, sizeof(buffer), &size));
|
||||
assert(std::strstr(buffer, "\"seq\":12") != nullptr);
|
||||
assert(
|
||||
std::strstr(
|
||||
buffer,
|
||||
"\"gravity_action\":\"freefall\"") != nullptr);
|
||||
assert(std::strstr(buffer, "\"gravity_zone\":\"body\"") != nullptr);
|
||||
}
|
||||
|
||||
void TestBatteryEstimator()
|
||||
{
|
||||
assert(!BatteryEstimator::IsPlausibleVoltage(0));
|
||||
assert(!BatteryEstimator::IsPlausibleVoltage(39));
|
||||
assert(!BatteryEstimator::IsPlausibleVoltage(2499));
|
||||
assert(BatteryEstimator::IsPlausibleVoltage(2500));
|
||||
assert(BatteryEstimator::IsPlausibleVoltage(3700));
|
||||
assert(BatteryEstimator::IsPlausibleVoltage(4500));
|
||||
assert(!BatteryEstimator::IsPlausibleVoltage(4501));
|
||||
|
||||
assert(BatteryEstimator::VoltageToPercent(4090) == 100);
|
||||
assert(BatteryEstimator::VoltageToPercent(3000) == 0);
|
||||
assert(BatteryEstimator::VoltageToPercent(3570) == 20);
|
||||
assert(BatteryEstimator::VoltageToPercent(3520) == 15);
|
||||
|
||||
BatteryEstimator estimator;
|
||||
estimator.Update(3700);
|
||||
assert(estimator.initialized());
|
||||
assert(!estimator.charging());
|
||||
estimator.Update(3715);
|
||||
estimator.Update(3730);
|
||||
assert(estimator.charging());
|
||||
estimator.Update(3700);
|
||||
estimator.Update(3670);
|
||||
assert(!estimator.charging());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestTouchTransitionsArePaired();
|
||||
TestImuBatchAndStillness();
|
||||
TestGravityStateMachine();
|
||||
TestProtocolMessages();
|
||||
TestBatteryEstimator();
|
||||
std::cout << "sensor_pipeline_test passed\n";
|
||||
return 0;
|
||||
}
|
||||
1017
host_tests/state_reducer_test.cc
Normal file
1017
host_tests/state_reducer_test.cc
Normal file
File diff suppressed because it is too large
Load Diff
59
host_tests/task_stack_budget_test.cc
Normal file
59
host_tests/task_stack_budget_test.cc
Normal file
@@ -0,0 +1,59 @@
|
||||
#include "core/task_stack_budget.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace borla::task_stack_budget;
|
||||
|
||||
// Regression floors. Floors below must always be <= the budgets in
|
||||
// core/task_stack_budget.h; they exist to stop an accidental edit from
|
||||
// silently shrinking a stack below the last field-validated size.
|
||||
//
|
||||
// Connectivity-class budgets were re-derived from device high-water marks
|
||||
// taken after a full TLS + OTA + BLE provisioning cycle, because every
|
||||
// byte of those stacks is .bss and therefore comes off the front of the
|
||||
// main internal heap — the pool BLE provisioning exhausts when it re-inits
|
||||
// the WiFi driver next to the BT controller. Measured peak usage / floor
|
||||
// connectivity2 2492 / 5120 dual_network2 3136 / 4096
|
||||
// friend_service2 960 / 3072 alarm2 1172 / 3072
|
||||
// websocket2 5964 / 10240 (TLS handshake headroom)
|
||||
// capture2 ~6.3 KB measured / 10 KB budget (internal RAM)
|
||||
//
|
||||
// kCaptureEncoderBytes is NOT lowered with them: the 24 KB trim tripped
|
||||
// the stack canary inside silk_NSQ_del_dec_c (the opus_encode() chain
|
||||
// alone walked 24,240 bytes), so the floor stays at the last
|
||||
// field-validated 32 KB. That stack is PSRAM; headroom there is free.
|
||||
static_assert(kPlaybackBytes >= 36 * 1024);
|
||||
static_assert(kCaptureBytes >= 10 * 1024);
|
||||
static_assert(kConnectivityManagerBytes >= 5 * 1024);
|
||||
static_assert(kDualNetworkBytes >= 4 * 1024);
|
||||
static_assert(kWebsocketTransportBytes >= 10 * 1024);
|
||||
static_assert(kFriendServiceBytes >= 3 * 1024);
|
||||
static_assert(kAlarmServiceBytes >= 3 * 1024);
|
||||
static_assert(kRuntimeDiagnosticsBytes >= 8 * 1024);
|
||||
static_assert(kLocalPromptProducerBytes >= 6 * 1024);
|
||||
static_assert(kCaptureEncoderBytes >= 32 * 1024);
|
||||
|
||||
// The real-time ordering is the point, not the absolute numbers: the two
|
||||
// deadline-bound loops must outrank the codec, and capture must outrank
|
||||
// playback because it is the one that cannot be late without corrupting
|
||||
// the AEC's alignment.
|
||||
using namespace borla::task_priority;
|
||||
static_assert(kCaptureLoop > kPlaybackLoop);
|
||||
static_assert(kPlaybackLoop > kAudioCodec);
|
||||
|
||||
assert(kPlaybackBytes % 1024 == 0);
|
||||
assert(kCaptureBytes % 1024 == 0);
|
||||
assert(kConnectivityManagerBytes % 1024 == 0);
|
||||
assert(kDualNetworkBytes % 1024 == 0);
|
||||
assert(kWebsocketTransportBytes % 1024 == 0);
|
||||
assert(kFriendServiceBytes % 1024 == 0);
|
||||
assert(kAlarmServiceBytes % 1024 == 0);
|
||||
assert(kRuntimeDiagnosticsBytes % 1024 == 0);
|
||||
assert(kLocalPromptProducerBytes % 1024 == 0);
|
||||
|
||||
std::cout << "task stack budgets passed\n";
|
||||
return 0;
|
||||
}
|
||||
107
host_tests/trace_context_test.cc
Normal file
107
host_tests/trace_context_test.cc
Normal file
@@ -0,0 +1,107 @@
|
||||
#include "diagnostics/trace_context.h"
|
||||
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
void TestFormatIdShape()
|
||||
{
|
||||
std::array<char, TraceContext::kIdCapacity> output{};
|
||||
const size_t size = TraceContext::FormatId(
|
||||
"turn", "AA-BB-CC-DD-EE-FF", 123456,
|
||||
output.data(), output.size());
|
||||
assert(std::strcmp(
|
||||
output.data(), "turn-AA-BB-CC-DD-EE-FF-123456") == 0);
|
||||
assert(size == std::strlen(output.data()));
|
||||
}
|
||||
|
||||
void TestFormatIdDefaultsAndTruncation()
|
||||
{
|
||||
std::array<char, TraceContext::kIdCapacity> output{};
|
||||
|
||||
// Missing inputs must still produce a greppable id, never an empty one.
|
||||
TraceContext::FormatId(
|
||||
nullptr, nullptr, 7, output.data(), output.size());
|
||||
assert(std::strcmp(output.data(), "dev-dev-7") == 0);
|
||||
TraceContext::FormatId("", "", 7, output.data(), output.size());
|
||||
assert(std::strcmp(output.data(), "dev-dev-7") == 0);
|
||||
|
||||
// A short buffer truncates and stays NUL-terminated, and the reported
|
||||
// length never points past the buffer.
|
||||
std::array<char, 8> tiny{};
|
||||
const size_t size = TraceContext::FormatId(
|
||||
"turn", "AA-BB-CC", 999999, tiny.data(), tiny.size());
|
||||
assert(tiny[tiny.size() - 1] == '\0');
|
||||
assert(size == std::strlen(tiny.data()));
|
||||
assert(size < tiny.size());
|
||||
|
||||
// Zero capacity must not write anything.
|
||||
assert(TraceContext::FormatId(
|
||||
"turn", "AA", 1, output.data(), 0) == 0);
|
||||
assert(TraceContext::FormatId(
|
||||
"turn", "AA", 1, nullptr, 16) == 0);
|
||||
}
|
||||
|
||||
void TestScopeLifecycle()
|
||||
{
|
||||
// Before anything is set, ids read as "-" rather than null.
|
||||
assert(TraceContext::TraceId() != nullptr);
|
||||
assert(TraceContext::SessionId() != nullptr);
|
||||
assert(TraceContext::RequestId() != nullptr);
|
||||
|
||||
TraceContext::Initialize("3C:DC:75:FB:12:FC");
|
||||
|
||||
// Colons are folded so ids stay safe inside "field=value" log grammar.
|
||||
TraceContext::RefreshTrace("ws");
|
||||
assert(std::strstr(TraceContext::TraceId(), "3C-DC-75-FB-12-FC") !=
|
||||
nullptr);
|
||||
assert(std::strchr(TraceContext::TraceId(), ':') == nullptr);
|
||||
assert(std::strncmp(TraceContext::TraceId(), "ws-", 3) == 0);
|
||||
|
||||
// The server owns the session scope; the device adopts it verbatim.
|
||||
TraceContext::SetSession("srv-session-42");
|
||||
assert(std::strcmp(
|
||||
TraceContext::SessionId(), "srv-session-42") == 0);
|
||||
TraceContext::SetSession("");
|
||||
assert(std::strcmp(TraceContext::SessionId(), "-") == 0);
|
||||
TraceContext::SetSession(nullptr);
|
||||
assert(std::strcmp(TraceContext::SessionId(), "-") == 0);
|
||||
|
||||
// ...but the device proposes one per connect, so the handshake never sends
|
||||
// the unset "-" (which the server would adopt verbatim) nor the previous
|
||||
// connection's id.
|
||||
const char* proposed = TraceContext::RefreshSession();
|
||||
assert(std::strncmp(proposed, "s-", 2) == 0);
|
||||
assert(std::strcmp(proposed, "-") != 0);
|
||||
assert(std::strcmp(proposed, TraceContext::SessionId()) == 0);
|
||||
assert(std::strstr(proposed, "3C-DC-75-FB-12-FC") != nullptr);
|
||||
// A server-supplied id still wins over the proposal.
|
||||
TraceContext::SetSession("srv-session-7");
|
||||
assert(std::strcmp(
|
||||
TraceContext::SessionId(), "srv-session-7") == 0);
|
||||
|
||||
// Each HTTP call gets a fresh request id, returned for the header.
|
||||
const char* first = TraceContext::NewRequestId();
|
||||
assert(std::strncmp(first, "req-", 4) == 0);
|
||||
assert(std::strcmp(first, TraceContext::RequestId()) == 0);
|
||||
|
||||
// A trace id pushed down from the server replaces the generated one.
|
||||
TraceContext::SetTrace("srv-trace-7");
|
||||
assert(std::strcmp(TraceContext::TraceId(), "srv-trace-7") == 0);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestFormatIdShape();
|
||||
TestFormatIdDefaultsAndTruncation();
|
||||
TestScopeLifecycle();
|
||||
std::cout << "trace context tests passed" << std::endl;
|
||||
return 0;
|
||||
}
|
||||
54
host_tests/voice_activity_detector_test.cc
Normal file
54
host_tests/voice_activity_detector_test.cc
Normal file
@@ -0,0 +1,54 @@
|
||||
#include "audio/voice_activity_detector.h"
|
||||
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
void TestHysteresis()
|
||||
{
|
||||
VoiceActivityDetector detector(
|
||||
VoiceActivityConfig{500, 2, 3});
|
||||
std::array<int16_t, 960> loud{};
|
||||
std::array<int16_t, 960> quiet{};
|
||||
loud.fill(1000);
|
||||
|
||||
assert(detector.Process(loud.data(), loud.size()) ==
|
||||
VoiceActivityResult::kSilence);
|
||||
assert(detector.Process(loud.data(), loud.size()) ==
|
||||
VoiceActivityResult::kSpeechStarted);
|
||||
assert(detector.speech_active());
|
||||
assert(detector.Process(quiet.data(), quiet.size()) ==
|
||||
VoiceActivityResult::kSpeech);
|
||||
assert(detector.Process(quiet.data(), quiet.size()) ==
|
||||
VoiceActivityResult::kSpeech);
|
||||
assert(detector.Process(quiet.data(), quiet.size()) ==
|
||||
VoiceActivityResult::kSpeechEnded);
|
||||
assert(!detector.speech_active());
|
||||
}
|
||||
|
||||
void TestNoiseDoesNotStartSpeech()
|
||||
{
|
||||
VoiceActivityDetector detector(
|
||||
VoiceActivityConfig{500, 2, 3});
|
||||
std::array<int16_t, 960> noise{};
|
||||
noise.fill(300);
|
||||
for (int index = 0; index < 20; ++index) {
|
||||
assert(detector.Process(noise.data(), noise.size()) ==
|
||||
VoiceActivityResult::kSilence);
|
||||
}
|
||||
assert(detector.LastRms() == 300);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestHysteresis();
|
||||
TestNoiseDoesNotStartSpeech();
|
||||
std::cout << "voice activity detector tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
61
host_tests/websocket_uri_test.cc
Normal file
61
host_tests/websocket_uri_test.cc
Normal file
@@ -0,0 +1,61 @@
|
||||
#include "protocol/websocket_uri.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace borla;
|
||||
|
||||
void TestDefaultsAndExplicitPort()
|
||||
{
|
||||
WebsocketUri uri;
|
||||
assert(ParseWebsocketUri("wss://example.com/v1/ws", &uri));
|
||||
assert(uri.secure);
|
||||
assert(uri.port == 443);
|
||||
assert(std::strcmp(uri.host.data(), "example.com") == 0);
|
||||
assert(std::strcmp(uri.path.data(), "/v1/ws") == 0);
|
||||
|
||||
assert(ParseWebsocketUri("ws://10.0.0.2:8000", &uri));
|
||||
assert(!uri.secure);
|
||||
assert(uri.port == 8000);
|
||||
assert(std::strcmp(uri.host.data(), "10.0.0.2") == 0);
|
||||
assert(std::strcmp(uri.path.data(), "/") == 0);
|
||||
}
|
||||
|
||||
void TestIpv6()
|
||||
{
|
||||
WebsocketUri uri;
|
||||
assert(ParseWebsocketUri(
|
||||
"wss://[2001:db8::1]:9443/socket", &uri));
|
||||
assert(uri.secure);
|
||||
assert(uri.port == 9443);
|
||||
assert(std::strcmp(uri.host.data(), "2001:db8::1") == 0);
|
||||
assert(std::strcmp(uri.path.data(), "/socket") == 0);
|
||||
}
|
||||
|
||||
void TestRejectsMalformedUris()
|
||||
{
|
||||
WebsocketUri uri;
|
||||
assert(!ParseWebsocketUri(nullptr, &uri));
|
||||
assert(!ParseWebsocketUri("", &uri));
|
||||
assert(!ParseWebsocketUri("http://example.com", &uri));
|
||||
assert(!ParseWebsocketUri("wss://", &uri));
|
||||
assert(!ParseWebsocketUri("wss://host:0/ws", &uri));
|
||||
assert(!ParseWebsocketUri("wss://host:65536/ws", &uri));
|
||||
assert(!ParseWebsocketUri("wss://host:abc/ws", &uri));
|
||||
assert(!ParseWebsocketUri("wss://[2001:db8::1/ws", &uri));
|
||||
assert(!ParseWebsocketUri("wss://a:b:c/ws", &uri));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
TestDefaultsAndExplicitPort();
|
||||
TestIpv6();
|
||||
TestRejectsMalformedUris();
|
||||
std::cout << "websocket URI tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user