diff options
| author | Christoph Berg <myon@debian.org> | 2026-09-26 23:24:03 +0200 |
|---|---|---|
| committer | Christoph Berg <myon@debian.org> | 2026-09-26 23:24:03 +0200 |
| commit | 059831534c7e884f0a607ed86b582fd00d821731 (patch) | |
| tree | 76bcb67a78f8aa2654fd34c2ad801a62136b0170 /tests/unit/tci | |
| parent | d83a420f0517d7fc47aeb288a6a0cf4891784fcc (diff) | |
New upstream version 3.2.0~rc1+dfsgupstream/3.2.0_rc1+dfsg
Diffstat (limited to 'tests/unit/tci')
| -rw-r--r-- | tests/unit/tci/CMakeLists.txt | 55 | ||||
| -rw-r--r-- | tests/unit/tci/TciSimScript.cpp | 416 | ||||
| -rw-r--r-- | tests/unit/tci/TciSimScript.hpp | 116 | ||||
| -rw-r--r-- | tests/unit/tci/TciSimServer.cpp | 328 | ||||
| -rw-r--r-- | tests/unit/tci/TciSimServer.hpp | 111 | ||||
| -rw-r--r-- | tests/unit/tci/test_tci_protocol.cpp | 110 | ||||
| -rw-r--r-- | tests/unit/tci/test_tci_receive_ownership.cpp | 451 | ||||
| -rw-r--r-- | tests/unit/tci/test_tci_sim_smoke.cpp | 387 | ||||
| -rw-r--r-- | tests/unit/tci/test_tci_stream.cpp | 204 | ||||
| -rw-r--r-- | tests/unit/tci/test_tci_transceiver_characterization.cpp | 912 | ||||
| -rw-r--r-- | tests/unit/tci/test_transceiver_base_period.cpp | 164 |
11 files changed, 3254 insertions, 0 deletions
diff --git a/tests/unit/tci/CMakeLists.txt b/tests/unit/tci/CMakeLists.txt new file mode 100644 index 00000000..abe6fed1 --- /dev/null +++ b/tests/unit/tci/CMakeLists.txt @@ -0,0 +1,55 @@ +add_executable (test_tci_stream + test_tci_stream.cpp +) +target_link_libraries (test_tci_stream Qt5::Test) +add_test (NAME test_tci_stream COMMAND test_tci_stream) + +add_executable (test_tci_protocol + test_tci_protocol.cpp +) +target_link_libraries (test_tci_protocol Qt5::Test) +add_test (NAME test_tci_protocol COMMAND test_tci_protocol) + +add_library (tci_simulator STATIC + TciSimScript.cpp + TciSimScript.hpp + TciSimServer.cpp + TciSimServer.hpp +) +target_include_directories (tci_simulator PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries (tci_simulator PUBLIC Qt5::Core Qt5::Network Qt5::WebSockets) + +add_executable (test_tci_sim_smoke test_tci_sim_smoke.cpp) +target_link_libraries (test_tci_sim_smoke PRIVATE tci_simulator Qt5::Test) +add_test (NAME test_tci_sim_smoke COMMAND test_tci_sim_smoke) +set_tests_properties (test_tci_sim_smoke PROPERTIES TIMEOUT 30) + +add_executable (test_tci_transceiver_characterization + test_tci_transceiver_characterization.cpp +) +target_link_libraries (test_tci_transceiver_characterization PRIVATE + tci_simulator wsjt_qt wsjt_fort_common Qt5::Test) +add_test (NAME test_tci_transceiver_characterization + COMMAND test_tci_transceiver_characterization) +set_tests_properties (test_tci_transceiver_characterization PROPERTIES + COST 32 + TIMEOUT 120) + +add_executable (test_transceiver_base_period test_transceiver_base_period.cpp) +target_include_directories (test_transceiver_base_period PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_transceiver_base_period PRIVATE wsjt_qt Qt5::Test) +add_test (NAME test_transceiver_base_period COMMAND test_transceiver_base_period) + +add_executable (test_tci_receive_ownership + test_tci_receive_ownership.cpp + ${CMAKE_SOURCE_DIR}/FastDecode.cpp) +target_include_directories (test_tci_receive_ownership PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_tci_receive_ownership PRIVATE + tci_simulator wsjt_qt wsjt_fort_common Qt5::Test) +add_test (NAME test_tci_receive_ownership COMMAND test_tci_receive_ownership) +set_tests_properties (test_tci_receive_ownership PROPERTIES + TIMEOUT 120 LABELS "receive-handoff;tci-receive") +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_tci_receive_ownership PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=halt_on_error=1:exitcode=66") +endif () diff --git a/tests/unit/tci/TciSimScript.cpp b/tests/unit/tci/TciSimScript.cpp new file mode 100644 index 00000000..ff8b6400 --- /dev/null +++ b/tests/unit/tci/TciSimScript.cpp @@ -0,0 +1,416 @@ +#include "TciSimScript.hpp" + +#include <utility> + +#include <QEventLoop> + +#include "moc_TciSimScript.cpp" + +TciSimScript::TciSimScript (TciSimServer * server, QObject * parent) + : QObject {parent} + , server_ {server} +{ + poll_timer_.setInterval (5); + delay_timer_.setSingleShot (true); + overall_timer_.setSingleShot (true); + connect (&poll_timer_, &QTimer::timeout, + this, &TciSimScript::poll_step); + connect (&delay_timer_, &QTimer::timeout, + this, &TciSimScript::delayed_step_ready); + connect (&overall_timer_, &QTimer::timeout, + this, &TciSimScript::overall_timeout); + connect (server_, &TciSimServer::client_gone, this, + [this] (int generation) + { + if (generation != close_generation_) return; + close_observed_ = true; + cursor_ = server_->cursor (server_->transcript ().size ()); + }); +} + +TciSimScript& TciSimScript::greet ( + TciSimGreeting greeting_value, int timeout_ms) +{ + steps_.push_back ({StepKind::Greet, {}, {}, qMax (0, timeout_ms), + greeting_value}); + return *this; +} + +TciSimScript& TciSimScript::expect ( + QString verb, ArgsPredicate predicate, int timeout_ms) +{ + append_expectation (StepKind::Expect, std::move (verb), + std::move (predicate), timeout_ms); + return *this; +} + +TciSimScript& TciSimScript::reply (QString text, int delay_ms) +{ + steps_.push_back ({StepKind::Reply, std::move (text), {}, + qMax (0, delay_ms), TciSimGreeting::Minimal}); + return *this; +} + +TciSimScript& TciSimScript::push (QString text, int delay_ms) +{ + steps_.push_back ({StepKind::Push, std::move (text), {}, + qMax (0, delay_ms), TciSimGreeting::Minimal}); + return *this; +} + +TciSimScript& TciSimScript::withhold ( + QString verb, ArgsPredicate predicate, int timeout_ms) +{ + append_expectation (StepKind::Withhold, std::move (verb), + std::move (predicate), timeout_ms); + return *this; +} + +TciSimScript& TciSimScript::delay (int delay_ms) +{ + steps_.push_back ({StepKind::Delay, {}, {}, qMax (0, delay_ms), + TciSimGreeting::Minimal}); + return *this; +} + +TciSimScript& TciSimScript::close_normally (QString reason) +{ + steps_.push_back ({StepKind::CloseNormally, std::move (reason), {}, 2000, + TciSimGreeting::Minimal}); + return *this; +} + +TciSimScript& TciSimScript::reconnect (int timeout_ms) +{ + steps_.push_back ({StepKind::Reconnect, {}, {}, qMax (0, timeout_ms), + TciSimGreeting::Minimal}); + return *this; +} + +void TciSimScript::start (int overall_timeout_ms) +{ + if (running_) return; + + running_ = true; + succeeded_ = false; + current_step_ = 0; + reconnect_after_generation_ = server_->connection_generation (); + active_connection_generation_ = server_->client_connected () + ? server_->connection_generation () : 0; + last_consumed_generation_ = 0; + delayed_step_generation_ = 0; + close_generation_ = 0; + close_observed_ = false; + has_consumed_expectation_ = false; + close_requested_ = false; + cursor_ = server_->cursor (); + last_error_.clear (); + overall_timer_.start (qMax (1, overall_timeout_ms)); + QTimer::singleShot (0, this, &TciSimScript::execute_step); +} + +bool TciSimScript::run (int overall_timeout_ms) +{ + QEventLoop loop; + connect (this, &TciSimScript::finished, &loop, &QEventLoop::quit); + start (overall_timeout_ms); + if (running_) loop.exec (); + return succeeded_; +} + +void TciSimScript::stop () +{ + if (running_) fail (QStringLiteral ("script stopped")); +} + +bool TciSimScript::running () const +{ + return running_; +} + +bool TciSimScript::succeeded () const +{ + return succeeded_; +} + +int TciSimScript::failed_step () const +{ + return succeeded_ ? -1 : current_step_ + 1; +} + +QString TciSimScript::last_error () const +{ + return last_error_; +} + +QStringList TciSimScript::greeting_messages (TciSimGreeting greeting) +{ + switch (greeting) + { + case TciSimGreeting::Thetis: + return { + QStringLiteral ("protocol:Thetis,1.6"), + QStringLiteral ("device:HermesLite"), + QStringLiteral ("trx_count:1"), + QStringLiteral ("channels_count:2"), + QStringLiteral ("vfo:0,0,14074000"), + QStringLiteral ("vfo:0,1,14075000"), + QStringLiteral ("modulation:0,digu"), + QStringLiteral ("split_enable:0,false"), + QStringLiteral ("trx:0,false"), + QStringLiteral ("start"), + QStringLiteral ("ready"), + }; + case TciSimGreeting::Minimal: + return { + QStringLiteral ("protocol:TCI,1.6"), + QStringLiteral ("start"), + QStringLiteral ("ready"), + }; + } + return {}; +} + +void TciSimScript::execute_step () +{ + if (!running_) return; + if (current_step_ >= static_cast<int> (steps_.size ())) + { + finish (true); + return; + } + + auto const& step = steps_.at (current_step_); + switch (step.kind) + { + case StepKind::Greet: + if (!server_->client_connected ()) + { + start_polling (step.timeout_ms); + return; + } + active_connection_generation_ = server_->connection_generation (); + last_consumed_generation_ = 0; + has_consumed_expectation_ = false; + for (auto const& message : greeting_messages (step.greeting)) + { + server_->send_text (message); + } + complete_step (); + return; + case StepKind::Expect: + case StepKind::Withhold: + if (current_expectation_satisfied ()) + { + complete_step (); + return; + } + start_polling (step.timeout_ms); + return; + case StepKind::Reply: + if (!has_consumed_expectation_ + || last_consumed_generation_ != active_connection_generation_) + { + fail (QStringLiteral ( + "reply requires an expectation consumed on the active connection")); + return; + } + delayed_step_generation_ = last_consumed_generation_; + if (step.timeout_ms > 0) + { + delay_timer_.start (step.timeout_ms); + } + else + { + delayed_step_ready (); + } + return; + case StepKind::Push: + case StepKind::Delay: + delayed_step_generation_ = active_connection_generation_; + if (step.timeout_ms > 0) + { + delay_timer_.start (step.timeout_ms); + } + else + { + delayed_step_ready (); + } + return; + case StepKind::CloseNormally: + if (!close_requested_) + { + if (!server_->client_connected ()) + { + fail (QStringLiteral ("cannot close without a connected client")); + return; + } + close_generation_ = server_->connection_generation (); + reconnect_after_generation_ = close_generation_; + close_observed_ = false; + close_requested_ = true; + server_->close_client (step.text); + start_polling (step.timeout_ms); + } + return; + case StepKind::Reconnect: + if (server_->client_connected () + && server_->connection_generation () > reconnect_after_generation_) + { + active_connection_generation_ = server_->connection_generation (); + last_consumed_generation_ = 0; + has_consumed_expectation_ = false; + complete_step (); + return; + } + start_polling (step.timeout_ms); + return; + } +} + +void TciSimScript::poll_step () +{ + if (!running_) return; + auto const& step = steps_.at (current_step_); + bool complete {false}; + if (step.kind == StepKind::Greet) + { + complete = server_->client_connected (); + if (complete) + { + poll_timer_.stop (); + execute_step (); + return; + } + } + else if (step.kind == StepKind::Reconnect) + { + complete = server_->client_connected () + && server_->connection_generation () > reconnect_after_generation_; + } + else if (step.kind == StepKind::CloseNormally) + { + complete = close_observed_; + } + else + { + complete = current_expectation_satisfied (); + } + + if (complete) + { + poll_timer_.stop (); + if (step.kind == StepKind::CloseNormally) + { + close_requested_ = false; + } + else if (step.kind == StepKind::Reconnect) + { + active_connection_generation_ = server_->connection_generation (); + last_consumed_generation_ = 0; + has_consumed_expectation_ = false; + } + complete_step (); + } + else if (step_elapsed_.elapsed () >= step.timeout_ms) + { + fail (QStringLiteral ("%1 timed out after %2 ms") + .arg (step_description (step)).arg (step.timeout_ms)); + } +} + +void TciSimScript::delayed_step_ready () +{ + if (!running_) return; + auto const& step = steps_.at (current_step_); + if (step.kind == StepKind::Reply || step.kind == StepKind::Push) + { + if (server_->client_connected () + && server_->connection_generation () == delayed_step_generation_) + { + server_->send_text (step.text); + } + else if (step.kind == StepKind::Reply) + { + fail (QStringLiteral ("reply target connection is no longer active")); + return; + } + } + complete_step (); +} + +void TciSimScript::overall_timeout () +{ + if (running_) fail (QStringLiteral ("overall script timeout")); +} + +void TciSimScript::append_expectation ( + StepKind kind, QString verb, ArgsPredicate predicate, int timeout_ms) +{ + steps_.push_back ({kind, std::move (verb), std::move (predicate), + qMax (0, timeout_ms), TciSimGreeting::Minimal}); +} + +void TciSimScript::start_polling (int) +{ + step_elapsed_.restart (); + poll_timer_.start (); +} + +void TciSimScript::complete_step () +{ + poll_timer_.stop (); + delay_timer_.stop (); + ++current_step_; + QTimer::singleShot (0, this, &TciSimScript::execute_step); +} + +void TciSimScript::fail (QString reason) +{ + auto const step_number = current_step_ + 1; + last_error_ = QStringLiteral ("step %1: %2\nTranscript:\n%3") + .arg (step_number).arg (reason, server_->transcript_text ()); + finish (false); +} + +void TciSimScript::finish (bool succeeded_value) +{ + poll_timer_.stop (); + delay_timer_.stop (); + overall_timer_.stop (); + running_ = false; + succeeded_ = succeeded_value; + emit finished (succeeded_); +} + +bool TciSimScript::current_expectation_satisfied () +{ + auto const& step = steps_.at (current_step_); + TciSimServer::Message message; + if (!server_->consume (&cursor_, TciSimServer::Direction::ClientToServer, + step.text, &message, step.predicate, + active_connection_generation_)) + { + return false; + } + last_consumed_generation_ = message.connection_generation; + has_consumed_expectation_ = true; + return true; +} + +QString TciSimScript::step_description (Step const& step) const +{ + switch (step.kind) + { + case StepKind::Greet: return QStringLiteral ("waiting to greet a client"); + case StepKind::Expect: return QStringLiteral ("expecting %1").arg (step.text); + case StepKind::Reply: return QStringLiteral ("replying with %1").arg (step.text); + case StepKind::Push: return QStringLiteral ("pushing %1").arg (step.text); + case StepKind::Withhold: + return QStringLiteral ("expecting and withholding %1").arg (step.text); + case StepKind::Delay: return QStringLiteral ("delaying"); + case StepKind::CloseNormally: return QStringLiteral ("closing the client"); + case StepKind::Reconnect: return QStringLiteral ("waiting for reconnection"); + } + return QStringLiteral ("running script step"); +} diff --git a/tests/unit/tci/TciSimScript.hpp b/tests/unit/tci/TciSimScript.hpp new file mode 100644 index 00000000..c8f0a3b1 --- /dev/null +++ b/tests/unit/tci/TciSimScript.hpp @@ -0,0 +1,116 @@ +#ifndef TCI_SIM_SCRIPT_HPP__ +#define TCI_SIM_SCRIPT_HPP__ + +#include <functional> +#include <vector> + +#include <QElapsedTimer> +#include <QObject> +#include <QString> +#include <QStringList> +#include <QTimer> + +#include "TciSimServer.hpp" + +enum class TciSimGreeting +{ + Thetis, + Minimal, +}; + +class TciSimScript final + : public QObject +{ + Q_OBJECT + +public: + using ArgsPredicate = std::function<bool (QStringList const&)>; + + explicit TciSimScript (TciSimServer * server, QObject * parent = nullptr); + + TciSimScript& greet (TciSimGreeting greeting = TciSimGreeting::Thetis, + int timeout_ms = 2000); + TciSimScript& expect (QString verb, ArgsPredicate predicate = {}, + int timeout_ms = 2000); + TciSimScript& reply (QString text, int delay_ms = 0); + TciSimScript& push (QString text, int delay_ms = 0); + TciSimScript& withhold (QString verb, ArgsPredicate predicate = {}, + int timeout_ms = 2000); + TciSimScript& delay (int delay_ms); + TciSimScript& close_normally ( + QString reason = QStringLiteral ("scripted disconnect")); + TciSimScript& reconnect (int timeout_ms = 2000); + + void start (int overall_timeout_ms = 10000); + bool run (int overall_timeout_ms = 10000); + void stop (); + + bool running () const; + bool succeeded () const; + int failed_step () const; + QString last_error () const; + + static QStringList greeting_messages (TciSimGreeting greeting); + +signals: + void finished (bool succeeded); + +private slots: + void execute_step (); + void poll_step (); + void delayed_step_ready (); + void overall_timeout (); + +private: + enum class StepKind + { + Greet, + Expect, + Reply, + Push, + Withhold, + Delay, + CloseNormally, + Reconnect, + }; + + struct Step + { + StepKind kind; + QString text; + ArgsPredicate predicate; + int timeout_ms {0}; + TciSimGreeting greeting {TciSimGreeting::Minimal}; + }; + + void append_expectation (StepKind kind, QString verb, + ArgsPredicate predicate, int timeout_ms); + void start_polling (int timeout_ms); + void complete_step (); + void fail (QString reason); + void finish (bool succeeded); + bool current_expectation_satisfied (); + QString step_description (Step const& step) const; + + TciSimServer * server_; + std::vector<Step> steps_; + TciSimServer::Cursor cursor_; + QTimer poll_timer_; + QTimer delay_timer_; + QTimer overall_timer_; + QElapsedTimer step_elapsed_; + int current_step_ {-1}; + int reconnect_after_generation_ {0}; + int active_connection_generation_ {0}; + int last_consumed_generation_ {0}; + int delayed_step_generation_ {0}; + int close_generation_ {0}; + bool close_observed_ {false}; + bool has_consumed_expectation_ {false}; + bool close_requested_ {false}; + bool running_ {false}; + bool succeeded_ {false}; + QString last_error_; +}; + +#endif // TCI_SIM_SCRIPT_HPP__ diff --git a/tests/unit/tci/TciSimServer.cpp b/tests/unit/tci/TciSimServer.cpp new file mode 100644 index 00000000..95296232 --- /dev/null +++ b/tests/unit/tci/TciSimServer.cpp @@ -0,0 +1,328 @@ +#include "TciSimServer.hpp" + +#include <utility> + +#include <QEventLoop> +#include <QHostAddress> +#include <QTimer> +#include <QUrl> +#include <QtWebSockets/QWebSocket> +#include <QtWebSockets/QWebSocketServer> + +#include "moc_TciSimServer.cpp" + +TciSimServer::TciSimServer (QObject * parent) + : QObject {parent} + , server_ {new QWebSocketServer {QStringLiteral ("TCI simulator"), + QWebSocketServer::NonSecureMode, this}} + , client_ {nullptr} +{ + connect (server_, &QWebSocketServer::newConnection, + this, &TciSimServer::on_new_connection); +} + +TciSimServer::~TciSimServer () +{ + close (); +} + +bool TciSimServer::listen () +{ + if (server_->isListening ()) return true; + if (!server_->listen (QHostAddress::LocalHost, 0)) return false; + port_ = server_->serverPort (); + return true; +} + +void TciSimServer::close () +{ + if (client_) + { + client_->close (QWebSocketProtocol::CloseCodeNormal, + QStringLiteral ("simulator done")); + client_ = nullptr; + } + server_->close (); + port_ = 0; +} + +quint16 TciSimServer::port () const +{ + return port_; +} + +QString TciSimServer::url () const +{ + return QStringLiteral ("ws://127.0.0.1:%1").arg (port_); +} + +bool TciSimServer::client_connected () const +{ + return client_ && client_->state () == QAbstractSocket::ConnectedState; +} + +bool TciSimServer::client_disconnected () const +{ + return !client_; +} + +int TciSimServer::connection_generation () const +{ + return connection_generation_; +} + +int TciSimServer::connection_count () const +{ + return connection_count_; +} + +void TciSimServer::send_text (QString text) +{ + if (!client_connected ()) return; + if (!text.endsWith (';')) text += ';'; + record_text (Direction::ServerToClient, text, connection_generation_); + client_->sendTextMessage (text); +} + +bool TciSimServer::send_binary (QByteArray const& data) +{ + return client_connected () && client_->sendBinaryMessage (data) == data.size (); +} + +bool TciSimServer::flush () +{ + return client_connected () && client_->flush (); +} + +void TciSimServer::send_text_later (QString text, int delay_ms) +{ + auto const generation = connection_generation_; + QTimer::singleShot (qMax (0, delay_ms), this, + [this, generation, text = std::move (text)] () mutable + { + if (client_connected () + && connection_generation_ == generation) + { + send_text (std::move (text)); + } + }); +} + +void TciSimServer::close_client (QString const& reason) +{ + if (client_) + { + client_->close (QWebSocketProtocol::CloseCodeNormal, reason); + } +} + +void TciSimServer::abort_client () +{ + if (client_) client_->abort (); +} + +QVector<TciSimServer::Message> const& TciSimServer::transcript () const +{ + return transcript_; +} + +QVector<TciSimServer::Frame> const& TciSimServer::frames () const +{ + return frames_; +} + +TciSimServer::Cursor TciSimServer::cursor (int start_index) const +{ + return {qBound (0, start_index, transcript_.size ())}; +} + +bool TciSimServer::consume ( + Cursor * cursor_value, Direction direction, QString const& verb, + Message * message, + std::function<bool (QStringList const&)> const& predicate, + int connection_generation) const +{ + if (!cursor_value) return false; + + for (int i = qMax (0, cursor_value->next_index); i < transcript_.size (); ++i) + { + auto const& candidate = transcript_.at (i); + cursor_value->next_index = i + 1; + if (candidate.direction != direction || candidate.verb != verb) continue; + if (connection_generation > 0 + && candidate.connection_generation != connection_generation) continue; + if (predicate && !predicate (candidate.args)) continue; + if (message) *message = candidate; + return true; + } + cursor_value->next_index = transcript_.size (); + return false; +} + +QVector<TciSimServer::Message> TciSimServer::messages ( + Direction direction, QString const& verb) const +{ + QVector<Message> result; + for (auto const& message : transcript_) + { + if (message.direction == direction + && (verb.isEmpty () || message.verb == verb)) + { + result.append (message); + } + } + return result; +} + +int TciSimServer::count (Direction direction, QString const& verb) const +{ + int result {0}; + for (auto const& message : transcript_) + { + if (message.direction == direction + && (verb.isEmpty () || message.verb == verb)) + { + ++result; + } + } + return result; +} + +int TciSimServer::index_of ( + Direction direction, QString const& verb, int occurrence) const +{ + if (occurrence < 0) return -1; + for (int i = 0; i < transcript_.size (); ++i) + { + auto const& message = transcript_.at (i); + if (message.direction == direction && message.verb == verb + && occurrence-- == 0) + { + return i; + } + } + return -1; +} + +bool TciSimServer::occurs_before ( + Direction first_direction, QString const& first_verb, + Direction second_direction, QString const& second_verb) const +{ + auto const first = index_of (first_direction, first_verb); + auto const second = index_of (second_direction, second_verb); + return first >= 0 && second >= 0 && first < second; +} + +QString TciSimServer::transcript_text () const +{ + QStringList lines; + lines.reserve (frames_.size ()); + for (auto const& frame : frames_) + { + auto const arrow = frame.direction == Direction::ClientToServer + ? QStringLiteral ("client -> server") + : QStringLiteral ("server -> client"); + lines.append (QStringLiteral ("frame #%1 connection %2 %3: %4") + .arg (frame.ordinal) + .arg (frame.connection_generation) + .arg (arrow, frame.raw)); + } + return lines.join ('\n'); +} + +bool TciSimServer::wait_for ( + std::function<bool ()> const& predicate, int timeout_ms) +{ + if (predicate ()) return true; + + QEventLoop loop; + QTimer poller; + QTimer timeout; + bool matched {false}; + poller.setInterval (5); + timeout.setSingleShot (true); + connect (&poller, &QTimer::timeout, &loop, + [&predicate, &matched, &loop] () + { + if (!predicate ()) return; + matched = true; + loop.quit (); + }); + connect (&timeout, &QTimer::timeout, &loop, &QEventLoop::quit); + poller.start (); + timeout.start (qMax (0, timeout_ms)); + loop.exec (); + return matched || predicate (); +} + +void TciSimServer::on_new_connection () +{ + while (auto * candidate = server_->nextPendingConnection ()) + { + if (client_) + { + candidate->close (QWebSocketProtocol::CloseCodePolicyViolated, + QStringLiteral ("one client at a time")); + candidate->deleteLater (); + continue; + } + + client_ = candidate; + connection_generation_ = ++connection_count_; + client_->setProperty ("tciConnectionGeneration", connection_generation_); + connect (client_, &QWebSocket::textMessageReceived, + this, &TciSimServer::on_text_message); + connect (client_, &QWebSocket::disconnected, + this, &TciSimServer::on_disconnected); + emit client_arrived (connection_generation_); + } +} + +void TciSimServer::on_text_message (QString const& text) +{ + auto * socket = qobject_cast<QWebSocket *> (sender ()); + auto const generation = socket + ? socket->property ("tciConnectionGeneration").toInt () + : connection_generation_; + record_text (Direction::ClientToServer, text, generation); + emit text_received (text, generation); +} + +void TciSimServer::on_disconnected () +{ + auto * socket = qobject_cast<QWebSocket *> (sender ()); + auto const generation = socket + ? socket->property ("tciConnectionGeneration").toInt () + : connection_generation_; + if (socket == client_) client_ = nullptr; + if (socket) socket->deleteLater (); + emit client_gone (generation); +} + +void TciSimServer::record_text ( + Direction direction, QString const& text, int generation) +{ + frames_.append ({direction, generation, next_frame_ordinal_++, text}); + auto const commands = text.split (';', Qt::SkipEmptyParts); + for (auto const& command : commands) + { + transcript_.append (parse_message (direction, generation, + next_ordinal_++, command)); + } +} + +TciSimServer::Message TciSimServer::parse_message ( + Direction direction, int generation, quint64 ordinal, QString const& raw) +{ + Message result {direction, generation, ordinal, raw, {}, {}}; + auto const separator = raw.indexOf (':'); + if (separator < 0) + { + result.verb = raw.trimmed (); + return result; + } + + result.verb = raw.left (separator).trimmed (); + result.args = raw.mid (separator + 1).split (',', Qt::KeepEmptyParts); + return result; +} diff --git a/tests/unit/tci/TciSimServer.hpp b/tests/unit/tci/TciSimServer.hpp new file mode 100644 index 00000000..c64c0a09 --- /dev/null +++ b/tests/unit/tci/TciSimServer.hpp @@ -0,0 +1,111 @@ +#ifndef TCI_SIM_SERVER_HPP__ +#define TCI_SIM_SERVER_HPP__ + +#include <functional> + +#include <QObject> +#include <QString> +#include <QStringList> +#include <QVector> + +class QWebSocket; +class QWebSocketServer; + +class TciSimServer final + : public QObject +{ + Q_OBJECT + +public: + enum class Direction + { + ClientToServer, + ServerToClient, + }; + + struct Message + { + Direction direction; + int connection_generation; + quint64 ordinal; + QString raw; + QString verb; + QStringList args; + }; + + struct Frame + { + Direction direction; + int connection_generation; + quint64 ordinal; + QString raw; + }; + + struct Cursor + { + int next_index {0}; + }; + + explicit TciSimServer (QObject * parent = nullptr); + ~TciSimServer () override; + + bool listen (); + void close (); + quint16 port () const; + QString url () const; + + bool client_connected () const; + bool client_disconnected () const; + int connection_generation () const; + int connection_count () const; + + void send_text (QString text); + bool send_binary (QByteArray const& data); + bool flush (); + void send_text_later (QString text, int delay_ms); + void close_client (QString const& reason = QStringLiteral ("simulator close")); + void abort_client (); + + QVector<Message> const& transcript () const; + QVector<Frame> const& frames () const; + Cursor cursor (int start_index = 0) const; + bool consume (Cursor * cursor, Direction direction, QString const& verb, + Message * message = nullptr, + std::function<bool (QStringList const&)> const& predicate = {}, + int connection_generation = 0) const; + QVector<Message> messages (Direction direction, QString const& verb = {}) const; + int count (Direction direction, QString const& verb = {}) const; + int index_of (Direction direction, QString const& verb, int occurrence = 0) const; + bool occurs_before (Direction first_direction, QString const& first_verb, + Direction second_direction, QString const& second_verb) const; + QString transcript_text () const; + + bool wait_for (std::function<bool ()> const& predicate, int timeout_ms); + +signals: + void client_arrived (int connection_generation); + void client_gone (int connection_generation); + void text_received (QString const& raw, int connection_generation); + +private slots: + void on_new_connection (); + void on_text_message (QString const& text); + void on_disconnected (); + +private: + void record_text (Direction direction, QString const& text, int generation); + static Message parse_message (Direction direction, int generation, + quint64 ordinal, QString const& raw); + + QWebSocketServer * server_; + QWebSocket * client_; + quint16 port_ {0}; + int connection_generation_ {0}; + int connection_count_ {0}; + quint64 next_ordinal_ {0}; + quint64 next_frame_ordinal_ {0}; + QVector<Message> transcript_; + QVector<Frame> frames_; +}; + +#endif // TCI_SIM_SERVER_HPP__ diff --git a/tests/unit/tci/test_tci_protocol.cpp b/tests/unit/tci/test_tci_protocol.cpp new file mode 100644 index 00000000..95b4e01d --- /dev/null +++ b/tests/unit/tci/test_tci_protocol.cpp @@ -0,0 +1,110 @@ +#include <limits> + +#include <QtTest> + +#include "Transceiver/TCIProtocol.hpp" + +class TestTciProtocol final + : public QObject +{ + Q_OBJECT + +private slots: + void parsesFrequency_data () + { + QTest::addColumn<QString> ("text"); + QTest::addColumn<quint64> ("expected"); + + QTest::newRow ("ordinary HF") << QString {"14074000"} << quint64 {14074000u}; + QTest::newRow ("below signed 32-bit boundary") << QString {"2147483647"} << quint64 {2147483647u}; + QTest::newRow ("at signed 32-bit boundary") << QString {"2147483648"} << quint64 {2147483648u}; + QTest::newRow ("above signed 32-bit boundary") << QString {"2147483649"} << quint64 {2147483649u}; + QTest::newRow ("10.368 GHz") << QString {"10368000000"} << quint64 {10368000000u}; + QTest::newRow ("upper supported TCI range") << QString {"250000000000"} << quint64 {250000000000u}; + QTest::newRow ("leading zeros") << QString {"00014074000"} << quint64 {14074000u}; + QTest::newRow ("zero") << QString {"0"} << quint64 {0u}; + QTest::newRow ("quint64 maximum") + << QString {"18446744073709551615"} << (std::numeric_limits<quint64>::max) (); + } + + void parsesFrequency () + { + QFETCH (QString, text); + QFETCH (quint64, expected); + + quint64 frequency {99u}; + QVERIFY (TciProtocol::parse_frequency (text, &frequency)); + QCOMPARE (frequency, expected); + } + + void rejectsMalformedFrequency_data () + { + QTest::addColumn<QString> ("text"); + + QTest::newRow ("empty") << QString {}; + QTest::newRow ("negative") << QString {"-14074000"}; + QTest::newRow ("positive sign") << QString {"+14074000"}; + QTest::newRow ("leading whitespace") << QString {" 14074000"}; + QTest::newRow ("trailing whitespace") << QString {"14074000 "}; + QTest::newRow ("group separator") << QString {"14,074,000"}; + QTest::newRow ("decimal") << QString {"14074.000"}; + QTest::newRow ("exponent") << QString {"14074e3"}; + QTest::newRow ("trailing text") << QString {"14074000Hz"}; + QTest::newRow ("unicode digit") << QString::fromUtf8 ("١٤٠٧٤٠٠٠"); + QTest::newRow ("replacement character") + << QString {"14"} + QChar {QChar::ReplacementCharacter} + QString {"074000"}; + QTest::newRow ("overflow") << QString {"18446744073709551616"}; + } + + void rejectsMalformedFrequency () + { + QFETCH (QString, text); + + quint64 frequency {99u}; + QVERIFY (!TciProtocol::parse_frequency (text, &frequency)); + QCOMPARE (frequency, quint64 {99u}); + } + + void rejectsMissingOutput () + { + QVERIFY (!TciProtocol::parse_frequency (QString {"14074000"}, nullptr)); + } + + void comparesFrequencyDifference_data () + { + QTest::addColumn<quint64> ("lhs"); + QTest::addColumn<quint64> ("rhs"); + QTest::addColumn<bool> ("expected"); + + QTest::newRow ("ordinary HF below threshold") + << quint64 {14074000u} << quint64 {15073999u} << false; + QTest::newRow ("below threshold") + << quint64 {10368000000u} << quint64 {10368999999u} << false; + QTest::newRow ("exact threshold") + << quint64 {10368000000u} << quint64 {10369000000u} << false; + QTest::newRow ("above threshold") + << quint64 {10368000000u} << quint64 {10369000001u} << true; + QTest::newRow ("above threshold reversed") + << quint64 {10369000001u} << quint64 {10368000000u} << true; + QTest::newRow ("signed boundary adjacent") + << quint64 {2147483647u} << quint64 {2147483648u} << false; + QTest::newRow ("upper supported range") + << quint64 {250000000000u} << quint64 {249998999999u} << true; + QTest::newRow ("quint64 upper edge") + << (std::numeric_limits<quint64>::max) () + << (std::numeric_limits<quint64>::max) () - quint64 {1000001u} << true; + } + + void comparesFrequencyDifference () + { + QFETCH (quint64, lhs); + QFETCH (quint64, rhs); + QFETCH (bool, expected); + + QCOMPARE (TciProtocol::frequency_difference_exceeds (lhs, rhs, quint64 {1000000u}), expected); + } +}; + +QTEST_MAIN (TestTciProtocol) + +#include "test_tci_protocol.moc" diff --git a/tests/unit/tci/test_tci_receive_ownership.cpp b/tests/unit/tci/test_tci_receive_ownership.cpp new file mode 100644 index 00000000..3f061130 --- /dev/null +++ b/tests/unit/tci/test_tci_receive_ownership.cpp @@ -0,0 +1,451 @@ +#include <QtTest> +#include <QMutexLocker> +#include <QThread> +#include <boost/log/keywords/channel.hpp> + +#include <algorithm> +#include <array> +#include <atomic> +#include <chrono> +#include <condition_variable> +#include <cstring> +#include <functional> +#include <memory> +#include <mutex> +#include <vector> + +#include "DecDataMutex.hpp" +#include "FastDecode.hpp" +#include "TciSimScript.hpp" +#include "TciSimServer.hpp" +#include "Transceiver/TCITransceiver.hpp" +#include "widgets/itoneAndicw.h" +#include "wsjtx_config.h" + +namespace +{ +dec_data_t storage {}; +constexpr int block = 3456; +constexpr int captureCount = block; + +struct ReceiveClock +{ + std::mutex mutex; + std::condition_variable changed; + qint64 timestamp = 104000; // 14 s into a 15 s period; 105000 wraps to zero. + bool armed = false, paused = false, released = false, timedOut = false; + + qint64 now () + { + std::unique_lock<std::mutex> lock {mutex}; + if (armed) + { + armed = false; + paused = true; + changed.notify_all (); + timedOut = !changed.wait_for (lock, std::chrono::seconds {5}, [&] { return released; }); + } + return timestamp; + } + void set (qint64 value) { std::lock_guard<std::mutex> lock {mutex}; timestamp = value; } + void arm () { std::lock_guard<std::mutex> lock {mutex}; armed = true; } + bool waitPaused () + { + std::unique_lock<std::mutex> lock {mutex}; + return changed.wait_for (lock, std::chrono::seconds {5}, [&] { return paused; }); + } + void release () + { + std::lock_guard<std::mutex> lock {mutex}; + released = true; + changed.notify_all (); + } +}; + +// The real decoder launcher is linked; only the downstream decoder is a probe. +struct DecodeProbe +{ + std::mutex mutex; + std::condition_variable changed; + bool released = false, timedOut = false; + std::vector<short> samples; + int frames = 0; + double period = 0; + QByteArray myCall, hisCall; + void release () + { + std::lock_guard<std::mutex> lock {mutex}; + released = true; + changed.notify_all (); + } +}; +DecodeProbe * activeProbe = nullptr; + +struct Job +{ + std::array<int, 15> arguments {}; + std::array<char, 8000> messages {}; + char myCall[12], hisCall[12]; + double period = 15; + Job () + { + arguments[1] = captureCount; + arguments[3] = 1; + arguments[9] = 104; + std::memcpy (myCall, "K1ABC ", 12); + std::memcpy (hisCall, "W9XYZ ", 12); + } + QFuture<FastDecodeResult> submit (short const * samples = storage.d2) + { + return startFastDecode (samples, arguments.data (), period, + myCall, hisCall); + } +}; + +class Harness +{ +public: + Harness () : logger_ {boost::log::keywords::channel = "TCI_RECEIVE_TEST"} + { + QObject::connect (&server, &TciSimServer::client_arrived, &server, [this] (int) { + server.send_text (TciSimScript::greeting_messages (TciSimGreeting::Thetis).join (';')); + }); + QObject::connect (&server, &TciSimServer::text_received, &server, + [this] (QString const& text, int) { + for (auto const& command : text.split (';', Qt::SkipEmptyParts)) + { + auto const verb = command.section (':', 0, 0); + if (verb == "split_enable") server.send_text ("split_enable:0,false"); + else if (verb == "audio_start" || verb == "audio_stop" + || verb == "modulation" || verb == "rx_enable" + || verb == "trx" || verb == "start" || verb == "stop") + server.send_text (command); + else if (verb == "vfo") + server.send_text (command.count (',') >= 2 ? command : "vfo:0,0,14074000"); + } + }); + context_ = new QObject; + context_->moveToThread (&thread_); + QObject::connect (&thread_, &QThread::finished, context_, &QObject::deleteLater); + thread_.start (); + } + + ~Harness () + { + clock.release (); + auto stopped = std::make_shared<std::atomic_bool> (false); + QMetaObject::invokeMethod (context_, [this, stopped] { + if (rig) { rig->stop (); delete rig; rig = nullptr; } + stopped->store (true); + }, Qt::QueuedConnection); + server.wait_for ([&] { return stopped->load (); }, 10000); + // Complete destruction before logger, clock and transport storage expire. + thread_.quit (); + thread_.wait (); + server.close (); + } + + bool start () + { + if (!server.listen ()) return false; + QString const address = QStringLiteral ("127.0.0.1:%1").arg (server.port ()); + QMetaObject::invokeMethod (context_, [this, address] { + rig = new TCITransceiver (&logger_, {}, "0", address, true, tci__audio, + context_, [this] { return clock.now (); }); + QObject::connect (rig, &Transceiver::failure, rig, [this] (QString const&) { + failed_.store (true); + }); + QObject::connect (rig, &Transceiver::tciframeswritten, rig, [this] (qint64) { + ++notifications_; + }); + QObject::connect (rig, &Transceiver::receiveAudio, &audioContext_, + [this] (ReceiveAudio audio) { + receiver_.accept (audio, storage); + }, Qt::QueuedConnection); + // A ready message is an ordered fence behind preceding binary frames. + QObject::connect (rig, &TCITransceiver::tci_done7, rig, [this] { + std::lock_guard<std::mutex> lock {fenceMutex_}; + ++fences_; + fenceChanged_.notify_all (); + }); + rig->start (1); + state_.online (true); + state_.frequency (14074000); + state_.mode (Transceiver::USB); + state_.period (15); + state_.audio (true); + state_.volume (0); + rig->set (state_, 2); + started_.store (true); + }, Qt::QueuedConnection); + return server.wait_for ([this] { return started_.load (); }, 10000) + && !failed_.load () && server.client_connected (); + } + + bool enableAudio (bool enabled) + { + QMetaObject::invokeMethod (context_, [this, enabled] { + state_.audio (enabled); + rig->set (state_, ++sequence_); + }, Qt::BlockingQueuedConnection); + return !failed_.load (); + } + + bool fence () + { + std::unique_lock<std::mutex> lock {fenceMutex_}; + auto const before = fences_; + server.send_text ("ready"); + server.flush (); + // No GUI event dispatch here: queued audio notifications may stay pending. + return fenceChanged_.wait_for (lock, std::chrono::seconds {5}, + [&] { return fences_ > before; }); + } + + bool packet (std::vector<float> const& pcm, int offset, int count, int receiver = 0) + { + QByteArray bytes; + if (!TciStream::prepare_float_frame (&bytes, 2 * count)) return false; + auto * header = TciStream::header (&bytes); + header->receiver = receiver; + header->sampleRate = 48000; + header->format = TciStream::Float32Format; + header->type = TciStream::RxAudioStream; + header->length = 2 * count; + header->channels = 2; + auto * payload = TciStream::float_payload (&bytes); + for (int i = 0; i < count; ++i) + { + payload[2 * i] = pcm[offset + i]; + payload[2 * i + 1] = -pcm[offset + i]; // Distinct unused right channel. + } + bool const sent = server.send_binary (bytes); + return sent; + } + + bool feed (std::vector<float> const& pcm, std::vector<int> const& chunks = {4096}, + int receiver = 0) + { + int offset = 0, index = 0; + while (offset < int (pcm.size ())) + { + int count = std::min (chunks[index++ % chunks.size ()], int (pcm.size ()) - offset); + if (!packet (pcm, offset, count, receiver)) return false; + offset += count; + } + return fence (); + } + + std::vector<short> snapshot () + { + QCoreApplication::sendPostedEvents (&audioContext_, QEvent::MetaCall); + QMutexLocker lock {&dec_data_mutex ()}; + return {storage.d2, storage.d2 + storage.params.kin}; + } + int notifications () const { return notifications_.load (); } + + TciSimServer server; + ReceiveClock clock; + TCITransceiver * rig = nullptr; +private: + Transceiver::logger_type logger_; + QThread thread_; + QObject * context_ = nullptr; + QObject audioContext_; + ReceiveAudioConsumer receiver_; + Transceiver::TransceiverState state_; + unsigned sequence_ = 2; + std::atomic_bool started_ {false}, failed_ {false}; + std::atomic_int notifications_ {0}; + std::mutex fenceMutex_; + std::condition_variable fenceChanged_; + int fences_ = 0; +}; + +std::vector<float> signal (int outputFrames, float value) +{ + return std::vector<float> (4 * outputFrames, value); +} +} + +dec_data_t& dec_data = storage; +int volatile itone[MAX_NUM_SYMBOLS] {}; +int volatile icw[NUM_CW_SYMBOLS] {}; +float gran () { return 0; } + +extern "C" void fast_decode_ (short samples[], int arguments[], double * period, + char[], char myCall[], char hisCall[], + fortran_charlen_t, fortran_charlen_t, fortran_charlen_t) +{ + auto& probe = *activeProbe; + std::unique_lock<std::mutex> lock {probe.mutex}; + probe.timedOut = !probe.changed.wait_for (lock, std::chrono::seconds {5}, + [&] { return probe.released; }); + if (probe.timedOut) return; + probe.frames = arguments[1]; + if (probe.frames >= 0 && probe.frames <= 360000) + probe.samples.assign (samples, samples + probe.frames); + probe.period = *period; + probe.myCall = QByteArray (myCall, 12); + probe.hisCall = QByteArray (hisCall, 12); +} + +class TestTciReceiveOwnership : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void packetization_preserves_audio () + { + Harness h; + QVERIFY (h.start ()); + auto pcm = signal (captureCount, 0.0f); + for (std::size_t i = 0; i < pcm.size (); ++i) + pcm[i] = (int (i % 31) - 15) / 32.0f; + // fil4 has persistent FIR history. Feed the same silent pre-roll for each + // run; do not reset it through test-only access to Fortran saved state. + QVERIFY (h.feed (signal (block, 0.0f))); + QVERIFY (h.feed (pcm)); + auto first = h.snapshot (); + QVERIFY (h.enableAudio (false)); + QVERIFY (h.enableAudio (true)); + QVERIFY (h.feed (signal (block, 0.0f), {4095})); + QVERIFY (h.feed (pcm, {4095})); + auto second = h.snapshot (); + QCOMPARE (first.size (), std::size_t (2 * block)); + QCOMPARE (second.size (), first.size ()); + QVERIFY (std::any_of (first.begin () + block, first.end (), [] (short x) { return x != 0; })); + // Discard pre-roll output: its first taps legitimately contain history + // from the preceding stream. Compare only identically conditioned audio. + QVERIFY (std::equal (first.begin () + block, first.end (), second.begin () + block)); + } + + void ignored_audio_does_not_change_reception () + { + Harness h; + QVERIFY (h.start ()); + QVERIFY (h.feed (signal (captureCount, 0.125f))); + auto before = h.snapshot (); + int const notifications = h.notifications (); + + QVERIFY (h.feed (signal (block, -0.25f), {4096}, 1)); + QVERIFY (before == h.snapshot ()); + QCOMPARE (h.notifications (), notifications); + + QVERIFY (h.enableAudio (false)); + QVERIFY (h.feed (signal (block, -0.25f))); + QVERIFY (before == h.snapshot ()); + QCOMPARE (h.notifications (), notifications); + // An accepted block is a positive control proving the transport and gate + // work, rather than mistaking an idle or disconnected receiver for success. + QVERIFY (h.enableAudio (true)); + QVERIFY (h.feed (signal (block, -0.25f))); + QCOMPARE (h.snapshot ().size (), std::size_t (block)); + } + + void submitted_job_survives_period_reuse () + { + Harness h; + QVERIFY (h.start ()); + QVERIFY (h.feed (signal (captureCount, 0.125f))); + auto const expected = h.snapshot (); + Job job; + DecodeProbe probe; + activeProbe = &probe; + auto future = job.submit (); + h.clock.set (105000); + bool const fed = h.feed (signal (captureCount, -0.25f)); + auto const replacement = h.snapshot (); + probe.release (); + future.waitForFinished (); + activeProbe = nullptr; + QVERIFY (fed); + QVERIFY (!probe.timedOut); + QCOMPARE (replacement.size (), expected.size ()); + QVERIFY (replacement != expected); + QCOMPARE (probe.samples.size (), expected.size ()); + QCOMPARE (probe.samples.back (), expected.back ()); + QVERIFY (probe.samples == expected); + QCOMPARE (probe.frames, captureCount); + QCOMPARE (probe.period, 15.0); + QCOMPARE (probe.myCall, QByteArray ("K1ABC ", 12)); + QCOMPARE (probe.hisCall, QByteArray ("W9XYZ ", 12)); + } + + void capture_vs_transport_append () + { + Harness h; + QVERIFY (h.start ()); + QVERIFY (h.feed (signal (captureCount, 0.125f))); + auto const expected = h.snapshot (); + // Leave one stereo frame before the next real downsampler output block. + auto next = signal (block, -0.25f); + next.pop_back (); + QVERIFY (h.feed (next)); + h.clock.arm (); + QVERIFY (h.packet (std::vector<float> { -0.25f }, 0, 1)); + h.server.flush (); + bool const paused = h.clock.waitPaused (); + Job job; + DecodeProbe probe; + probe.released = true; + activeProbe = &probe; + h.clock.release (); + // Both real sample accesses follow release, with no completion ordering. + auto future = job.submit (); + bool const finished = h.fence (); + future.waitForFinished (); + activeProbe = nullptr; + QVERIFY (paused); + QVERIFY (finished); + QVERIFY (!h.clock.timedOut); + QVERIFY (!probe.timedOut); + QCOMPARE (h.snapshot ().size (), std::size_t (captureCount + block)); + QVERIFY (probe.samples == expected); + } + + void delayed_notification_retains_period_identity () + { + Harness h; + QVERIFY (h.start ()); + Job job; + DecodeProbe probe; + probe.released = true; + activeProbe = &probe; + QObject consumer; + bool handled = false; + int rejected = 0; + auto received = std::make_unique<dec_data_t> (); + ReceiveAudioConsumer receiver; + QFuture<FastDecodeResult> future; + QObject::connect (h.rig, &Transceiver::receiveAudio, &consumer, [&] (ReceiveAudio audio) { + if (!receiver.accept (audio, *received)) { ++rejected; return; } + if (handled || audio->end () != captureCount) return; + handled = true; + future = job.submit (received->d2); + }, Qt::QueuedConnection); + // Transport fences do not dispatch the main thread's queued callbacks. + bool const fedA = h.feed (signal (captureCount, 0.125f)); + auto const expected = h.snapshot (); + h.clock.set (105000); + bool const fedB = h.feed (signal (captureCount, -0.25f)); + auto const replacement = h.snapshot (); + QCoreApplication::sendPostedEvents (&consumer, QEvent::MetaCall); + future.waitForFinished (); + activeProbe = nullptr; + QVERIFY (fedA); + QVERIFY (fedB); + QVERIFY (handled); + QVERIFY (rejected > 0); + QVERIFY (!probe.timedOut); + QCOMPARE (expected.size (), std::size_t (captureCount)); + QCOMPARE (replacement.size (), expected.size ()); + QVERIFY (replacement != expected); + QCOMPARE (probe.samples.size (), expected.size ()); + QCOMPARE (probe.samples.back (), replacement.back ()); + QVERIFY (probe.samples == replacement); + // Stale A is rejected; B still reaches the production decode boundary. + } +}; + +QTEST_GUILESS_MAIN (TestTciReceiveOwnership) +#include "test_tci_receive_ownership.moc" diff --git a/tests/unit/tci/test_tci_sim_smoke.cpp b/tests/unit/tci/test_tci_sim_smoke.cpp new file mode 100644 index 00000000..582bb66a --- /dev/null +++ b/tests/unit/tci/test_tci_sim_smoke.cpp @@ -0,0 +1,387 @@ +#include "TciSimScript.hpp" +#include "TciSimServer.hpp" + +#include <memory> + +#include <QElapsedTimer> +#include <QTimer> +#include <QtTest> +#include <QtWebSockets/QWebSocket> + +namespace +{ + struct ReconnectState + { + bool client_disconnected {false}; + bool server_disconnected {false}; + bool reopened {false}; + }; + + void reconnect_once_after_retirement ( + QWebSocket& client, TciSimServer& server) + { + auto state = std::make_shared<ReconnectState> (); + auto reopen = [state, &client, &server] + { + if (state->reopened || !state->client_disconnected + || !state->server_disconnected) + { + return; + } + state->reopened = true; + QTimer::singleShot (0, &client, + [&client, &server] + { + client.open (QUrl {server.url ()}); + }); + }; + + QObject::connect (&client, &QWebSocket::disconnected, &client, + [state, reopen] + { + state->client_disconnected = true; + reopen (); + }); + QObject::connect (&server, &TciSimServer::client_gone, &client, + [state, reopen] (int) + { + state->server_disconnected = true; + reopen (); + }); + } +} + +class TestTciSim final + : public QObject +{ + Q_OBJECT + +private slots: + void recordsOrderedFullDuplexTranscript () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&client, &server] + { + return server.client_connected () + && client.state () == QAbstractSocket::ConnectedState; + }, 1000)); + + client.sendTextMessage (QStringLiteral ( + "vfo:0,0,14074000;vfo:0,1,14075000;split_enable:0,true;")); + QVERIFY (server.wait_for ([&server] + { + return server.count ( + TciSimServer::Direction::ClientToServer) == 3; + }, 1000)); + server.send_text (QStringLiteral ("vfo:0,0,14074000;trx:0,false")); + + auto const& frames = server.frames (); + QCOMPARE (frames.size (), 2); + QCOMPARE (frames.at (0).raw, QStringLiteral ( + "vfo:0,0,14074000;vfo:0,1,14075000;split_enable:0,true;")); + QCOMPARE (frames.at (1).raw, + QStringLiteral ("vfo:0,0,14074000;trx:0,false;")); + QCOMPARE (frames.at (0).ordinal, quint64 {0}); + QCOMPARE (frames.at (1).ordinal, quint64 {1}); + + auto const& transcript = server.transcript (); + QCOMPARE (transcript.size (), 5); + QCOMPARE (transcript.at (0).direction, + TciSimServer::Direction::ClientToServer); + QCOMPARE (transcript.at (0).connection_generation, 1); + QCOMPARE (transcript.at (0).ordinal, quint64 {0}); + QCOMPARE (transcript.at (0).raw, QStringLiteral ("vfo:0,0,14074000")); + QCOMPARE (transcript.at (0).verb, QStringLiteral ("vfo")); + QCOMPARE (transcript.at (0).args, + QStringList ({"0", "0", "14074000"})); + QCOMPARE (transcript.at (1).verb, QStringLiteral ("vfo")); + QCOMPARE (transcript.at (2).verb, QStringLiteral ("split_enable")); + QCOMPARE (transcript.at (3).direction, + TciSimServer::Direction::ServerToClient); + QCOMPARE (transcript.at (4).verb, QStringLiteral ("trx")); + QVERIFY (server.occurs_before (TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), + TciSimServer::Direction::ClientToServer, + QStringLiteral ("split_enable"))); + } + + void cursorConsumesRepeatedCommands () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&client, &server] + { + return server.client_connected () + && client.state () == QAbstractSocket::ConnectedState; + }, 1000)); + client.sendTextMessage (QStringLiteral ( + "vfo:0,0,7074000;vfo:0,0,14074000;vfo:0,0,21074000;")); + QVERIFY (server.wait_for ([&server] + { + return server.count ( + TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo")) == 3; + }, 1000)); + + auto cursor = server.cursor (); + TciSimServer::Message message; + QVERIFY (server.consume (&cursor, TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), &message)); + QCOMPARE (message.args.at (2), QStringLiteral ("7074000")); + QVERIFY (server.consume (&cursor, TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), &message)); + QCOMPARE (message.args.at (2), QStringLiteral ("14074000")); + QVERIFY (server.consume (&cursor, TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), &message, + [] (QStringList const& args) + { + return args.value (2) == QStringLiteral ("21074000"); + })); + QCOMPARE (message.ordinal, quint64 {2}); + QVERIFY (!server.consume (&cursor, TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"))); + QCOMPARE (server.count (TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo")), 3); + QCOMPARE (server.index_of (TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), 2), 2); + } + + void scriptGreetsDelaysAndWithholds () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + QStringList received; + bool command_sent {false}; + QElapsedTimer delayed_reply; + connect (&client, &QWebSocket::textMessageReceived, this, + [&client, &received, &command_sent, + &delayed_reply] (QString const& text) + { + received.append (text); + if (text != QStringLiteral ("ready;") || command_sent) return; + command_sent = true; + delayed_reply.start (); + client.sendTextMessage (QStringLiteral ("vfo:0,0,14074000;")); + }); + + TciSimScript script {&server}; + script.greet (TciSimGreeting::Thetis) + .withhold (QStringLiteral ("vfo"), + [] (QStringList const& args) + { + return args.value (2) == QStringLiteral ("14074000"); + }) + .delay (30) + .push (QStringLiteral ("vfo:0,0,14074000")); + client.open (QUrl {server.url ()}); + QVERIFY2 (script.run (2000), qPrintable (script.last_error ())); + QVERIFY (received.contains (QStringLiteral ("ready;"))); + QVERIFY (command_sent); + QVERIFY (delayed_reply.elapsed () >= 20); + QCOMPARE (server.count (TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo")), 1); + QCOMPARE (server.count (TciSimServer::Direction::ServerToClient, + QStringLiteral ("vfo")), 3); + } + + void scriptClosesAndAcceptsReconnect () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + reconnect_once_after_retirement (client, server); + + TciSimScript script {&server}; + script.greet (TciSimGreeting::Minimal) + .close_normally () + .reconnect () + .greet (TciSimGreeting::Minimal); + client.open (QUrl {server.url ()}); + QVERIFY2 (script.run (3000), qPrintable (script.last_error ())); + QCOMPARE (server.connection_count (), 2); + QCOMPARE (server.count (TciSimServer::Direction::ServerToClient, + QStringLiteral ("ready")), 2); + auto const ready = server.messages (TciSimServer::Direction::ServerToClient, + QStringLiteral ("ready")); + QCOMPARE (ready.at (0).connection_generation, 1); + QCOMPARE (ready.at (1).connection_generation, 2); + } + + void reconnectExpectationsIgnoreOldConnectionCommands () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + reconnect_once_after_retirement (client, server); + int client_connection_count {0}; + connect (&client, &QWebSocket::connected, this, + [&client, &client_connection_count] + { + ++client_connection_count; + if (client_connection_count == 2) + { + QTimer::singleShot (30, &client, + [&client] + { + client.sendTextMessage ( + QStringLiteral ("future:2;")); + }); + } + }); + + TciSimScript script {&server}; + script.expect (QStringLiteral ("trigger")) + .close_normally () + .reconnect () + .expect (QStringLiteral ("future"), + [] (QStringList const& args) {return args == QStringList {"2"};}); + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&client, &server] + { + return server.client_connected () + && client.state () == QAbstractSocket::ConnectedState; + }, 1000)); + QTimer::singleShot (0, &client, + [&client] + { + client.sendTextMessage ( + QStringLiteral ("trigger;future:1;")); + }); + QVERIFY2 (script.run (3000), qPrintable (script.last_error ())); + auto const future = server.messages (TciSimServer::Direction::ClientToServer, + QStringLiteral ("future")); + QCOMPARE (future.size (), 2); + QCOMPARE (future.at (0).connection_generation, 1); + QCOMPARE (future.at (1).connection_generation, 2); + } + + void delayedPushDoesNotCrossConnectionGeneration () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + reconnect_once_after_retirement (client, server); + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&client, &server] + { + return server.client_connected () + && client.state () == QAbstractSocket::ConnectedState; + }, 1000)); + + TciSimScript script {&server}; + script.push (QStringLiteral ("old-generation"), 50); + QTimer::singleShot (10, &server, [&server] {server.close_client ();}); + QVERIFY2 (script.run (1000), qPrintable (script.last_error ())); + QVERIFY (server.wait_for ([&server] {return server.connection_count () == 2;}, 1000)); + QCOMPARE (server.count (TciSimServer::Direction::ServerToClient, + QStringLiteral ("old-generation")), 0); + } + + void replyUsesTheConsumedExpectationGeneration () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + QStringList received; + connect (&client, &QWebSocket::textMessageReceived, this, + [&client, &received] (QString const& text) + { + received.append (text); + if (text == QStringLiteral ("ready;")) + { + client.sendTextMessage (QStringLiteral ("request:1;")); + } + }); + + TciSimScript script {&server}; + script.greet (TciSimGreeting::Minimal) + .expect (QStringLiteral ("request")) + .reply (QStringLiteral ("ack:1")); + client.open (QUrl {server.url ()}); + + QVERIFY2 (script.run (2000), qPrintable (script.last_error ())); + QVERIFY (server.wait_for ([&received] + { + return received.contains (QStringLiteral ("ack:1;")); + }, 1000)); + auto const replies = server.messages ( + TciSimServer::Direction::ServerToClient, QStringLiteral ("ack")); + QCOMPARE (replies.size (), 1); + QCOMPARE (replies.first ().connection_generation, 1); + } + + void replyWithoutAnExpectationFails () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + TciSimScript script {&server}; + script.greet (TciSimGreeting::Minimal) + .reply (QStringLiteral ("ack:1")); + client.open (QUrl {server.url ()}); + + QVERIFY (!script.run (1000)); + QVERIFY (script.last_error ().contains ( + QStringLiteral ("reply requires an expectation"))); + QCOMPARE (server.count (TciSimServer::Direction::ServerToClient, + QStringLiteral ("ack")), 0); + } + + void closeWithoutAClientFails () + { + TciSimServer server; + QVERIFY (server.listen ()); + + TciSimScript script {&server}; + script.close_normally (); + + QVERIFY (!script.run (100)); + QVERIFY (script.last_error ().contains ( + QStringLiteral ("cannot close without a connected client"))); + QCOMPARE (server.connection_count (), 0); + } + + void failureIncludesTranscript () + { + TciSimServer server; + QVERIFY (server.listen ()); + QWebSocket client; + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&server] { return server.client_connected (); }, 1000)); + client.sendTextMessage (QStringLiteral ("vfo:0,0,7074000;")); + + TciSimScript script {&server}; + script.expect (QStringLiteral ("trx"), {}, 20); + QVERIFY (!script.run (500)); + QCOMPARE (script.failed_step (), 1); + QVERIFY (script.last_error ().contains (QStringLiteral ("expecting trx"))); + QVERIFY (script.last_error ().contains (QStringLiteral ("vfo:0,0,7074000"))); + } + + void waitForShortCircuits () + { + TciSimServer server; + QElapsedTimer elapsed; + elapsed.start (); + QVERIFY (server.wait_for ([] { return true; }, 1000)); + QVERIFY (elapsed.elapsed () < 100); + } +}; + +QTEST_MAIN (TestTciSim) + +#include "test_tci_sim_smoke.moc" diff --git a/tests/unit/tci/test_tci_stream.cpp b/tests/unit/tci/test_tci_stream.cpp new file mode 100644 index 00000000..a9c8cfb4 --- /dev/null +++ b/tests/unit/tci/test_tci_stream.cpp @@ -0,0 +1,204 @@ +#include <cstddef> + +#include <QtTest> + +#include "Transceiver/TCIStream.hpp" + +class TestTciStream final + : public QObject +{ + Q_OBJECT + +private slots: + void preservesWireHeaderLayout () + { + QCOMPARE (sizeof (TciStream::Header), size_t {64}); + QCOMPARE (offsetof (TciStream::Header, length), size_t {20}); + QCOMPARE (offsetof (TciStream::Header, type), size_t {24}); + QCOMPARE (offsetof (TciStream::Header, channels), size_t {28}); + } + + void preparesExactZeroedFloatFrame () + { + QByteArray frame (128, '\x7f'); + + QVERIFY (TciStream::prepare_float_frame (&frame, 2048u)); + QCOMPARE (frame.size (), 64 + 2048 * int (sizeof (float))); + for (auto byte : frame) + { + QCOMPARE (byte, char {0}); + } + QVERIFY (TciStream::has_complete_float_payload (frame, 2048u)); + QVERIFY (!TciStream::has_complete_float_payload (frame.left (frame.size () - 1), 2048u)); + } + + void rejectsOversizedFloatFrame () + { + QByteArray frame; + QVERIFY (!TciStream::prepare_float_frame (&frame, TciStream::MaxFloatSamples + 1u)); + QVERIFY (!TciStream::checked_float_frame_size (1u, nullptr)); + } + + void recognizesChannelHeaderVersions_data () + { + QTest::addColumn<QString> ("version"); + QTest::addColumn<bool> ("expected"); + + QTest::newRow ("pre-channel header") << QString {"1.8"} << false; + QTest::newRow ("first channel header") << QString {"1.9"} << true; + QTest::newRow ("patch version") << QString {"1.9.1"} << true; + QTest::newRow ("current protocol") << QString {"2.0"} << true; + QTest::newRow ("invalid") << QString {"ExpertSDR3"} << false; + QTest::newRow ("missing") << QString {} << false; + } + + void recognizesChannelHeaderVersions () + { + QFETCH (QString, version); + QFETCH (bool, expected); + + QCOMPARE (TciStream::protocol_has_channels (version), expected); + } + + void validatesChronoParameters_data () + { + QTest::addColumn<bool> ("modern"); + QTest::addColumn<quint32> ("header_channels"); + QTest::addColumn<quint32> ("length"); + QTest::addColumn<quint32> ("format"); + QTest::addColumn<quint32> ("codec"); + QTest::addColumn<quint32> ("sample_rate"); + QTest::addColumn<bool> ("expected_valid"); + QTest::addColumn<quint32> ("expected_channels"); + + QTest::newRow ("legacy ignores reserved") + << false << quint32 {0xdeadbeefu} << quint32 {2048} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << true << quint32 {2}; + QTest::newRow ("modern mono") + << true << quint32 {1} << quint32 {3} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << true << quint32 {1}; + QTest::newRow ("modern stereo") + << true << quint32 {2} << quint32 {2048} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << true << quint32 {2}; + QTest::newRow ("zero-length mono") + << true << quint32 {1} << quint32 {0} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << true << quint32 {1}; + QTest::newRow ("odd stereo") + << true << quint32 {2} << quint32 {3} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << false << quint32 {0}; + QTest::newRow ("invalid modern channels") + << true << quint32 {0} << quint32 {2048} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << false << quint32 {0}; + QTest::newRow ("unsupported format") + << true << quint32 {2} << quint32 {2048} + << quint32 {0} << TciStream::UncompressedCodec << quint32 {48000} + << false << quint32 {0}; + QTest::newRow ("unsupported codec") + << true << quint32 {2} << quint32 {2048} + << TciStream::Float32Format << quint32 {1} << quint32 {48000} + << false << quint32 {0}; + QTest::newRow ("unsupported sample rate") + << true << quint32 {2} << quint32 {2048} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {24000} + << false << quint32 {0}; + QTest::newRow ("oversized") + << true << quint32 {1} << TciStream::MaxFloatSamples + 1u + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << false << quint32 {0}; + } + + void validatesChronoParameters () + { + QFETCH (bool, modern); + QFETCH (quint32, header_channels); + QFETCH (quint32, length); + QFETCH (quint32, format); + QFETCH (quint32, codec); + QFETCH (quint32, sample_rate); + QFETCH (bool, expected_valid); + QFETCH (quint32, expected_channels); + + TciStream::Header chrono {}; + chrono.sampleRate = sample_rate; + chrono.format = format; + chrono.codec = codec; + chrono.length = length; + chrono.channels = header_channels; + quint32 channels {99u}; + + QCOMPARE (TciStream::valid_tx_chrono (chrono, modern, 48000u, &channels), expected_valid); + if (expected_valid) + { + QCOMPARE (channels, expected_channels); + } + } + + void buildsConformingStereoResponse () + { + TciStream::Header chrono {}; + chrono.receiver = 1u; + chrono.sampleRate = 48000u; + chrono.length = 2048u; + QByteArray response; + + QVERIFY (TciStream::prepare_tx_audio_frame (&response, chrono, 2u)); + QCOMPARE (response.size (), 8256); + auto const * header = TciStream::header (response); + QCOMPARE (header->receiver, quint32 {1}); + QCOMPARE (header->sampleRate, quint32 {48000}); + QCOMPARE (header->format, TciStream::Float32Format); + QCOMPARE (header->codec, TciStream::UncompressedCodec); + QCOMPARE (header->length, quint32 {2048}); + QCOMPARE (header->type, quint32 {TciStream::TxAudioStream}); + QCOMPARE (header->channels, quint32 {2}); + for (auto reserved : header->reserved) + { + QCOMPARE (reserved, quint32 {0}); + } + for (quint32 i = 0u; i < header->length; ++i) + { + QCOMPARE (TciStream::float_payload (response)[i], 0.0f); + } + } + + void rejectsInvalidResponseChannelShape () + { + TciStream::Header chrono {}; + chrono.length = 3u; + QByteArray response; + + QVERIFY (!TciStream::prepare_tx_audio_frame (&response, chrono, 0u)); + QVERIFY (!TciStream::prepare_tx_audio_frame (&response, chrono, 2u)); + QVERIFY (TciStream::prepare_tx_audio_frame (&response, chrono, 1u)); + QCOMPARE (response.size (), 64 + 3 * int (sizeof (float))); + } + + void packsMonoAndStereoChannelFrames () + { + float mono[2] {}; + auto * mono_end = TciStream::write_channel_frame (0.25f, 1u, mono); + mono_end = TciStream::write_channel_frame (-0.5f, 1u, mono_end); + QCOMPARE (mono_end, mono + 2); + QCOMPARE (mono[0], 0.25f); + QCOMPARE (mono[1], -0.5f); + + float stereo[4] {}; + auto * stereo_end = TciStream::write_channel_frame (0.25f, 2u, stereo); + stereo_end = TciStream::write_channel_frame (-0.5f, 2u, stereo_end); + QCOMPARE (stereo_end, stereo + 4); + QCOMPARE (stereo[0], 0.25f); + QCOMPARE (stereo[1], 0.25f); + QCOMPARE (stereo[2], -0.5f); + QCOMPARE (stereo[3], -0.5f); + } +}; + +QTEST_MAIN (TestTciStream) + +#include "test_tci_stream.moc" diff --git a/tests/unit/tci/test_tci_transceiver_characterization.cpp b/tests/unit/tci/test_tci_transceiver_characterization.cpp new file mode 100644 index 00000000..17c3a395 --- /dev/null +++ b/tests/unit/tci/test_tci_transceiver_characterization.cpp @@ -0,0 +1,912 @@ +#include <functional> +#include <memory> + +#include <boost/log/keywords/channel.hpp> + +#include <QCoreApplication> +#include <QElapsedTimer> +#include <QTest> +#include <QTimer> +#include <QVector> + +#include "commons.h" +#include "TciSimScript.hpp" +#include "TciSimServer.hpp" +#include "Transceiver/TCITransceiver.hpp" +#include "widgets/itoneAndicw.h" + +namespace +{ + dec_data_t test_dec_data {}; + + using Direction = TciSimServer::Direction; + using Message = TciSimServer::Message; + using State = Transceiver::TransceiverState; + using Frequency = Transceiver::Frequency; + using CommandHandler = std::function<bool (QString const&, QStringList const&, int)>; + + Frequency constexpr initial_frequency {14074000}; + + using RigFactory = std::function<std::unique_ptr<Transceiver> ( + Transceiver::logger_type *, QString const&)>; + + RigFactory legacy_rig_factory () + { + return [] (Transceiver::logger_type * logger, QString const& address) + { + return std::unique_ptr<Transceiver> { + new TCITransceiver {logger, {}, QStringLiteral ("0"), address, + true, 0}}; + }; + } + + int message_index ( + TciSimServer const& server, int start, Direction direction, + QString const& verb, + std::function<bool (Message const&)> const& predicate = {}) + { + auto const& transcript = server.transcript (); + for (int i = qMax (0, start); i < transcript.size (); ++i) + { + auto const& message = transcript.at (i); + if (message.direction == direction && message.verb == verb + && (!predicate || predicate (message))) + { + return i; + } + } + return -1; + } + + bool has_args (Message const& message, QStringList const& args) + { + return message.args == args; + } + + class RigHarness + { + public: + using StatePredicate = std::function<bool (State const&)>; + + explicit RigHarness (RigFactory factory = legacy_rig_factory ()) + : logger_ {boost::log::keywords::channel = "TCI_CHARACTERIZATION"} + , factory_ {std::move (factory)} + { + QObject::connect (&server_, &TciSimServer::client_arrived, &server_, + [this] (int) + { + server_.send_text (startup_greeting ()); + }); + QObject::connect (&server_, &TciSimServer::text_received, &server_, + [this] (QString const& text, int generation) + { + handle_client_text (text, generation); + }); + } + + ~RigHarness () + { + tearing_down_ = true; + command_handler_ = {}; + destroy_rig (); + server_.close (); + } + + bool listen () + { + if (!server_.listen ()) return false; + create_rig (); + return true; + } + + bool start (unsigned sequence_number = 1) + { + auto const update_cursor = observations_.size (); + auto const previous_generation = server_.connection_generation (); + auto * rig = rig_.get (); + QTimer::singleShot (0, rig, + [rig, sequence_number] + { + rig->start (sequence_number); + }); + auto const completed = server_.wait_for ( + [this, update_cursor, previous_generation, sequence_number] + { + return server_.client_connected () + && server_.connection_generation () > previous_generation + && observed_state_since ( + update_cursor, sequence_number, + [] (State const& state) {return state.online ();}); + }, 7000); + return completed && server_.client_connected () + && server_.connection_generation () > previous_generation + && observed_state_since ( + update_cursor, sequence_number, + [] (State const& state) {return state.online ();}); + } + + bool restart (unsigned sequence_number) + { + return start (sequence_number); + } + + bool stop () + { + auto const completed = std::make_shared<bool> (false); + auto * rig = rig_.get (); + QTimer::singleShot (0, rig, + [rig, completed] + { + rig->stop (); + *completed = true; + }); + return server_.wait_for ( + [this, completed] + { + return *completed && server_.client_disconnected (); + }, 7000); + } + + int set (State state, unsigned sequence_number) + { + auto const update_cursor = observations_.size (); + auto * rig = rig_.get (); + QTimer::singleShot (0, rig, + [rig, state, sequence_number] + { + rig->set (state, sequence_number); + }); + return update_cursor; + } + + void set_now (State const& state, unsigned sequence_number) + { + rig_->set (state, sequence_number); + } + + void schedule_set (State state, unsigned sequence_number) + { + QTimer::singleShot (0, &server_, + [this, state, sequence_number] + { + if (!tearing_down_ && rig_) + { + rig_->set (state, sequence_number); + } + }); + } + + void set_command_handler (CommandHandler handler) + { + command_handler_ = std::move (handler); + } + + TciSimServer& server () {return server_;} + Transceiver& rig () {return *rig_;} + State const& state () const {return state_;} + int observation_count () const {return observations_.size ();} + int failure_count () const {return failures_.size ();} + + bool observed_state_since ( + int cursor, StatePredicate const& predicate) const + { + for (int i = qMax (0, cursor); i < observations_.size (); ++i) + { + if (predicate (observations_.at (i).state)) return true; + } + return false; + } + + bool observed_state_since ( + int cursor, unsigned sequence_number, + StatePredicate const& predicate) const + { + for (int i = qMax (0, cursor); i < observations_.size (); ++i) + { + auto const& observation = observations_.at (i); + if (observation.sequence_number == sequence_number + && predicate (observation.state)) + { + return true; + } + } + return false; + } + + bool wait_for_state ( + int cursor, unsigned sequence_number, + StatePredicate predicate, int timeout_ms = 6000) + { + auto const failure_cursor = failures_.size (); + auto const completed = server_.wait_for ( + [this, cursor, sequence_number, &predicate, failure_cursor] + { + return failures_.size () > failure_cursor + || observed_state_since (cursor, sequence_number, predicate); + }, timeout_ms); + return completed && failures_.size () == failure_cursor + && observed_state_since (cursor, sequence_number, predicate); + } + + bool wait_for_current_state (StatePredicate predicate, int timeout_ms = 1000) + { + return server_.wait_for ([this, &predicate] {return predicate (state_);}, + timeout_ms); + } + + bool wait_for_failure (int cursor, int timeout_ms = 6000) + { + return server_.wait_for ([this, cursor] {return failures_.size () > cursor;}, + timeout_ms); + } + + QString diagnostics () const + { + auto const sequence = observations_.isEmpty () + ? 0u : observations_.last ().sequence_number; + auto const failure = failures_.isEmpty () + ? QStringLiteral ("none") : failures_.last (); + return QStringLiteral ( + "connected=%1 generation=%2 updates=%3 sequence=%4 online=%5 " + "rx=%6 tx=%7 split=%8 ptt=%9 failure=%10\n%11") + .arg (server_.client_connected ()) + .arg (server_.connection_generation ()) + .arg (observations_.size ()) + .arg (sequence) + .arg (state_.online ()) + .arg (state_.frequency ()) + .arg (state_.tx_frequency ()) + .arg (state_.split ()) + .arg (state_.ptt ()) + .arg (failure, server_.transcript_text ()); + } + + private: + struct StateObservation + { + State state; + unsigned sequence_number; + }; + + static QString startup_greeting () + { + return TciSimScript::greeting_messages (TciSimGreeting::Thetis).join (';') + + ';'; + } + + void create_rig () + { + auto const address = QStringLiteral ("127.0.0.1:%1").arg (server_.port ()); + rig_ = factory_ (&logger_, address); + QObject::connect ( + rig_.get (), &Transceiver::update, &server_, + [this] (State const& state, unsigned sequence_number) + { + state_ = state; + observations_.append ({state, sequence_number}); + }); + QObject::connect ( + rig_.get (), &Transceiver::failure, &server_, + [this] (QString const& reason) {failures_.append (reason);}); + } + + void destroy_rig () + { + if (!rig_) return; + + bool client_gone = !server_.client_connected (); + auto const connection = QObject::connect ( + &server_, &TciSimServer::client_gone, &server_, + [&client_gone] (int) {client_gone = true;}); + rig_->stop (); + if (!client_gone) + { + server_.wait_for ([&client_gone] {return client_gone;}, 1000); + } + QObject::disconnect (connection); + rig_.reset (); + QCoreApplication::processEvents (QEventLoop::AllEvents, 20); + } + + void handle_client_text (QString const& text, int generation) + { + auto const commands = text.split (';', Qt::SkipEmptyParts); + for (auto const& command : commands) + { + auto const separator = command.indexOf (':'); + auto const verb = separator < 0 + ? command.trimmed () : command.left (separator).trimmed (); + auto const args = separator < 0 + ? QStringList {} : command.mid (separator + 1).split (',', Qt::KeepEmptyParts); + if (command_handler_ && command_handler_ (verb, args, generation)) continue; + acknowledge (verb, args); + } + } + + void acknowledge (QString const& verb, QStringList const& args) + { + if (verb == QStringLiteral ("vfo") && args.size () >= 3) + { + server_.send_text (QStringLiteral ("vfo:%1,%2,%3") + .arg (args.at (0), args.at (1), args.at (2))); + } + else if (verb == QStringLiteral ("modulation") && args.size () >= 2) + { + server_.send_text (QStringLiteral ("modulation:%1,%2") + .arg (args.at (0), args.at (1))); + } + else if (verb == QStringLiteral ("split_enable")) + { + auto const enabled = args.size () >= 2 ? args.at (1) : args.value (0); + server_.send_text (QStringLiteral ("split_enable:0,%1").arg (enabled)); + } + else if (verb == QStringLiteral ("trx") && args.size () >= 2) + { + server_.send_text (QStringLiteral ("trx:%1,%2") + .arg (args.at (0), args.at (1))); + } + else if (verb == QStringLiteral ("rx_enable") && args.size () >= 2) + { + server_.send_text (QStringLiteral ("rx_enable:%1,%2") + .arg (args.at (0), args.at (1))); + } + else if (verb == QStringLiteral ("start") || verb == QStringLiteral ("stop")) + { + server_.send_text (verb); + } + } + + TciSimServer server_; + Transceiver::logger_type logger_; + RigFactory factory_; + std::unique_ptr<Transceiver> rig_; + CommandHandler command_handler_; + QVector<StateObservation> observations_; + QStringList failures_; + State state_; + bool tearing_down_ {false}; + }; + + State state_from (RigHarness const& harness) + { + auto state = harness.state (); + state.online (true); + return state; + } +} + +// The TCI object references application-owned DSP globals through wsjt_qt. +dec_data_t& dec_data = test_dec_data; +int volatile itone[MAX_NUM_SYMBOLS] {}; +int volatile icw[NUM_CW_SYMBOLS] {}; + +float gran () +{ + return 0.0f; +} + +class TestTciTransceiverCharacterization final + : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase () + { + Logger::disable (); + qRegisterMetaType<Transceiver::TransceiverState> (); + } + + void startup_adopts_greeting_and_preserves_framing () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + + auto const& server = harness.server (); + QCOMPARE (server.connection_count (), 1); + QCOMPARE (harness.state ().frequency (), initial_frequency); + QCOMPARE (harness.state ().tx_frequency (), Frequency {0}); + QCOMPARE (harness.state ().mode (), Transceiver::DIG_U); + QVERIFY (!harness.state ().split ()); + + auto const& frames = server.frames (); + QVERIFY (!frames.isEmpty ()); + QCOMPARE (frames.first ().raw, + TciSimScript::greeting_messages (TciSimGreeting::Thetis).join (';') + + ';'); + + auto const device = message_index (server, 0, Direction::ServerToClient, + QStringLiteral ("device")); + auto const rx_vfo = message_index (server, device + 1, Direction::ServerToClient, + QStringLiteral ("vfo")); + auto const mode = message_index (server, rx_vfo + 1, Direction::ServerToClient, + QStringLiteral ("modulation")); + auto const ready = message_index (server, mode + 1, Direction::ServerToClient, + QStringLiteral ("ready")); + QVERIFY2 (device >= 0 && rx_vfo > device && mode > rx_vfo + && ready > mode, + qPrintable (harness.diagnostics ())); + } + + void rx_vfo_acknowledgement_precedes_dependent_mode () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + + Frequency constexpr target {14074100}; + auto const operation_start = harness.server ().transcript ().size (); + harness.set_command_handler ( + [&harness] (QString const& verb, QStringList const& args, int) + { + if (verb == QStringLiteral ("vfo") && args == QStringList {"0", "0", "14074100"}) + { + harness.server ().send_text_later ( + QStringLiteral ("unexpected:payload;vfo:1,0,14074100"), 5); + harness.server ().send_text_later (QStringLiteral ("vfo:0,0,14074100"), 30); + return true; + } + return false; + }); + + auto requested = state_from (harness); + requested.frequency (target); + requested.mode (Transceiver::USB); + auto const update_cursor = harness.set (requested, 10); + QVERIFY2 (harness.wait_for_state ( + update_cursor, 10, + [] (State const& state) + { + return state.frequency () == target && state.mode () == Transceiver::USB; + }), qPrintable (harness.diagnostics ())); + + auto const& server = harness.server (); + auto const vfo_command = message_index ( + server, operation_start, Direction::ClientToServer, QStringLiteral ("vfo"), + [] (Message const& message) {return has_args (message, {"0", "0", "14074100"});}); + auto const vfo_ack = message_index ( + server, vfo_command + 1, Direction::ServerToClient, QStringLiteral ("vfo"), + [] (Message const& message) {return has_args (message, {"0", "0", "14074100"});}); + auto const mode_command = message_index ( + server, operation_start, Direction::ClientToServer, QStringLiteral ("modulation"), + [] (Message const& message) {return has_args (message, {"0", "usb"});}); + QVERIFY2 (vfo_command >= 0 && vfo_ack > vfo_command && mode_command > vfo_ack, + qPrintable (harness.diagnostics ())); + QCOMPARE (harness.state ().frequency (), target); + QCOMPARE (harness.state ().mode (), Transceiver::USB); + + auto const vfo_count = server.count (Direction::ClientToServer, + QStringLiteral ("vfo")); + auto const mode_count = server.count (Direction::ClientToServer, + QStringLiteral ("modulation")); + QTest::qWait (75); + QCOMPARE (server.count (Direction::ClientToServer, QStringLiteral ("vfo")), + vfo_count); + QCOMPARE (server.count (Direction::ClientToServer, + QStringLiteral ("modulation")), mode_count); + } + + void unacknowledged_rx_vfo_fails_boundedly_without_dependent_commands () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + Frequency constexpr target {7074125}; + auto const operation_start = harness.server ().transcript ().size (); + harness.set_command_handler ( + [] (QString const& verb, QStringList const& args, int) + { + return verb == QStringLiteral ("vfo") + && args == QStringList {"0", "0", "7074125"}; + }); + auto requested = state_from (harness); + requested.frequency (target); + requested.mode (Transceiver::USB); + + QElapsedTimer deadline; + deadline.start (); + harness.set (requested, 20); + QVERIFY2 (harness.wait_for_failure (failure_cursor), + qPrintable (harness.diagnostics ())); + + auto const& server = harness.server (); + auto const attempts = server.messages (Direction::ClientToServer, + QStringLiteral ("vfo")); + int matching_attempts {0}; + for (auto const& attempt : attempts) + { + if (attempt.ordinal < static_cast<quint64> (operation_start)) continue; + QVERIFY2 (has_args (attempt, {"0", "0", "7074125"}), + qPrintable (harness.diagnostics ())); + ++matching_attempts; + } + QVERIFY2 (matching_attempts >= 1, qPrintable (harness.diagnostics ())); + QCOMPARE (message_index (server, operation_start, Direction::ClientToServer, + QStringLiteral ("modulation")), -1); + QVERIFY (deadline.elapsed () < 6000); + QVERIFY (harness.failure_count () - failure_cursor <= 1); + QVERIFY (harness.wait_for_current_state ( + [] (State const& state) {return !state.online ();})); + + auto const attempts_after_failure = matching_attempts; + QTest::qWait (50); + int attempts_after_wait {0}; + for (auto const& attempt : server.messages (Direction::ClientToServer, + QStringLiteral ("vfo"))) + { + if (attempt.ordinal >= static_cast<quint64> (operation_start) + && has_args (attempt, {"0", "0", "7074125"})) + { + ++attempts_after_wait; + } + } + QCOMPARE (attempts_after_wait, attempts_after_failure); + } + + void split_and_tx_vfo_settle_before_ptt () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + + Frequency constexpr tx_frequency {14076000}; + auto const operation_start = harness.server ().transcript ().size (); + struct AcknowledgementState + { + bool split_scheduled {false}; + bool split_sent {false}; + bool tx_vfo_scheduled {false}; + bool tx_vfo_sent {false}; + bool ptt_before_prerequisites {false}; + }; + auto const acknowledgements = std::make_shared<AcknowledgementState> (); + harness.set_command_handler ( + [&harness, acknowledgements] (QString const& verb, + QStringList const& args, int) + { + if (verb == QStringLiteral ("split_enable") + && args == QStringList {"0", "true"}) + { + if (!acknowledgements->split_scheduled + && !acknowledgements->split_sent) + { + acknowledgements->split_scheduled = true; + QTimer::singleShot ( + 25, &harness.server (), + [&harness, acknowledgements] + { + acknowledgements->split_sent = true; + harness.server ().send_text ( + QStringLiteral ("split_enable:0,true")); + }); + } + return !acknowledgements->split_sent; + } + if (verb == QStringLiteral ("vfo") + && args == QStringList {"0", "1", "14076000"}) + { + if (!acknowledgements->tx_vfo_scheduled + && !acknowledgements->tx_vfo_sent) + { + acknowledgements->tx_vfo_scheduled = true; + QTimer::singleShot ( + 25, &harness.server (), + [&harness, acknowledgements] + { + acknowledgements->tx_vfo_sent = true; + harness.server ().send_text ( + QStringLiteral ("vfo:0,1,14076000")); + }); + } + return !acknowledgements->tx_vfo_sent; + } + if (verb == QStringLiteral ("trx") + && args == QStringList {"0", "true"}) + { + acknowledgements->ptt_before_prerequisites = + acknowledgements->ptt_before_prerequisites + || !acknowledgements->split_sent + || !acknowledgements->tx_vfo_sent; + } + return false; + }); + auto requested = state_from (harness); + requested.tx_frequency (tx_frequency); + requested.split (true); + requested.ptt (true); + auto const update_cursor = harness.set (requested, 30); + QVERIFY2 (harness.wait_for_state ( + update_cursor, 30, + [] (State const& state) + { + return state.split () && state.tx_frequency () == tx_frequency + && state.ptt (); + }), qPrintable (harness.diagnostics ())); + + auto const& server = harness.server (); + auto const split_command = message_index ( + server, operation_start, Direction::ClientToServer, + QStringLiteral ("split_enable"), + [] (Message const& message) {return has_args (message, {"0", "true"});}); + auto const split_ack = message_index ( + server, operation_start, Direction::ServerToClient, QStringLiteral ("split_enable"), + [] (Message const& message) {return has_args (message, {"0", "true"});}); + auto const tx_vfo_command = message_index ( + server, operation_start, Direction::ClientToServer, QStringLiteral ("vfo"), + [] (Message const& message) + { + return has_args (message, {"0", "1", "14076000"}); + }); + auto const tx_vfo_ack = message_index ( + server, operation_start, Direction::ServerToClient, QStringLiteral ("vfo"), + [] (Message const& message) {return has_args (message, {"0", "1", "14076000"});}); + auto const ptt_command = message_index ( + server, operation_start, Direction::ClientToServer, QStringLiteral ("trx"), + [] (Message const& message) {return message.args.size () >= 2 + && message.args.at (0) == "0" + && message.args.at (1) == "true";}); + QVERIFY2 (!acknowledgements->ptt_before_prerequisites && split_command >= 0 + && split_ack > split_command && tx_vfo_command >= 0 + && tx_vfo_ack > tx_vfo_command && ptt_command > split_ack + && ptt_command > tx_vfo_ack, + qPrintable (harness.diagnostics ())); + QVERIFY (harness.state ().split ()); + QCOMPARE (harness.state ().tx_frequency (), tx_frequency); + QVERIFY (harness.state ().ptt ()); + } + + void unsolicited_split_divergence_converges_without_ptt () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + + auto requested = state_from (harness); + requested.tx_frequency (14076050); + requested.split (true); + auto const setup_cursor = harness.set (requested, 35); + QVERIFY2 (harness.wait_for_state ( + setup_cursor, 35, + [] (State const& state) {return state.split ();}), + qPrintable (harness.diagnostics ())); + QVERIFY (harness.state ().split ()); + + auto const operation_start = harness.server ().transcript ().size (); + auto const observation_cursor = harness.observation_count (); + harness.server ().send_text (QStringLiteral ("split_enable:0,false")); + + QVERIFY (harness.server ().wait_for ( + [&harness, operation_start, observation_cursor] + { + return message_index ( + harness.server (), operation_start, Direction::ClientToServer, + QStringLiteral ("split_enable"), + [] (Message const& message) {return has_args (message, {"0", "true"});}) + >= 0 + || harness.observed_state_since ( + observation_cursor, + [] (State const& state) {return !state.split ();}); + }, 1000)); + + auto const correction = message_index ( + harness.server (), operation_start, Direction::ClientToServer, + QStringLiteral ("split_enable"), + [] (Message const& message) {return has_args (message, {"0", "true"});}); + if (correction >= 0) + { + QVERIFY (harness.server ().wait_for ( + [&harness] {return harness.state ().split ();}, 1000)); + } + else + { + QVERIFY2 (!harness.state ().split (), + qPrintable (harness.diagnostics ())); + } + QCOMPARE (message_index (harness.server (), operation_start, + Direction::ClientToServer, + QStringLiteral ("trx")), -1); + } + + void explicit_stop_can_restart_on_a_new_connection_generation () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const first_generation = harness.server ().connection_generation (); + + QVERIFY2 (harness.stop (), qPrintable (harness.diagnostics ())); + QVERIFY2 (harness.restart (41), qPrintable (harness.diagnostics ())); + + QVERIFY (harness.server ().connection_generation () > first_generation); + auto const second_generation = harness.server ().connection_generation (); + QVERIFY (harness.state ().online ()); + QCOMPARE (harness.state ().frequency (), initial_frequency); + + auto requested = state_from (harness); + requested.frequency (14074125); + auto const update_cursor = harness.set (requested, 42); + QVERIFY2 (harness.wait_for_state ( + update_cursor, 42, + [] (State const& state) {return state.frequency () == 14074125;}), + qPrintable (harness.diagnostics ())); + QCOMPARE (harness.state ().frequency (), Frequency {14074125}); + auto const fresh_command = message_index ( + harness.server (), 0, Direction::ClientToServer, QStringLiteral ("vfo"), + [second_generation] (Message const& message) + { + return message.connection_generation == second_generation + && has_args (message, {"0", "0", "14074125"}); + }); + QVERIFY2 (fresh_command >= 0, qPrintable (harness.diagnostics ())); + } + + void in_flight_disconnect_is_bounded () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + harness.set_command_handler ( + [&harness] (QString const& verb, QStringList const& args, int) + { + if (verb != QStringLiteral ("vfo") + || args != QStringList {"0", "0", "14074150"}) return false; + QTimer::singleShot (0, &harness.server (), + [&harness] {harness.server ().close_client ();}); + return true; + }); + auto requested = state_from (harness); + requested.frequency (14074150); + + QElapsedTimer deadline; + deadline.start (); + harness.set (requested, 42); + QVERIFY (harness.server ().wait_for ( + [&harness] {return harness.server ().client_disconnected ();}, 1000)); + + harness.set_command_handler ({}); + QVERIFY2 (harness.stop (), qPrintable (harness.diagnostics ())); + QVERIFY (deadline.elapsed () < 8000); + QVERIFY (harness.failure_count () - failure_cursor <= 1); + } + + void unexpected_stale_and_duplicate_messages_leave_coherent_state () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + Frequency constexpr target {14074200}; + auto const operation_start = harness.server ().transcript ().size (); + bool injected {false}; + harness.set_command_handler ( + [&harness, &injected] (QString const& verb, QStringList const& args, int) + { + if (injected || verb != QStringLiteral ("vfo") + || args != QStringList {"0", "0", "14074200"}) return false; + injected = true; + harness.server ().send_text ( + QStringLiteral ("unexpected:payload;vfo:1,0,not-a-frequency")); + harness.server ().send_text_later (QStringLiteral ("vfo:0,0,14074199"), 10); + harness.server ().send_text_later ( + QStringLiteral ("vfo:0,0,14074200;vfo:0,0,14074200"), 25); + return true; + }); + auto requested = state_from (harness); + requested.frequency (target); + harness.set (requested, 50); + + QVERIFY (harness.server ().wait_for ( + [&harness] + { + int correct_acks {0}; + for (auto const& message : harness.server ().messages ( + Direction::ServerToClient, QStringLiteral ("vfo"))) + { + if (has_args (message, {"0", "0", "14074200"})) ++correct_acks; + } + return correct_acks == 2; + }, 1000)); + QCOMPARE (harness.failure_count (), failure_cursor); + QVERIFY (harness.wait_for_current_state ( + [] (State const& state) {return state.frequency () == target;})); + QCOMPARE (harness.state ().frequency (), target); + + int requested_attempts {0}; + for (auto const& message : harness.server ().messages ( + Direction::ClientToServer, QStringLiteral ("vfo"))) + { + if (message.ordinal >= static_cast<quint64> (operation_start) + && has_args (message, {"0", "0", "14074200"})) + { + ++requested_attempts; + } + } + QVERIFY (requested_attempts >= 1); + } + + void reentrant_duplicate_request_is_bounded_and_coherent () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + Frequency constexpr target {14074250}; + auto requested = state_from (harness); + requested.frequency (target); + bool reentered {false}; + harness.set_command_handler ( + [&harness, &reentered, requested] (QString const& verb, + QStringList const& args, int) + { + if (reentered || verb != QStringLiteral ("vfo") + || args != QStringList {"0", "0", "14074250"}) return false; + reentered = true; + harness.schedule_set (requested, 61); + harness.server ().send_text_later (QStringLiteral ("vfo:0,0,14074250"), 25); + return true; + }); + + auto const reentrant_cursor = harness.observation_count (); + harness.set_now (requested, 60); + QCOMPARE (harness.failure_count (), failure_cursor); + QCOMPARE (harness.state ().frequency (), target); + QVERIFY (reentered); + QVERIFY2 (harness.observed_state_since ( + reentrant_cursor, 61, + [] (State const& state) {return state.frequency () == target;}), + qPrintable (harness.diagnostics ())); + } + + void reentrant_superseding_request_remains_recoverable () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + Frequency constexpr first_target {14074300}; + Frequency constexpr latest_target {14074350}; + auto first = state_from (harness); + first.frequency (first_target); + auto latest = first; + latest.frequency (latest_target); + bool reentered {false}; + harness.set_command_handler ( + [&harness, &reentered, latest] (QString const& verb, + QStringList const& args, int) + { + if (reentered || verb != QStringLiteral ("vfo") + || args != QStringList {"0", "0", "14074300"}) return false; + reentered = true; + harness.schedule_set (latest, 71); + harness.server ().send_text_later (QStringLiteral ("vfo:0,0,14074300"), 25); + return true; + }); + + auto const reentrant_cursor = harness.observation_count (); + harness.set_now (first, 70); + auto const settled = harness.state ().frequency (); + QVERIFY (settled == first_target || settled == latest_target); + QCOMPARE (harness.failure_count (), failure_cursor); + QVERIFY2 (harness.observed_state_since ( + reentrant_cursor, 71, + [] (State const&) {return true;}), + qPrintable (harness.diagnostics ())); + + harness.set_now (latest, 72); + QCOMPARE (harness.failure_count (), failure_cursor); + QCOMPARE (harness.state ().frequency (), latest_target); + QVERIFY (reentered); + } +}; + +QTEST_GUILESS_MAIN (TestTciTransceiverCharacterization) + +#include "test_tci_transceiver_characterization.moc" diff --git a/tests/unit/tci/test_transceiver_base_period.cpp b/tests/unit/tci/test_transceiver_base_period.cpp new file mode 100644 index 00000000..976e6651 --- /dev/null +++ b/tests/unit/tci/test_transceiver_base_period.cpp @@ -0,0 +1,164 @@ +#include "Transceiver/TransceiverBase.hpp" + +#include <stdexcept> + +#include <boost/log/keywords/channel.hpp> + +#include <QSignalSpy> +#include <QtTest> + +namespace +{ + class PeriodRecordingTransceiver final + : public TransceiverBase + { + public: + explicit PeriodRecordingTransceiver (logger_type * logger) + : TransceiverBase {logger, nullptr} + { + } + + QVector<double> applied_periods; + QStringList events; + double backend_period {15.0}; + bool fail_next_period {false}; + + protected: + int do_start () override {return 0;} + void do_stop () override {backend_period = 15.0;} + void do_frequency (Frequency, MODE, bool) override {} + void do_tx_frequency (Frequency, MODE, bool) override {} + void do_mode (MODE) override {} + void do_ptt (bool) override {} + + void do_period (double period) override + { + events.append (QStringLiteral ("period")); + if (fail_next_period) + { + fail_next_period = false; + throw std::runtime_error {"period rejected"}; + } + backend_period = period; + applied_periods.append (period); + } + + void do_modulator_start (TxEvidence::TxRequest const&) override + { + events.append (QStringLiteral ("modulator")); + } + }; + + Transceiver::TransceiverState online_state () + { + Transceiver::TransceiverState state; + state.online (true); + return state; + } +} + +class TestTransceiverBasePeriod final + : public QObject +{ + Q_OBJECT + +private slots: + void initial_period_is_applied_even_when_it_matches_state_default () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + QVector<double> expected {120.0}; + + rig.set (online_state (), 1); + + QCOMPARE (rig.applied_periods, expected); + QCOMPARE (rig.backend_period, 120.0); + } + + void unchanged_period_is_not_reapplied () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + auto state = online_state (); + QVector<double> expected {120.0}; + + rig.set (state, 1); + rig.set (state, 2); + + QCOMPARE (rig.applied_periods, expected); + } + + void changed_period_is_applied_once () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + auto state = online_state (); + QVector<double> expected {120.0, 15.0}; + + rig.set (state, 1); + state.period (15.0); + rig.set (state, 2); + rig.set (state, 3); + + QCOMPARE (rig.applied_periods, expected); + QCOMPARE (rig.backend_period, 15.0); + } + + void period_is_reapplied_after_restart () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + auto state = online_state (); + QVector<double> expected {120.0, 120.0}; + + rig.set (state, 1); + rig.stop (); + rig.start (2); + state = online_state (); + rig.set (state, 3); + + QCOMPARE (rig.applied_periods, expected); + QCOMPARE (rig.backend_period, 120.0); + } + + void period_is_applied_before_modulator_start () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + auto state = online_state (); + QStringList expected {QStringLiteral ("period"), + QStringLiteral ("modulator")}; + state.tx_audio (true); + + rig.set (state, 1); + + QCOMPARE (rig.events, expected); + } + + void failed_period_is_retried () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + QSignalSpy failures {&rig, &Transceiver::failure}; + auto state = online_state (); + QVector<double> expected {120.0}; + rig.fail_next_period = true; + + rig.set (state, 1); + rig.set (state, 2); + + QCOMPARE (failures.count (), 1); + QCOMPARE (rig.applied_periods, expected); + QCOMPARE (rig.backend_period, 120.0); + } +}; + +QTEST_GUILESS_MAIN (TestTransceiverBasePeriod) + +#include "test_transceiver_base_period.moc" |
