summaryrefslogtreecommitdiff
path: root/tests/unit/common
diff options
context:
space:
mode:
Diffstat (limited to 'tests/unit/common')
-rw-r--r--tests/unit/common/CMakeLists.txt303
-rw-r--r--tests/unit/common/QsoReactionTestSupport.hpp71
-rw-r--r--tests/unit/common/test_active_station_list.cpp67
-rw-r--r--tests/unit/common/test_active_stations.cpp86
-rw-r--r--tests/unit/common/test_auto_respond_period.cpp217
-rw-r--r--tests/unit/common/test_auto_respond_scoring.cpp65
-rw-r--r--tests/unit/common/test_auto_respond_selection_latch.cpp36
-rw-r--r--tests/unit/common/test_auto_sequence_reaction.cpp203
-rw-r--r--tests/unit/common/test_beacon_tx_controller.cpp586
-rw-r--r--tests/unit/common/test_callsign_validator.cpp48
-rw-r--r--tests/unit/common/test_configuration_dialog_layout.cpp521
-rw-r--r--tests/unit/common/test_decode_output_plan.cpp1146
-rw-r--r--tests/unit/common/test_decoded_message_fields.cpp58
-rw-r--r--tests/unit/common/test_decoded_message_reaction.cpp385
-rw-r--r--tests/unit/common/test_decoded_time.cpp54
-rw-r--r--tests/unit/common/test_displaytext.cpp397
-rw-r--r--tests/unit/common/test_emulate_split_transceiver.cpp129
-rw-r--r--tests/unit/common/test_fox_guard_bands.cpp92
-rw-r--r--tests/unit/common/test_fox_operator_actions.cpp124
-rw-r--r--tests/unit/common/test_frequency_editors.cpp273
-rw-r--r--tests/unit/common/test_hamlib_mode.cpp78
-rw-r--r--tests/unit/common/test_hamlib_vfo_role_state.cpp83
-rw-r--r--tests/unit/common/test_highlighting_rules.cpp86
-rw-r--r--tests/unit/common/test_hound_transmission_policy.cpp179
-rw-r--r--tests/unit/common/test_http_user_agent.cpp53
-rw-r--r--tests/unit/common/test_livecq_callsign.cpp39
-rw-r--r--tests/unit/common/test_mainwindow_compact_controls.cpp114
-rw-r--r--tests/unit/common/test_operating_frequency.cpp211
-rw-r--r--tests/unit/common/test_qso_reaction.cpp712
-rw-r--r--tests/unit/common/test_qsy_message_parser.cpp316
-rw-r--r--tests/unit/common/test_qt_helpers.cpp586
-rw-r--r--tests/unit/common/test_rig_frequency_change_policy.cpp246
-rw-r--r--tests/unit/common/test_round_robin_selection.cpp103
-rw-r--r--tests/unit/common/test_rr73_policy.cpp43
-rw-r--r--tests/unit/common/test_spec_op_label.cpp55
-rw-r--r--tests/unit/common/test_superfox_tx_planner.cpp125
-rw-r--r--tests/unit/common/test_tx_inhibit_transceiver.cpp485
-rw-r--r--tests/unit/common/test_tx_start_policy.cpp108
-rw-r--r--tests/unit/common/test_wait_feature_policy.cpp162
-rw-r--r--tests/unit/common/test_waterfall_scale.cpp267
-rw-r--r--tests/unit/common/test_wf_palette.cpp113
41 files changed, 9025 insertions, 0 deletions
diff --git a/tests/unit/common/CMakeLists.txt b/tests/unit/common/CMakeLists.txt
new file mode 100644
index 00000000..770aa0ec
--- /dev/null
+++ b/tests/unit/common/CMakeLists.txt
@@ -0,0 +1,303 @@
+add_executable (test_qt_helpers
+ test_qt_helpers.cpp
+ ${CMAKE_SOURCE_DIR}/qt_helpers.cpp
+)
+target_include_directories (test_qt_helpers PRIVATE ${CMAKE_BINARY_DIR})
+target_link_libraries (test_qt_helpers Qt5::Test Qt5::Network Qt5::Widgets)
+add_test (NAME test_qt_helpers COMMAND test_qt_helpers)
+
+add_executable (test_callsign_validator
+ test_callsign_validator.cpp
+ ${CMAKE_SOURCE_DIR}/validators/CallsignValidator.cpp
+)
+target_link_libraries (test_callsign_validator Qt5::Test Qt5::Gui)
+add_test (NAME test_callsign_validator COMMAND test_callsign_validator)
+
+add_executable (test_livecq_callsign
+ test_livecq_callsign.cpp
+)
+target_link_libraries (test_livecq_callsign wsjt_qt Qt5::Test)
+add_test (NAME test_livecq_callsign COMMAND test_livecq_callsign)
+
+add_executable (test_decoded_message_fields test_decoded_message_fields.cpp)
+target_link_libraries (test_decoded_message_fields wsjt_qt wsjt_fort_common Qt5::Test)
+add_test (NAME test_decoded_message_fields COMMAND test_decoded_message_fields)
+
+add_executable (test_decoded_time
+ test_decoded_time.cpp
+ ${CMAKE_SOURCE_DIR}/Network/DecodedTime.cpp
+)
+target_link_libraries (test_decoded_time Qt5::Test)
+add_test (NAME test_decoded_time COMMAND test_decoded_time)
+
+add_executable (test_displaytext
+ test_displaytext.cpp
+ ${CMAKE_SOURCE_DIR}/widgets/displaytext.cpp
+)
+target_link_libraries (test_displaytext wsjt_qt wsjt_fort_common Qt5::Test)
+add_test (NAME test_displaytext COMMAND test_displaytext)
+
+add_executable (test_fox_operator_actions
+ test_fox_operator_actions.cpp
+)
+target_link_libraries (test_fox_operator_actions Qt5::Test)
+add_test (NAME test_fox_operator_actions COMMAND test_fox_operator_actions)
+
+add_executable (test_wf_palette
+ test_wf_palette.cpp
+)
+target_link_libraries (test_wf_palette wsjt_qt Qt5::Test)
+add_test (NAME test_wf_palette COMMAND test_wf_palette)
+
+add_executable (test_waterfall_scale
+ test_waterfall_scale.cpp
+)
+target_link_libraries (test_waterfall_scale Qt5::Test)
+add_test (NAME test_waterfall_scale COMMAND test_waterfall_scale)
+
+add_executable (test_http_user_agent
+ test_http_user_agent.cpp
+ )
+target_link_libraries (test_http_user_agent wsjt_qt Qt5::Test)
+add_test (NAME test_http_user_agent COMMAND test_http_user_agent)
+
+add_executable (test_fox_guard_bands
+ test_fox_guard_bands.cpp
+ ${CMAKE_SOURCE_DIR}/FoxGuardBands.cpp
+)
+target_link_libraries (test_fox_guard_bands Qt5::Test)
+add_test (NAME test_fox_guard_bands COMMAND test_fox_guard_bands)
+
+add_executable (test_highlighting_rules
+ test_highlighting_rules.cpp
+ ${CMAKE_SOURCE_DIR}/HighlightingRules.cpp
+)
+target_link_libraries (test_highlighting_rules Qt5::Test)
+add_test (NAME test_highlighting_rules COMMAND test_highlighting_rules)
+
+add_executable (test_tx_start_policy
+ test_tx_start_policy.cpp
+)
+target_link_libraries (test_tx_start_policy Qt5::Test)
+add_test (NAME test_tx_start_policy COMMAND test_tx_start_policy)
+
+add_executable (test_beacon_tx_controller
+ test_beacon_tx_controller.cpp
+ ${CMAKE_SOURCE_DIR}/BeaconTxController.cpp
+)
+target_link_libraries (test_beacon_tx_controller Qt5::Test)
+add_test (NAME test_beacon_tx_controller COMMAND test_beacon_tx_controller)
+
+add_executable (test_round_robin_selection
+ test_round_robin_selection.cpp
+ ${CMAKE_SOURCE_DIR}/widgets/RoundRobinSelection.cpp
+ ${CMAKE_SOURCE_DIR}/BeaconTxController.cpp
+)
+target_link_libraries (test_round_robin_selection Qt5::Test Qt5::Widgets)
+add_test (NAME test_round_robin_selection COMMAND test_round_robin_selection)
+set_tests_properties (test_round_robin_selection PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
+
+add_executable (test_rig_frequency_change_policy
+ test_rig_frequency_change_policy.cpp
+)
+target_link_libraries (test_rig_frequency_change_policy Qt5::Test)
+add_test (NAME test_rig_frequency_change_policy COMMAND test_rig_frequency_change_policy)
+
+add_executable (test_wait_feature_policy
+ test_wait_feature_policy.cpp
+)
+target_link_libraries (test_wait_feature_policy Qt5::Test)
+add_test (NAME test_wait_feature_policy COMMAND test_wait_feature_policy)
+
+add_executable (test_superfox_tx_planner
+ test_superfox_tx_planner.cpp
+ ${CMAKE_SOURCE_DIR}/SuperFoxTxPlanner.cpp
+)
+target_link_libraries (test_superfox_tx_planner Qt5::Test)
+add_test (NAME test_superfox_tx_planner COMMAND test_superfox_tx_planner)
+
+add_executable (test_auto_respond_selection_latch
+ test_auto_respond_selection_latch.cpp
+ ${CMAKE_SOURCE_DIR}/AutoRespondSelectionLatch.cpp
+)
+target_link_libraries (test_auto_respond_selection_latch Qt5::Test)
+add_test (NAME test_auto_respond_selection_latch COMMAND test_auto_respond_selection_latch)
+
+add_executable (test_auto_respond_scoring
+ test_auto_respond_scoring.cpp
+)
+target_link_libraries (test_auto_respond_scoring Qt5::Test)
+add_test (NAME test_auto_respond_scoring COMMAND test_auto_respond_scoring)
+
+add_executable (test_auto_respond_period
+ test_auto_respond_period.cpp
+ ${CMAKE_SOURCE_DIR}/AutoRespondPeriod.cpp
+)
+target_link_libraries (test_auto_respond_period wsjt_qt wsjt_fort_common Qt5::Test)
+add_test (NAME test_auto_respond_period COMMAND test_auto_respond_period)
+
+add_executable (test_emulate_split_transceiver
+ test_emulate_split_transceiver.cpp
+ ${CMAKE_SOURCE_DIR}/Transceiver/EmulateSplitTransceiver.cpp
+ ${CMAKE_SOURCE_DIR}/Transceiver/Transceiver.cpp
+ ${CMAKE_SOURCE_DIR}/qt_helpers.cpp
+)
+target_include_directories (test_emulate_split_transceiver PRIVATE ${CMAKE_BINARY_DIR})
+target_link_libraries (test_emulate_split_transceiver Boost::log Qt5::Test Qt5::Network Qt5::Widgets)
+add_test (NAME test_emulate_split_transceiver COMMAND test_emulate_split_transceiver)
+
+add_executable (test_tx_inhibit_transceiver
+ test_tx_inhibit_transceiver.cpp
+ ${CMAKE_SOURCE_DIR}/Transceiver/TxInhibitTransceiver.cpp
+ ${CMAKE_SOURCE_DIR}/Transceiver/TransceiverBase.cpp
+ ${CMAKE_SOURCE_DIR}/Transceiver/Transceiver.cpp
+ ${CMAKE_SOURCE_DIR}/qt_helpers.cpp
+)
+target_include_directories (test_tx_inhibit_transceiver PRIVATE ${CMAKE_BINARY_DIR})
+target_link_libraries (test_tx_inhibit_transceiver Boost::log Qt5::Test Qt5::Network Qt5::Widgets)
+add_test (NAME test_tx_inhibit_transceiver COMMAND test_tx_inhibit_transceiver)
+
+add_executable (test_hamlib_mode
+ test_hamlib_mode.cpp
+)
+target_link_libraries (test_hamlib_mode wsjt_qt Qt5::Test)
+add_test (NAME test_hamlib_mode COMMAND test_hamlib_mode)
+
+add_executable (test_hamlib_vfo_role_state
+ test_hamlib_vfo_role_state.cpp
+)
+target_link_libraries (test_hamlib_vfo_role_state Hamlib::Hamlib Qt5::Test)
+add_test (NAME test_hamlib_vfo_role_state COMMAND test_hamlib_vfo_role_state)
+
+add_executable (test_active_station_list
+ test_active_station_list.cpp
+ ${CMAKE_SOURCE_DIR}/ActiveStationList.cpp
+)
+target_link_libraries (test_active_station_list Qt5::Test)
+add_test (NAME test_active_station_list COMMAND test_active_station_list)
+
+add_executable (test_frequency_editors
+ test_frequency_editors.cpp
+ ${CMAKE_SOURCE_DIR}/Logger.cpp
+)
+target_link_libraries (test_frequency_editors wsjt_qt Boost::log_setup Qt5::Test Qt5::Widgets)
+add_test (NAME test_frequency_editors COMMAND test_frequency_editors)
+
+add_executable (test_decoded_message_reaction
+ test_decoded_message_reaction.cpp
+)
+target_link_libraries (test_decoded_message_reaction wsjt_qt wsjt_fort_common Qt5::Test)
+add_test (NAME test_decoded_message_reaction COMMAND test_decoded_message_reaction)
+
+add_executable (test_decode_output_plan
+ test_decode_output_plan.cpp
+)
+target_link_libraries (test_decode_output_plan wsjt_qt wsjt_fort_common Qt5::Test)
+add_test (NAME test_decode_output_plan COMMAND test_decode_output_plan)
+
+add_executable (test_auto_sequence_reaction
+ test_auto_sequence_reaction.cpp
+)
+target_link_libraries (test_auto_sequence_reaction wsjt_qt wsjt_fort_common Qt5::Test)
+add_test (NAME test_auto_sequence_reaction COMMAND test_auto_sequence_reaction)
+
+add_executable (test_rr73_policy
+ test_rr73_policy.cpp
+ ${CMAKE_SOURCE_DIR}/Rr73Policy.cpp
+)
+target_link_libraries (test_rr73_policy Qt5::Test)
+add_test (NAME test_rr73_policy COMMAND test_rr73_policy)
+
+add_executable (test_qso_reaction
+ test_qso_reaction.cpp
+)
+target_link_libraries (test_qso_reaction wsjt_qt wsjt_fort_common Qt5::Test)
+add_test (NAME test_qso_reaction COMMAND test_qso_reaction)
+
+add_executable (test_hound_transmission_policy
+ test_hound_transmission_policy.cpp
+ ${CMAKE_SOURCE_DIR}/HoundTransmissionPolicy.cpp
+)
+target_link_libraries (test_hound_transmission_policy Qt5::Test)
+add_test (NAME test_hound_transmission_policy COMMAND test_hound_transmission_policy)
+
+add_executable (test_qsy_message_parser
+ test_qsy_message_parser.cpp
+ ${CMAKE_SOURCE_DIR}/widgets/QSYMessageParser.cpp
+)
+target_link_libraries (test_qsy_message_parser Qt5::Test)
+add_test (NAME test_qsy_message_parser COMMAND test_qsy_message_parser)
+
+add_executable (test_spec_op_label
+ test_spec_op_label.cpp
+ ${CMAKE_SOURCE_DIR}/widgets/SpecOpLabel.cpp
+)
+target_link_libraries (test_spec_op_label Qt5::Test)
+add_test (NAME test_spec_op_label COMMAND test_spec_op_label)
+
+qt5_wrap_ui (test_active_stations_UIS ${CMAKE_SOURCE_DIR}/widgets/activeStations.ui)
+add_executable (test_active_stations
+ test_active_stations.cpp
+ ${CMAKE_SOURCE_DIR}/widgets/activeStations.cpp
+ ${test_active_stations_UIS}
+)
+target_include_directories (test_active_stations PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+target_link_libraries (test_active_stations wsjt_qt Qt5::Test Qt5::Widgets)
+add_test (NAME test_active_stations COMMAND test_active_stations)
+set_tests_properties (test_active_stations PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
+
+if (WSJT_ENABLE_TSAN)
+ # These tests exercise Qt GUI classes but do not test the window-system
+ # integration. Offscreen QPA avoids Arch xcb/DBus startup reports while
+ # preserving the tests' widget and event-loop behavior.
+ set_tests_properties (
+ test_qt_helpers
+ test_displaytext
+ test_wf_palette
+ test_emulate_split_transceiver
+ test_hamlib_mode
+ test_frequency_editors
+ test_decoded_message_reaction
+ test_decode_output_plan
+ test_auto_sequence_reaction
+ test_qso_reaction
+ PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
+endif ()
+qt5_wrap_ui (test_configuration_dialog_layout_UIS
+ ${CMAKE_SOURCE_DIR}/Configuration.ui
+)
+add_executable (test_configuration_dialog_layout
+ test_configuration_dialog_layout.cpp
+ ${test_configuration_dialog_layout_UIS}
+)
+target_include_directories (test_configuration_dialog_layout PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+target_link_libraries (test_configuration_dialog_layout wsjt_qt Qt5::Test Qt5::Widgets)
+add_test (NAME test_configuration_dialog_layout COMMAND test_configuration_dialog_layout)
+add_test (NAME test_configuration_dialog_layout_fusion COMMAND test_configuration_dialog_layout)
+set_tests_properties (test_configuration_dialog_layout_fusion PROPERTIES
+ ENVIRONMENT "QT_STYLE_OVERRIDE=Fusion"
+)
+add_test (NAME test_configuration_dialog_layout_scaled COMMAND test_configuration_dialog_layout)
+set_tests_properties (test_configuration_dialog_layout_scaled PROPERTIES
+ ENVIRONMENT "QT_ENABLE_HIGHDPI_SCALING=1;QT_SCALE_FACTOR=1.5"
+)
+
+add_executable (test_operating_frequency
+ test_operating_frequency.cpp
+ ${CMAKE_SOURCE_DIR}/OperatingFrequency.cpp
+)
+target_include_directories (test_operating_frequency PRIVATE ${CMAKE_BINARY_DIR})
+target_link_libraries (test_operating_frequency Qt5::Test)
+add_test (NAME test_operating_frequency COMMAND test_operating_frequency)
+
+add_executable (test_mainwindow_compact_controls
+ test_mainwindow_compact_controls.cpp
+ ${CMAKE_SOURCE_DIR}/widgets/TxDriveSlider.cpp
+)
+target_include_directories (test_mainwindow_compact_controls PRIVATE ${CMAKE_SOURCE_DIR})
+target_link_libraries (test_mainwindow_compact_controls Qt5::Test Qt5::Widgets)
+add_test (NAME test_mainwindow_compact_controls COMMAND test_mainwindow_compact_controls)
+add_test (NAME test_mainwindow_compact_controls_scaled COMMAND test_mainwindow_compact_controls)
+set_tests_properties (test_mainwindow_compact_controls_scaled PROPERTIES
+ ENVIRONMENT "QT_ENABLE_HIGHDPI_SCALING=1;QT_SCALE_FACTOR=1.5"
+)
diff --git a/tests/unit/common/QsoReactionTestSupport.hpp b/tests/unit/common/QsoReactionTestSupport.hpp
new file mode 100644
index 00000000..c344ed2a
--- /dev/null
+++ b/tests/unit/common/QsoReactionTestSupport.hpp
@@ -0,0 +1,71 @@
+#ifndef QSOREACTIONTESTSUPPORT_HPP
+#define QSOREACTIONTESTSUPPORT_HPP
+
+#include "DecodedMessageReaction.hpp"
+#include "Decoder/decodedtext.h"
+
+namespace QsoReactionTestSupport
+{
+ using Effect = DecodedMessageReaction::QsoReactionEffect;
+ using Plan = DecodedMessageReaction::QsoReactionPlan;
+ using Snapshot = DecodedMessageReaction::QsoReactionSnapshot;
+
+ inline DecodedText decode(QString const& payload, QString const& marker = "~",
+ QString const& time = "0605", int frequency = 1500)
+ {
+ return DecodedText {
+ QString {"%1 -10 0.3 %2 %3 %4"}
+ .arg(time).arg(frequency, 4, 10, QChar {'0'}).arg(marker).arg(payload)};
+ }
+
+ inline Snapshot neutralStationSnapshot()
+ {
+ Snapshot snapshot;
+ snapshot.myCall = "K1ABC";
+ snapshot.baseCall = "K1ABC";
+ snapshot.dxCall = "W1AW";
+ snapshot.hisCall = "W1AW";
+ snapshot.hisGrid = "FN31";
+ snapshot.trPeriod = 15.0;
+ snapshot.nominalFrequency = 14074000;
+ snapshot.rxFrequency = 1500;
+ snapshot.txFrequency = 1500;
+ return snapshot;
+ }
+
+ inline int effectIndex(Plan const& plan, Effect::Kind kind, int from = 0)
+ {
+ for (int i = from; i < plan.effects.size(); ++i) {
+ if (plan.effects[i].kind == kind) return i;
+ }
+ return -1;
+ }
+
+ inline int effectCount(Plan const& plan, Effect::Kind kind)
+ {
+ int count = 0;
+ for (auto const& effect : plan.effects) {
+ if (effect.kind == kind) ++count;
+ }
+ return count;
+ }
+
+ inline bool hasEffect(Plan const& plan, Effect::Kind kind)
+ {
+ return effectIndex(plan, kind) >= 0;
+ }
+
+ inline int intEffect(Plan const& plan, Effect::Kind kind, int defaultValue = -1)
+ {
+ int const index = effectIndex(plan, kind);
+ return index >= 0 ? plan.effects[index].intValue : defaultValue;
+ }
+
+ inline QString textEffect(Plan const& plan, Effect::Kind kind)
+ {
+ int const index = effectIndex(plan, kind);
+ return index >= 0 ? plan.effects[index].text : QString {};
+ }
+}
+
+#endif // QSOREACTIONTESTSUPPORT_HPP
diff --git a/tests/unit/common/test_active_station_list.cpp b/tests/unit/common/test_active_station_list.cpp
new file mode 100644
index 00000000..b07933fe
--- /dev/null
+++ b/tests/unit/common/test_active_station_list.cpp
@@ -0,0 +1,67 @@
+#include <QtTest>
+
+#include "ActiveStationList.hpp"
+
+class TestActiveStationList : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ void limitsAscendingRows();
+ void limitsDescendingRows();
+ void preservesEqualKeyOrder();
+ void handlesEmptyAndZeroLimit();
+};
+
+void TestActiveStationList::limitsAscendingRows()
+{
+ QVector<ActiveStationListItem> rows;
+ for(int i=59; i>=0; --i) rows.append({float(i), QString::number(i)});
+
+ auto const limited=sorted_limited_active_station_items(rows, 50, false);
+
+ QCOMPARE(limited.size(), 50);
+ QCOMPARE(limited.front().text, QString {"0"});
+ QCOMPARE(limited.back().text, QString {"49"});
+}
+
+void TestActiveStationList::limitsDescendingRows()
+{
+ QVector<ActiveStationListItem> rows;
+ for(int i=0; i<60; ++i) rows.append({float(i), QString::number(i)});
+
+ auto const limited=sorted_limited_active_station_items(rows, 50, true);
+
+ QCOMPARE(limited.size(), 50);
+ QCOMPARE(limited.front().text, QString {"59"});
+ QCOMPARE(limited.back().text, QString {"10"});
+}
+
+void TestActiveStationList::preservesEqualKeyOrder()
+{
+ QVector<ActiveStationListItem> rows {
+ {2.0f, "first"},
+ {1.0f, "low"},
+ {2.0f, "second"},
+ {2.0f, "third"}
+ };
+
+ auto const limited=sorted_limited_active_station_items(rows, 4, true);
+
+ QCOMPARE(limited[0].text, QString {"first"});
+ QCOMPARE(limited[1].text, QString {"second"});
+ QCOMPARE(limited[2].text, QString {"third"});
+ QCOMPARE(limited[3].text, QString {"low"});
+}
+
+void TestActiveStationList::handlesEmptyAndZeroLimit()
+{
+ QVERIFY(sorted_limited_active_station_items({}, 50, false).isEmpty());
+
+ QVector<ActiveStationListItem> rows {{1.0f, "row"}};
+ QVERIFY(sorted_limited_active_station_items(rows, 0, false).isEmpty());
+}
+
+QTEST_MAIN(TestActiveStationList)
+
+#include "test_active_station_list.moc"
diff --git a/tests/unit/common/test_active_stations.cpp b/tests/unit/common/test_active_stations.cpp
new file mode 100644
index 00000000..d53f58e0
--- /dev/null
+++ b/tests/unit/common/test_active_stations.cpp
@@ -0,0 +1,86 @@
+#include <QtTest>
+#include <QCheckBox>
+#include <QLabel>
+#include <QPlainTextEdit>
+#include <QSettings>
+#include <QTemporaryDir>
+
+#include "widgets/activeStations.h"
+
+class TestActiveStations : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void transitions();
+ void clickRouting();
+};
+
+void TestActiveStations::transitions()
+{
+ QTemporaryDir directory;
+ QVERIFY(directory.isValid());
+ QSettings settings(directory.filePath("settings.ini"), QSettings::IniFormat);
+ ActiveStations widget(&settings, QFont{});
+ using Mode = ActiveStations::DisplayMode;
+ auto const modes = {Mode::Standard, Mode::Q65, Mode::Q65Pileup, Mode::Fox};
+ auto ready = widget.findChild<QCheckBox *>("cbReadyOnly");
+ auto wanted = widget.findChild<QCheckBox *>("cbWantedOnly");
+ auto label = widget.findChild<QLabel *>("label");
+ auto header = widget.findChild<QLabel *>("header_label2");
+ QVERIFY(ready && wanted && label && header);
+
+ for (auto previous : modes) {
+ for (auto mode : modes) {
+ widget.setupUi(previous);
+ widget.setupUi(mode);
+ bool const fox = mode == Mode::Fox;
+ bool const pileup = mode == Mode::Q65Pileup;
+ QCOMPARE(ready->isHidden(), fox || pileup);
+ QCOMPARE(wanted->isHidden(), pileup);
+ QCOMPARE(wanted->text(), fox ? QString("My call only") : QString("# Wanted only"));
+ QCOMPARE(label->isHidden(), fox || pileup);
+ QCOMPARE(label->text(), mode == Mode::Q65 ? QString("QSOs:") : QString("Rate:"));
+ QCOMPARE(widget.findChild<QWidget *>("score")->isHidden(), mode != Mode::Standard);
+ QCOMPARE(widget.findChild<QWidget *>("sbMaxAge")->isHidden(), fox || pileup);
+ QCOMPARE(header->text().contains("Fsked"), mode == Mode::Q65);
+ QCOMPARE(header->text().contains("Age(h)"), pileup);
+ QCOMPARE(header->text().contains("Message"), fox);
+ }
+ }
+}
+
+void TestActiveStations::clickRouting()
+{
+ QTemporaryDir directory;
+ QVERIFY(directory.isValid());
+ QSettings settings(directory.filePath("settings.ini"), QSettings::IniFormat);
+ ActiveStations widget(&settings, QFont{});
+ QSignalSpy station(&widget, SIGNAL(callSandP(int)));
+ QSignalSpy hound(&widget, SIGNAL(queueActiveWindowHound(QString)));
+ QVERIFY(station.isValid());
+ QVERIFY(hound.isValid());
+ auto editor = widget.findChild<QPlainTextEdit *>("RecentStationsPlainTextEdit");
+ QVERIFY(editor);
+ using Mode = ActiveStations::DisplayMode;
+ for (auto mode : {Mode::Fox, Mode::Q65, Mode::Q65Pileup, Mode::Standard}) {
+ widget.displayRecentStations(mode, " 2. K1ABC FN42\n");
+ widget.findChild<QLabel *>("header_label2")->setText("Translated heading");
+ widget.findChild<QCheckBox *>("cbWantedOnly")->setText("Translated filter");
+ widget.setClickOK(false);
+ editor->moveCursor(QTextCursor::Start);
+ station.clear();
+ hound.clear();
+ QVERIFY(QMetaObject::invokeMethod(&widget, "on_textEdit_clicked", Qt::DirectConnection));
+ QCOMPARE(station.count() + hound.count(), 0);
+ widget.setClickOK(true);
+ QVERIFY(QMetaObject::invokeMethod(&widget, "on_textEdit_clicked", Qt::DirectConnection));
+ QCOMPARE(hound.count(), mode == Mode::Fox ? 1 : 0);
+ QCOMPARE(station.count(), mode == Mode::Fox ? 0 : 1);
+ if (mode == Mode::Fox) QCOMPARE(hound.at(0).at(0).toString(), QString(" 2. K1ABC FN42"));
+ else QCOMPARE(station.at(0).at(0).toInt(), 2);
+ }
+}
+
+QTEST_MAIN(TestActiveStations)
+#include "test_active_stations.moc"
diff --git a/tests/unit/common/test_auto_respond_period.cpp b/tests/unit/common/test_auto_respond_period.cpp
new file mode 100644
index 00000000..3f1f7623
--- /dev/null
+++ b/tests/unit/common/test_auto_respond_period.cpp
@@ -0,0 +1,217 @@
+#include <QtTest>
+
+#include "AutoRespondPeriod.hpp"
+#include "Decoder/decodedtext.h"
+
+namespace
+{
+ QDateTime utc(QString const& text)
+ {
+ auto value = QDateTime::fromString(text, Qt::ISODateWithMs);
+ value.setTimeSpec(Qt::UTC);
+ return value;
+ }
+
+ AutoRespondPeriodState armedState(QDateTime const& period,
+ AutoRespondPolicy policy = AutoRespondPolicy::First)
+ {
+ AutoRespondPeriodState state;
+ state.setEnableTx(true);
+ state.observePeriod(period, true, true, policy);
+ return state;
+ }
+}
+
+class TestAutoRespondPeriod final : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void enableTxAtReceiveBoundaryArmsPeriod()
+ {
+ auto const period = utc("2026-08-03T12:00:15.000Z");
+ AutoRespondPeriodState state;
+ state.setEnableTx(true);
+
+ QVERIFY(state.observePeriod(period, true, true, AutoRespondPolicy::First));
+ QVERIFY(state.accepts(period));
+ }
+
+ void armedPeriodAcceptsOnlyItsDecodeSequence()
+ {
+ auto const period = utc("2026-08-03T12:00:15.000Z");
+ auto state = armedState(period);
+
+ QVERIFY(state.accepts(period));
+ QVERIFY(!state.accepts(period.addSecs(-15)));
+ QVERIFY(!state.accepts(period.addSecs(15)));
+ }
+
+ void enableDuringReceivePeriodArmsItProspectively()
+ {
+ auto const period = utc("2026-08-03T12:00:15.000Z");
+ AutoRespondPeriodState state;
+ QVERIFY(!state.observePeriod(period, true, true, AutoRespondPolicy::First));
+ QVERIFY(!state.claimFirst(period));
+
+ state.setEnableTx(true);
+
+ QVERIFY(state.armCurrentReceivePeriod(true, AutoRespondPolicy::First));
+ QVERIFY(state.claimFirst(period));
+ }
+
+ void disableAndReenableWithinReceivePeriodCanRearmIt()
+ {
+ auto const period = utc("2026-08-03T12:00:15.000Z");
+ auto state = armedState(period);
+
+ state.setEnableTx(false);
+ QVERIFY(!state.accepts(period));
+ state.setEnableTx(true);
+
+ QVERIFY(state.armCurrentReceivePeriod(true, AutoRespondPolicy::First));
+ QVERIFY(state.accepts(period));
+ }
+
+ void enableDuringTransmitArmsNextReceivePeriodOnly()
+ {
+ auto const period = utc("2026-08-03T12:00:15.000Z");
+ AutoRespondPeriodState state;
+ state.observePeriod(period, true, true, AutoRespondPolicy::First);
+
+ auto const transmitPeriod = period.addSecs(15);
+ state.observePeriod(transmitPeriod, false, true, AutoRespondPolicy::First);
+ state.setEnableTx(true);
+ QVERIFY(!state.armCurrentReceivePeriod(true, AutoRespondPolicy::First));
+ QVERIFY(!state.accepts(period));
+
+ auto const nextReceivePeriod = period.addSecs(30);
+
+ QVERIFY(state.observePeriod(nextReceivePeriod, true, true, AutoRespondPolicy::First));
+ QVERIFY(state.accepts(nextReceivePeriod));
+ }
+
+ void transmitPeriodKeepsDecodeWindowOpenUntilActualTransmit()
+ {
+ auto const receivePeriod = utc("2026-08-03T12:00:15.000Z");
+ auto state = armedState(receivePeriod);
+
+ state.observePeriod(receivePeriod.addSecs(15), false, true, AutoRespondPolicy::First);
+ QVERIFY(state.accepts(receivePeriod));
+
+ state.close();
+ QVERIFY(!state.accepts(receivePeriod));
+ }
+
+ void firstPolicyClaimsOnlyOneCallerPerPeriod()
+ {
+ auto const period = utc("2026-08-03T12:00:15.000Z");
+ auto state = armedState(period);
+
+ QVERIFY(state.claimFirst(period));
+ QVERIFY(!state.claimFirst(period));
+
+ auto const nextPeriod = period.addSecs(30);
+ state.observePeriod(period.addSecs(15), false, true, AutoRespondPolicy::First);
+ state.observePeriod(nextPeriod, true, true, AutoRespondPolicy::First);
+ QVERIFY(state.claimFirst(nextPeriod));
+ }
+
+ void repeatedEnableDoesNotResetFirstCallerClaim()
+ {
+ auto const period = utc("2026-08-03T12:00:15.000Z");
+ auto state = armedState(period);
+
+ QVERIFY(state.claimFirst(period));
+ QVERIFY(!state.setEnableTx(true));
+ QVERIFY(!state.armCurrentReceivePeriod(true, AutoRespondPolicy::First));
+ QVERIFY(!state.claimFirst(period));
+ }
+
+ void responsePolicyIsSnapshottedForThePeriod()
+ {
+ auto const period = utc("2026-08-03T12:00:07.500Z");
+ auto state = armedState(period, AutoRespondPolicy::MaxSignal);
+
+ QCOMPARE(state.policy(), AutoRespondPolicy::MaxSignal);
+ state.observePeriod(period, true, true, AutoRespondPolicy::MinSignal);
+ QCOMPARE(state.policy(), AutoRespondPolicy::MaxSignal);
+ }
+
+ void cqIntentAndActivePolicyAreRequired()
+ {
+ auto const period = utc("2026-08-03T12:00:15.000Z");
+ AutoRespondPeriodState state;
+ state.setEnableTx(true);
+
+ QVERIFY(!state.observePeriod(period, true, false, AutoRespondPolicy::First));
+ state.observePeriod(period.addSecs(15), false, true, AutoRespondPolicy::First);
+ QVERIFY(!state.observePeriod(period.addSecs(30), true, true, AutoRespondPolicy::None));
+ }
+
+ void currentPeriodArmingRequiresCqIntentAndActivePolicy()
+ {
+ auto const period = utc("2026-08-03T12:00:15.000Z");
+ AutoRespondPeriodState state;
+ state.observePeriod(period, true, true, AutoRespondPolicy::First);
+ state.setEnableTx(true);
+
+ QVERIFY(!state.armCurrentReceivePeriod(false, AutoRespondPolicy::First));
+ QVERIFY(!state.armCurrentReceivePeriod(true, AutoRespondPolicy::None));
+ QVERIFY(state.armCurrentReceivePeriod(true, AutoRespondPolicy::MaxSignal));
+ QCOMPARE(state.policy(), AutoRespondPolicy::MaxSignal);
+ }
+
+ void directOpeningMessagesAreEligible_data()
+ {
+ QTest::addColumn<QString>("payload");
+
+ QTest::newRow("grid") << "K1ABC W1AW FN31";
+ QTest::newRow("report") << "K1ABC W1AW -10";
+ QTest::newRow("positive-report") << "K1ABC W1AW +03";
+ }
+
+ void directOpeningMessagesAreEligible()
+ {
+ QFETCH(QString, payload);
+ DecodedText message {"0605 -10 0.3 1500 ~ " + payload};
+
+ QVERIFY(message.isStandardMessage());
+ QVERIFY(isDirectAutoRespondCandidate(message, "K1ABC"));
+ }
+
+ void compoundConfiguredCallRequiresExactRecipient()
+ {
+ DecodedText exactCall {"0605 -10 0.3 1500 ~ K1ABC/P W1AW FN31"};
+ DecodedText sharedBase {"0605 -10 0.3 1500 ~ K1ABC W1AW FN31"};
+
+ QVERIFY(exactCall.isStandardMessage());
+ QVERIFY(sharedBase.isStandardMessage());
+ QVERIFY(isDirectAutoRespondCandidate(exactCall, "K1ABC/P"));
+ QVERIFY(!isDirectAutoRespondCandidate(sharedBase, "K1ABC/P"));
+ }
+
+ void nonOpeningMessagesAreRejected_data()
+ {
+ QTest::addColumn<QString>("payload");
+
+ QTest::newRow("generic-cq") << "CQ W1AW FN31";
+ QTest::newRow("another-recipient") << "K9XYZ W1AW FN31";
+ QTest::newRow("self") << "K1ABC K1ABC FN31";
+ QTest::newRow("roger-report") << "K1ABC W1AW R-10";
+ QTest::newRow("rrr") << "K1ABC W1AW RRR";
+ QTest::newRow("rr73") << "K1ABC W1AW RR73";
+ QTest::newRow("73") << "K1ABC W1AW 73";
+ }
+
+ void nonOpeningMessagesAreRejected()
+ {
+ QFETCH(QString, payload);
+ DecodedText message {"0605 -10 0.3 1500 ~ " + payload};
+
+ QVERIFY(!isDirectAutoRespondCandidate(message, "K1ABC"));
+ }
+};
+
+QTEST_MAIN(TestAutoRespondPeriod)
+#include "test_auto_respond_period.moc"
diff --git a/tests/unit/common/test_auto_respond_scoring.cpp b/tests/unit/common/test_auto_respond_scoring.cpp
new file mode 100644
index 00000000..a8bf5db8
--- /dev/null
+++ b/tests/unit/common/test_auto_respond_scoring.cpp
@@ -0,0 +1,65 @@
+#include <QtTest>
+
+#include "AutoRespondScoring.hpp"
+
+class TestAutoRespondScoring final : public QObject
+{
+ Q_OBJECT
+
+private:
+ Q_SLOT void firstDecodedSignalCandidateAlwaysWins()
+ {
+ AutoRespondScores scores;
+
+ QVERIFY(scores.considerMaximumDb(-40));
+ QVERIFY(scores.considerMinimumDb(40));
+ }
+
+ Q_SLOT void maximumDbKeepsStrongestCandidate()
+ {
+ AutoRespondScores scores;
+
+ QVERIFY(scores.considerMaximumDb(-20));
+ QVERIFY(scores.considerMaximumDb(-10));
+ QVERIFY(!scores.considerMaximumDb(-10));
+ QVERIFY(!scores.considerMaximumDb(-30));
+ }
+
+ Q_SLOT void minimumDbKeepsWeakestCandidate()
+ {
+ AutoRespondScores scores;
+
+ QVERIFY(scores.considerMinimumDb(-10));
+ QVERIFY(scores.considerMinimumDb(-20));
+ QVERIFY(!scores.considerMinimumDb(-20));
+ QVERIFY(!scores.considerMinimumDb(-5));
+ }
+
+ Q_SLOT void firstDistanceCandidateAlwaysWins()
+ {
+ AutoRespondScores scores;
+
+ QVERIFY(scores.considerDistance(0));
+ QVERIFY(!scores.considerDistance(0));
+ QVERIFY(scores.considerDistance(1));
+ QVERIFY(scores.considerDistance(100));
+ QVERIFY(!scores.considerDistance(100));
+ }
+
+ Q_SLOT void resetAllowsNewCandidates()
+ {
+ AutoRespondScores scores;
+ QVERIFY(scores.considerDistance(100));
+ QVERIFY(scores.considerMaximumDb(10));
+ QVERIFY(scores.considerMinimumDb(-40));
+
+ scores.reset();
+
+ QVERIFY(scores.considerDistance(0));
+ QVERIFY(scores.considerMaximumDb(-40));
+ QVERIFY(scores.considerMinimumDb(40));
+ }
+};
+
+QTEST_MAIN(TestAutoRespondScoring)
+#include "test_auto_respond_scoring.moc"
diff --git a/tests/unit/common/test_auto_respond_selection_latch.cpp b/tests/unit/common/test_auto_respond_selection_latch.cpp
new file mode 100644
index 00000000..d81910e9
--- /dev/null
+++ b/tests/unit/common/test_auto_respond_selection_latch.cpp
@@ -0,0 +1,36 @@
+#include <QtTest>
+
+#include "AutoRespondSelectionLatch.hpp"
+
+class TestAutoRespondSelectionLatch : public QObject
+{
+ Q_OBJECT
+
+private:
+ Q_SLOT void selectForClearsAfterDelay()
+ {
+ AutoRespondSelectionLatch latch;
+
+ latch.selectFor(10);
+
+ QVERIFY(latch.isSelected());
+ QTRY_VERIFY_WITH_TIMEOUT(!latch.isSelected(), 250);
+ }
+
+ Q_SLOT void selectForRestartsResetDelay()
+ {
+ AutoRespondSelectionLatch latch;
+
+ latch.selectFor(30);
+ QTest::qWait(10);
+ latch.selectFor(100);
+
+ QVERIFY(latch.isSelected());
+ QTest::qWait(50);
+ QVERIFY(latch.isSelected());
+ QTRY_VERIFY_WITH_TIMEOUT(!latch.isSelected(), 250);
+ }
+};
+
+QTEST_MAIN(TestAutoRespondSelectionLatch)
+#include "test_auto_respond_selection_latch.moc"
diff --git a/tests/unit/common/test_auto_sequence_reaction.cpp b/tests/unit/common/test_auto_sequence_reaction.cpp
new file mode 100644
index 00000000..2964c1f7
--- /dev/null
+++ b/tests/unit/common/test_auto_sequence_reaction.cpp
@@ -0,0 +1,203 @@
+#include <QtTest>
+
+#include "QsoReactionTestSupport.hpp"
+
+namespace
+{
+ using namespace QsoReactionTestSupport;
+
+ Snapshot baseSnapshot()
+ {
+ auto snapshot = neutralStationSnapshot();
+ snapshot.mode = "FT8";
+ snapshot.autoEnabled = true;
+ snapshot.autoSequenceEnabled = true;
+ snapshot.tx1Enabled = true;
+ snapshot.qsoProgress = QsoProgress::Calling;
+ return snapshot;
+ }
+}
+
+class TestAutoSequenceReaction final
+ : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void stopsToAvoidQrmWhenPartnerRepliesNearOurTxFrequencyToAnotherCaller()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.qsoProgress = QsoProgress::Replying;
+ snapshot.txFrequency = 815;
+ DecodedText message {"0605 -10 0.3 0815 ~ K9XYZ W1AW -10"};
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ message, snapshot, DecodedMessageReaction::AutoSequencePhase::StandardDecode, 25, 50);
+
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::Reacted);
+ QVERIFY(hasEffect(plan, Effect::Kind::ClickStopTx));
+ }
+
+ void processesDirectedReplyToOurCall()
+ {
+ auto snapshot = baseSnapshot();
+ DecodedText message {"0605 -10 0.3 1500 ~ K1ABC W1AW -10"};
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ message, snapshot, DecodedMessageReaction::AutoSequencePhase::StandardDecode, 25, 50);
+
+ QVERIFY(hasEffect(plan, Effect::Kind::ProcessSyntheticMessageNow));
+ }
+
+ void standard73DoesNotTreatEmptyDxCallAsMatch_data()
+ {
+ QTest::addColumn<QString>("dxCall");
+ QTest::addColumn<bool>("advances");
+
+ QTest::newRow("selected-partner") << "W1AW" << true;
+ QTest::newRow("empty-partner") << "" << false;
+ }
+
+ void standard73DoesNotTreatEmptyDxCallAsMatch()
+ {
+ QFETCH(QString, dxCall);
+ QFETCH(bool, advances);
+ auto snapshot = baseSnapshot();
+ snapshot.dxCall = dxCall;
+ snapshot.hisCall = dxCall;
+ snapshot.qsoProgress = QsoProgress::RogerReport;
+ DecodedText message {"0605 -10 0.3 1500 ~ K9XYZ W1AW 73"};
+ QVERIFY(message.isStandardMessage());
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ message, snapshot, DecodedMessageReaction::AutoSequencePhase::StandardDecode, 25, 50);
+
+ QCOMPARE(hasEffect(plan, Effect::Kind::ProcessSyntheticMessageNow), advances);
+ }
+
+ void processesTypeTwoDeReplyWithinTolerance()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.callingCq = true;
+ snapshot.autoReply = true;
+ DecodedText message {"0605 -10 0.3 1500 ~ DE W1AW -10"};
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ message, snapshot, DecodedMessageReaction::AutoSequencePhase::StandardDecode, 25, 50);
+
+ QVERIFY(hasEffect(plan, Effect::Kind::ProcessSyntheticMessageNow));
+ }
+
+ void ignoresProcessActionInFoxMode()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.specOp = SpecialOperatingActivity::FOX;
+ DecodedText message {"0605 -10 0.3 1500 ~ K1ABC W1AW -10"};
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ message, snapshot, DecodedMessageReaction::AutoSequencePhase::StandardDecode, 25, 50);
+
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::NoReaction);
+ }
+
+ void freeText73DoesNotAdvanceMsk144AutoSequence()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "MSK144";
+ snapshot.qsoProgress = QsoProgress::RogerReport;
+ DecodedText message {"060522 -10 0.3 1500 & RR73"};
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ message, snapshot, DecodedMessageReaction::AutoSequencePhase::StandardDecode, 25, 50);
+
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::NoReaction);
+ }
+
+ void storesEuVhfExchangeForAutoSequenceCandidate()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "MSK144";
+ DecodedText message {"060522 -10 0.3 1500 & <K1ABC> W1AW 520001 FN31 W1AW R X"};
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ message, snapshot, DecodedMessageReaction::AutoSequencePhase::StandardDecode, 25, 50);
+
+ QCOMPARE(textEffect(plan, Effect::Kind::SetReceivedExchange),
+ message.clean_string().trimmed().right(13));
+ }
+
+ void ignoresEuVhfExchangeForRejectedDecode()
+ {
+ auto snapshot = baseSnapshot();
+ DecodedText message {"0605 -10 0.3 1500 ~ RANDOM <K1ABC> 520001 FN31"};
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ message, snapshot, DecodedMessageReaction::AutoSequencePhase::StandardDecode, 25, 50);
+
+ QVERIFY(textEffect(plan, Effect::Kind::SetReceivedExchange).isEmpty());
+ }
+
+ void legacyShortMessages_data()
+ {
+ QTest::addColumn<QString>("payload");
+ QTest::addColumn<int>("expectedTxMessage");
+
+ QTest::newRow("ooo") << "K1ABC W1AW OOO" << 3;
+ QTest::newRow("ro") << "RO" << 4;
+ QTest::newRow("rrr") << "RRR" << 5;
+ QTest::newRow("73") << "73" << 5;
+ }
+
+ void legacyShortMessages()
+ {
+ QFETCH(QString, payload);
+ QFETCH(int, expectedTxMessage);
+ auto snapshot = neutralStationSnapshot();
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ decode(payload, "#"), snapshot,
+ DecodedMessageReaction::AutoSequencePhase::LegacyShortMessage, 15, 15);
+
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::Reacted);
+ QCOMPARE(intEffect(plan, Effect::Kind::SetTxMessage), expectedTxMessage);
+ }
+
+ void legacyShortMessageTolerance_data()
+ {
+ QTest::addColumn<int>("frequency");
+ QTest::addColumn<bool>("reacts");
+
+ QTest::newRow("minus-sixteen") << 1484 << false;
+ QTest::newRow("minus-fifteen") << 1485 << true;
+ QTest::newRow("plus-fifteen") << 1515 << true;
+ QTest::newRow("plus-sixteen") << 1516 << false;
+ }
+
+ void legacyShortMessageTolerance()
+ {
+ QFETCH(int, frequency);
+ QFETCH(bool, reacts);
+ auto snapshot = neutralStationSnapshot();
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ decode("RRR", "#", "0605", frequency), snapshot,
+ DecodedMessageReaction::AutoSequencePhase::LegacyShortMessage, 15, 15);
+
+ QCOMPARE(plan.disposition == DecodedMessageReaction::ReactionDisposition::Reacted, reacts);
+ }
+
+ void legacyShortMessageHonorsStartToleranceArgument()
+ {
+ auto snapshot = neutralStationSnapshot();
+
+ auto const plan = DecodedMessageReaction::planAutoSequence(
+ decode("RRR", "#", "0605", 1516), snapshot,
+ DecodedMessageReaction::AutoSequencePhase::LegacyShortMessage, 16, 15);
+
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::Reacted);
+ QCOMPARE(intEffect(plan, Effect::Kind::SetTxMessage), 5);
+ }
+};
+
+QTEST_MAIN(TestAutoSequenceReaction)
+#include "test_auto_sequence_reaction.moc"
diff --git a/tests/unit/common/test_beacon_tx_controller.cpp b/tests/unit/common/test_beacon_tx_controller.cpp
new file mode 100644
index 00000000..ba0cd7c7
--- /dev/null
+++ b/tests/unit/common/test_beacon_tx_controller.cpp
@@ -0,0 +1,586 @@
+#include <QtTest>
+
+#include "BeaconTxController.hpp"
+
+using namespace BeaconTx;
+
+namespace
+{
+ int count (Controller::Actions const& actions, ActionKind kind)
+ {
+ int result = 0;
+ for (auto const& action : actions) if (action.kind == kind) ++result;
+ return result;
+ }
+
+ Action const * first (Controller::Actions const& actions, ActionKind kind)
+ {
+ for (auto const& action : actions) if (action.kind == kind) return &action;
+ return nullptr;
+ }
+
+ ScheduleProposal proposal (Disposition disposition)
+ {
+ ScheduleProposal result;
+ result.disposition = disposition;
+ return result;
+ }
+
+ ScheduleProposal hoppingProposal (Disposition disposition, bool tune = false)
+ {
+ auto result = proposal (disposition);
+ result.source = PlanSource::BandHop;
+ result.hasHoppingProposal = true;
+ result.hopping.frequenciesIndex = 3;
+ result.hopping.tuneRequired = tune;
+ return result;
+ }
+
+ struct Harness
+ {
+ Controller controller;
+
+ void initialize (RoundRobinPolicy policy = RoundRobinPolicy::random ())
+ {
+ controller.enterMode (1000, policy);
+ controller.setAutoEnabled (true);
+ auto const actions = controller.observeUtc (100);
+ QCOMPARE (count (actions, ActionKind::SetTransmitWindow), 1);
+ QVERIFY (!actions.front ().enabled);
+ }
+
+ PlanId prepare (Disposition disposition = Disposition::Transmit)
+ {
+ auto const actions = controller.receiveCompleted ();
+ auto const request = first (actions, ActionKind::RequestScheduleProposal);
+ if (!request) return {};
+ auto const id = request->planId;
+ controller.proposalDelivered (id, proposal (disposition));
+ return id;
+ }
+
+ PlanId enterPreparedTransmit ()
+ {
+ auto const id = prepare ();
+ controller.observeUtc (1100);
+ return id;
+ }
+ };
+
+ struct ActionRecorder
+ {
+ std::vector<Action> actions;
+
+ void record (Controller::Actions const& newActions)
+ {
+ actions.insert (actions.end (), newActions.begin (), newActions.end ());
+ }
+
+ int countFor (PlanId id, ActionKind kind) const
+ {
+ int result = 0;
+ for (auto const& action : actions)
+ {
+ if (action.planId == id && action.kind == kind) ++result;
+ }
+ return result;
+ }
+ };
+
+}
+
+class TestBeaconTxController final : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void roundRobinPolicyCodec ();
+ void delayedAdjacentPeriodAndDuplicateObservation ();
+ void resyncReceivesPartialSlotAndPreparesAtCompletion ();
+ void receiveCompletionPreparesOnce ();
+ void successfulTxLifecycleRecordsAndPreparesOnce ();
+ void failedTxStartRecordsNothingAndRecovers ();
+ void modeExitDuringPttTailDoesNotPrepare ();
+ void manualTuneAcrossBoundaryRestoresAutoAndPrepares ();
+ void automaticTuneCompletesExistingPlanWithoutRedraw ();
+ void staleAutomaticTuneEventsAreIgnored ();
+ void expiredAutomaticTunePreparesOnceAfterTail ();
+ void txNextSurvivesTuneAndResync ();
+ void txNextClearsOnlyWhenMessageStarts ();
+ void txNextCancellationReusesUnderlyingPlan ();
+ void suppressedTxNextCancellationDoesNotDraw ();
+ void fixedRoundRobinUsesUtcBoundaryWithoutProposal ();
+ void txNextPrecedesFixedRoundRobin ();
+ void policyChangeDuringTxDrawsOnceAtCompletion ();
+ void bandChangeFailureConvertsSamePlanToReceive ();
+ void staleAndDuplicateBandOutcomesAreIgnored ();
+ void proposalRequestDoesNotActuate ();
+ void startedSessionCrossesBoundaryAndPreparesOnStop ();
+ void oldStopCannotPrepareReenteredEpoch ();
+ void txNextWithdrawalAfterBoundaryUsesUnderlyingReceive ();
+ void txNextWithdrawalDuringStartWaitsForStop ();
+ void acceptedStartIgnoresConflictingDuplicateResult ();
+ void acceptedStartWithoutMessageRecordsNothingAndRecovers ();
+ void earlyTxStopClosesWindowAndPrepares ();
+ void autoDisabledForcesReceiveWithoutRedraw ();
+ void backwardClockStepResynchronizesToReceive ();
+ void oneProposalRequestAndApplicationPerPlanId ();
+};
+
+void TestBeaconTxController::roundRobinPolicyCodec ()
+{
+ auto policy = parseRoundRobinPolicy ("2/4");
+ QCOMPARE (policy.kind, RoundRobinPolicy::Kind::Fixed);
+ QCOMPARE (policy.selectedSlot, 1);
+ QCOMPARE (policy.slotCount, 4);
+ QVERIFY (formatRoundRobinPolicy (policy) == "2/4");
+
+ policy = parseRoundRobinPolicy ("7/12");
+ QCOMPARE (policy.kind, RoundRobinPolicy::Kind::Fixed);
+ QCOMPARE (policy.selectedSlot, 6);
+ QCOMPARE (policy.slotCount, 12);
+
+ QVERIFY (formatRoundRobinPolicy (parseRoundRobinPolicy (" +2 / 4 \t")) == "2/4");
+ for (auto const& text : {"random", "Random", "randomized", "0/4", "5/4", "2/4x",
+ "2/4/6", "2/", "/4", "2/99999999999999999999", "-1/4"})
+ {
+ QCOMPARE (parseRoundRobinPolicy (text).kind, RoundRobinPolicy::Kind::Random);
+ }
+ QVERIFY (formatRoundRobinPolicy (RoundRobinPolicy::random ()) == "random");
+}
+
+void TestBeaconTxController::delayedAdjacentPeriodAndDuplicateObservation ()
+{
+ Harness h;
+ h.initialize ();
+ auto const request = h.controller.receiveCompleted ();
+ auto const id = first (request, ActionKind::RequestScheduleProposal)->planId;
+
+ auto const boundary = h.controller.observeUtc (1101);
+ QVERIFY (!boundary.front ().enabled);
+ QVERIFY (h.controller.proposalDelivered (id, proposal (Disposition::Transmit)).empty ());
+ QVERIFY (h.controller.observeUtc (1199).empty ());
+}
+
+void TestBeaconTxController::resyncReceivesPartialSlotAndPreparesAtCompletion ()
+{
+ Harness h;
+ h.initialize ();
+ h.prepare ();
+
+ auto const resync = h.controller.observeUtc (3100);
+ QCOMPARE (count (resync, ActionKind::SetTransmitWindow), 1);
+ QVERIFY (!resync.front ().enabled);
+ auto const completion = h.controller.receiveCompleted ();
+ QCOMPARE (count (completion, ActionKind::RequestScheduleProposal), 1);
+ QVERIFY (h.controller.receiveCompleted ().empty ());
+}
+
+void TestBeaconTxController::receiveCompletionPreparesOnce ()
+{
+ Harness h;
+ h.initialize ();
+ QCOMPARE (count (h.controller.receiveCompleted (), ActionKind::RequestScheduleProposal), 1);
+ QVERIFY (h.controller.receiveCompleted ().empty ());
+}
+
+void TestBeaconTxController::successfulTxLifecycleRecordsAndPreparesOnce ()
+{
+ Harness h;
+ h.initialize ();
+ auto const id = h.enterPreparedTransmit ();
+ h.controller.txStartRequested ();
+ QVERIFY (h.controller.txStartResult (id, true).empty ());
+ auto const started = h.controller.messageStarted (id);
+ QCOMPARE (count (started, ActionKind::RecordBeaconTransmission), 1);
+
+ h.controller.transmitWindowEnded ();
+ auto const stopped = h.controller.txStopped (id);
+ QCOMPARE (count (stopped, ActionKind::RequestScheduleProposal), 1);
+ QVERIFY (h.controller.txStopped (id).empty ());
+}
+
+void TestBeaconTxController::failedTxStartRecordsNothingAndRecovers ()
+{
+ Harness h;
+ h.initialize ();
+ auto const id = h.enterPreparedTransmit ();
+ h.controller.txStartRequested ();
+ auto const failed = h.controller.txStartResult (id, false);
+ QCOMPARE (count (failed, ActionKind::RecordBeaconTransmission), 0);
+ QCOMPARE (count (failed, ActionKind::RequestScheduleProposal), 0);
+ QVERIFY (h.controller.txStartResult (id, false).empty ());
+ QCOMPARE (count (h.controller.txStopped (id), ActionKind::RequestScheduleProposal), 1);
+}
+
+void TestBeaconTxController::modeExitDuringPttTailDoesNotPrepare ()
+{
+ Harness h;
+ h.initialize ();
+ auto const id = h.enterPreparedTransmit ();
+ h.controller.txStartRequested ();
+ h.controller.txStartResult (id, true);
+ QCOMPARE (count (h.controller.messageStarted (id), ActionKind::RecordBeaconTransmission), 1);
+ h.controller.transmitWindowEnded ();
+ h.controller.exitMode ();
+ QCOMPARE (count (h.controller.txStopped (id), ActionKind::RequestScheduleProposal), 0);
+ QCOMPARE (h.controller.txLifecycle (), TxLifecycle::None);
+}
+
+void TestBeaconTxController::manualTuneAcrossBoundaryRestoresAutoAndPrepares ()
+{
+ Harness h;
+ h.initialize ();
+ h.controller.tuneStarted (TuneKind::Manual);
+ auto const boundary = h.controller.observeUtc (1100);
+ QVERIFY (!boundary.front ().enabled);
+ QVERIFY (h.controller.receiveCompleted ().empty ());
+
+ auto const completed = h.controller.tuneCompleted (h.controller.tunePlanId ());
+ QCOMPARE (count (completed, ActionKind::RestoreAuto), 1);
+ QCOMPARE (count (completed, ActionKind::RequestScheduleProposal), 1);
+}
+
+void TestBeaconTxController::automaticTuneCompletesExistingPlanWithoutRedraw ()
+{
+ Harness h;
+ h.initialize ();
+ auto const request = h.controller.receiveCompleted ();
+ auto const id = first (request, ActionKind::RequestScheduleProposal)->planId;
+ auto const apply = h.controller.proposalDelivered (id, hoppingProposal (Disposition::Transmit, true));
+ QCOMPARE (count (apply, ActionKind::ApplyBandChange), 1);
+ auto const tune = h.controller.bandChangeOutcome (id, true);
+ QCOMPARE (count (tune, ActionKind::StartAutomaticTune), 1);
+ h.controller.tuneStarted (TuneKind::Automatic, id);
+
+ auto const completed = h.controller.tuneCompleted (id);
+ QCOMPARE (count (completed, ActionKind::RestoreAuto), 1);
+ QCOMPARE (count (completed, ActionKind::RequestScheduleProposal), 0);
+ QVERIFY (h.controller.observeUtc (1100).front ().enabled);
+}
+
+void TestBeaconTxController::staleAutomaticTuneEventsAreIgnored ()
+{
+ Harness h;
+ h.initialize ();
+ auto const request = h.controller.receiveCompleted ();
+ auto const id = first (request, ActionKind::RequestScheduleProposal)->planId;
+ h.controller.proposalDelivered (id, hoppingProposal (Disposition::Transmit, true));
+ h.controller.bandChangeOutcome (id, true);
+ auto stale = id;
+ ++stale.epoch;
+
+ QVERIFY (h.controller.tuneStarted (TuneKind::Automatic, stale).empty ());
+ QCOMPARE (h.controller.tuneKind (), TuneKind::None);
+ h.controller.tuneStarted (TuneKind::Automatic, id);
+ QVERIFY (h.controller.tuneCompleted (stale).empty ());
+ QCOMPARE (h.controller.tuneKind (), TuneKind::Automatic);
+ QCOMPARE (count (h.controller.tuneCompleted (id), ActionKind::RestoreAuto), 1);
+}
+
+void TestBeaconTxController::expiredAutomaticTunePreparesOnceAfterTail ()
+{
+ Harness h;
+ h.initialize ();
+ auto const request = h.controller.receiveCompleted ();
+ auto const id = first (request, ActionKind::RequestScheduleProposal)->planId;
+ h.controller.proposalDelivered (id, hoppingProposal (Disposition::Transmit, true));
+ h.controller.bandChangeOutcome (id, true);
+ h.controller.tuneStarted (TuneKind::Automatic, id);
+ QVERIFY (!h.controller.observeUtc (1100).front ().enabled);
+
+ auto const completed = h.controller.tuneCompleted (id);
+ QCOMPARE (count (completed, ActionKind::RequestScheduleProposal), 1);
+ QVERIFY (h.controller.tuneCompleted (id).empty ());
+}
+
+void TestBeaconTxController::txNextSurvivesTuneAndResync ()
+{
+ Harness h;
+ h.initialize ();
+ h.controller.setTxNext (true);
+ QVERIFY (h.controller.receiveCompleted ().empty ());
+ h.controller.tuneStarted (TuneKind::Manual);
+ h.controller.observeUtc (3100);
+ h.controller.tuneCompleted (h.controller.tunePlanId ());
+ QVERIFY (h.controller.txNextPending ());
+ QVERIFY (h.controller.receiveCompleted ().empty ());
+ QVERIFY (h.controller.observeUtc (4100).front ().enabled);
+}
+
+void TestBeaconTxController::txNextClearsOnlyWhenMessageStarts ()
+{
+ Harness h;
+ h.initialize ();
+ h.controller.setTxNext (true);
+ h.controller.receiveCompleted ();
+ auto const id = h.controller.observeUtc (1100).front ().planId;
+ h.controller.txStartRequested ();
+ h.controller.txStartResult (id, true);
+ QVERIFY (h.controller.txNextPending ());
+ auto const started = h.controller.messageStarted (id);
+ QCOMPARE (count (started, ActionKind::ClearTxNextUi), 1);
+ QCOMPARE (count (started, ActionKind::RecordBeaconTransmission), 1);
+ QVERIFY (!h.controller.txNextPending ());
+}
+
+void TestBeaconTxController::txNextCancellationReusesUnderlyingPlan ()
+{
+ Harness h;
+ h.initialize ();
+ h.prepare (Disposition::Transmit);
+ h.controller.setTxNext (true);
+ h.controller.setTxNext (false);
+ QVERIFY (h.controller.observeUtc (1100).front ().enabled);
+}
+
+void TestBeaconTxController::suppressedTxNextCancellationDoesNotDraw ()
+{
+ Harness h;
+ h.initialize ();
+ h.controller.setTxNext (true);
+ QVERIFY (h.controller.receiveCompleted ().empty ());
+ h.controller.setTxNext (false);
+ QVERIFY (!h.controller.observeUtc (1100).front ().enabled);
+}
+
+void TestBeaconTxController::fixedRoundRobinUsesUtcBoundaryWithoutProposal ()
+{
+ Harness h;
+ h.initialize (RoundRobinPolicy::fixed (1, 2));
+ QVERIFY (h.controller.receiveCompleted ().empty ());
+ QVERIFY (h.controller.observeUtc (1100).front ().enabled);
+ auto const receiveBoundary = h.controller.observeUtc (2100);
+ QCOMPARE (count (receiveBoundary, ActionKind::SetTransmitWindow), 1);
+ QVERIFY (!receiveBoundary.front ().enabled);
+ QVERIFY (!h.controller.observeUtc (2199).size ());
+}
+
+void TestBeaconTxController::txNextPrecedesFixedRoundRobin ()
+{
+ Harness h;
+ h.initialize (RoundRobinPolicy::fixed (0, 2));
+ h.controller.setTxNext (true);
+ h.controller.receiveCompleted ();
+ QVERIFY (h.controller.observeUtc (1100).front ().enabled);
+}
+
+void TestBeaconTxController::policyChangeDuringTxDrawsOnceAtCompletion ()
+{
+ Harness h;
+ h.initialize (RoundRobinPolicy::fixed (1, 2));
+ auto const id = h.controller.observeUtc (1100).front ().planId;
+ h.controller.txStartRequested ();
+ h.controller.txStartResult (id, true);
+ h.controller.messageStarted (id);
+ h.controller.setRoundRobinPolicy (RoundRobinPolicy::random ());
+ h.controller.transmitWindowEnded ();
+ QCOMPARE (count (h.controller.txStopped (id), ActionKind::RequestScheduleProposal), 1);
+ QVERIFY (h.controller.txStopped (id).empty ());
+}
+
+void TestBeaconTxController::bandChangeFailureConvertsSamePlanToReceive ()
+{
+ Harness h;
+ h.initialize ();
+ auto const request = h.controller.receiveCompleted ();
+ auto const id = first (request, ActionKind::RequestScheduleProposal)->planId;
+ auto const apply = h.controller.proposalDelivered (id, hoppingProposal (Disposition::Transmit));
+ QCOMPARE (count (apply, ActionKind::ApplyBandChange), 1);
+ QVERIFY (h.controller.bandChangeOutcome (id, false).empty ());
+ QVERIFY (!h.controller.observeUtc (1100).front ().enabled);
+}
+
+void TestBeaconTxController::staleAndDuplicateBandOutcomesAreIgnored ()
+{
+ Harness h;
+ h.initialize ();
+ auto const request = h.controller.receiveCompleted ();
+ auto const id = first (request, ActionKind::RequestScheduleProposal)->planId;
+ auto const apply = h.controller.proposalDelivered (id, hoppingProposal (Disposition::Transmit, true));
+ QCOMPARE (count (apply, ActionKind::ApplyBandChange), 1);
+ auto stale = id;
+ ++stale.epoch;
+ QVERIFY (h.controller.bandChangeOutcome (stale, true).empty ());
+ QCOMPARE (count (h.controller.bandChangeOutcome (id, true), ActionKind::StartAutomaticTune), 1);
+ QVERIFY (h.controller.bandChangeOutcome (id, true).empty ());
+ QVERIFY (h.controller.proposalDelivered (id, hoppingProposal (Disposition::Transmit)).empty ());
+}
+
+void TestBeaconTxController::proposalRequestDoesNotActuate ()
+{
+ Harness h;
+ h.initialize ();
+ auto const actions = h.controller.receiveCompleted ();
+ QCOMPARE (count (actions, ActionKind::RequestScheduleProposal), 1);
+ QCOMPARE (count (actions, ActionKind::ApplyBandChange), 0);
+ QCOMPARE (count (actions, ActionKind::StartAutomaticTune), 0);
+}
+
+void TestBeaconTxController::startedSessionCrossesBoundaryAndPreparesOnStop ()
+{
+ Harness h;
+ h.initialize ();
+ auto const id = h.enterPreparedTransmit ();
+ h.controller.txStartRequested ();
+ h.controller.txStartResult (id, true);
+ h.controller.messageStarted (id);
+
+ auto const boundary = h.controller.observeUtc (2100);
+ QVERIFY (!boundary.front ().enabled);
+ QCOMPARE (h.controller.txLifecycle (), TxLifecycle::MessageStarted);
+ QCOMPARE (count (h.controller.txStopped (id), ActionKind::RequestScheduleProposal), 1);
+}
+
+void TestBeaconTxController::oldStopCannotPrepareReenteredEpoch ()
+{
+ Harness h;
+ h.initialize ();
+ auto const oldId = h.enterPreparedTransmit ();
+ h.controller.txStartRequested ();
+ h.controller.txStartResult (oldId, true);
+ h.controller.messageStarted (oldId);
+ h.controller.exitMode ();
+ h.controller.enterMode (1000);
+ h.controller.observeUtc (2100);
+
+ QCOMPARE (count (h.controller.txStopped (oldId), ActionKind::RequestScheduleProposal), 0);
+ QVERIFY (!h.controller.futurePlan ());
+ QCOMPARE (h.controller.txLifecycle (), TxLifecycle::None);
+ QVERIFY (!h.controller.txPlanId ().isValid ());
+ QVERIFY (h.controller.txStopped (oldId).empty ());
+
+ auto const completion = h.controller.receiveCompleted ();
+ QCOMPARE (count (completion, ActionKind::RequestScheduleProposal), 1);
+ auto const nextId = first (completion, ActionKind::RequestScheduleProposal)->planId;
+ QVERIFY (h.controller.receiveCompleted ().empty ());
+ QVERIFY (h.controller.txStopped (oldId).empty ());
+
+ h.controller.proposalDelivered (nextId, proposal (Disposition::Transmit));
+ auto const boundary = h.controller.observeUtc (3100);
+ QCOMPARE (count (boundary, ActionKind::SetTransmitWindow), 1);
+ QVERIFY (first (boundary, ActionKind::SetTransmitWindow)->enabled);
+ QVERIFY (h.controller.currentPlanId () == nextId);
+}
+
+void TestBeaconTxController::txNextWithdrawalAfterBoundaryUsesUnderlyingReceive ()
+{
+ Harness h;
+ h.initialize ();
+ h.prepare (Disposition::Receive);
+ h.controller.setTxNext (true);
+ QVERIFY (h.controller.observeUtc (1100).front ().enabled);
+
+ auto const withdrawn = h.controller.setTxNext (false);
+ QCOMPARE (count (withdrawn, ActionKind::SetTransmitWindow), 1);
+ QVERIFY (!withdrawn.front ().enabled);
+ QCOMPARE (h.controller.txLifecycle (), TxLifecycle::None);
+}
+
+void TestBeaconTxController::txNextWithdrawalDuringStartWaitsForStop ()
+{
+ Harness h;
+ h.initialize ();
+ h.prepare (Disposition::Receive);
+ h.controller.setTxNext (true);
+ auto const id = h.controller.observeUtc (1100).front ().planId;
+ h.controller.txStartRequested ();
+
+ auto const withdrawn = h.controller.setTxNext (false);
+ QVERIFY (!first (withdrawn, ActionKind::SetTransmitWindow)->enabled);
+ QCOMPARE (h.controller.txLifecycle (), TxLifecycle::StartRequested);
+ QCOMPARE (count (withdrawn, ActionKind::RequestScheduleProposal), 0);
+ QCOMPARE (count (h.controller.txStopped (id), ActionKind::RequestScheduleProposal), 1);
+}
+
+void TestBeaconTxController::acceptedStartIgnoresConflictingDuplicateResult ()
+{
+ Harness h;
+ h.initialize ();
+ auto const id = h.enterPreparedTransmit ();
+ h.controller.txStartRequested ();
+ h.controller.txStartResult (id, true);
+
+ QVERIFY (h.controller.txStartResult (id, false).empty ());
+ QCOMPARE (h.controller.txLifecycle (), TxLifecycle::StartRequested);
+ QCOMPARE (count (h.controller.messageStarted (id), ActionKind::RecordBeaconTransmission), 1);
+}
+
+void TestBeaconTxController::acceptedStartWithoutMessageRecordsNothingAndRecovers ()
+{
+ Harness h;
+ h.initialize ();
+ auto const id = h.enterPreparedTransmit ();
+ h.controller.txStartRequested ();
+ h.controller.txStartResult (id, true);
+
+ auto const ended = h.controller.transmitWindowEnded ();
+ QCOMPARE (count (ended, ActionKind::RecordBeaconTransmission), 0);
+ QCOMPARE (count (ended, ActionKind::RequestScheduleProposal), 0);
+ QCOMPARE (count (h.controller.txStopped (id), ActionKind::RequestScheduleProposal), 1);
+}
+
+void TestBeaconTxController::earlyTxStopClosesWindowAndPrepares ()
+{
+ Harness h;
+ h.initialize ();
+ auto const id = h.enterPreparedTransmit ();
+ h.controller.txStartRequested ();
+ h.controller.txStartResult (id, true);
+ h.controller.messageStarted (id);
+
+ auto const stopped = h.controller.txStopped (id);
+ QCOMPARE (count (stopped, ActionKind::SetTransmitWindow), 1);
+ QVERIFY (!first (stopped, ActionKind::SetTransmitWindow)->enabled);
+ QCOMPARE (count (stopped, ActionKind::RequestScheduleProposal), 1);
+}
+
+void TestBeaconTxController::autoDisabledForcesReceiveWithoutRedraw ()
+{
+ Harness h;
+ h.initialize ();
+ h.prepare (Disposition::Transmit);
+ h.controller.setAutoEnabled (false);
+
+ auto const boundary = h.controller.observeUtc (1100);
+ QVERIFY (!boundary.front ().enabled);
+ QCOMPARE (count (boundary, ActionKind::RequestScheduleProposal), 0);
+}
+
+void TestBeaconTxController::backwardClockStepResynchronizesToReceive ()
+{
+ Harness h;
+ h.initialize ();
+ h.prepare (Disposition::Transmit);
+ auto const epoch = h.controller.currentPlanId ().epoch;
+
+ auto const resync = h.controller.observeUtc (50);
+ QCOMPARE (count (resync, ActionKind::SetTransmitWindow), 1);
+ QVERIFY (!resync.front ().enabled);
+ QVERIFY (h.controller.currentPlanId ().epoch != epoch);
+ QVERIFY (!h.controller.futurePlan ());
+}
+
+void TestBeaconTxController::oneProposalRequestAndApplicationPerPlanId ()
+{
+ Harness h;
+ h.initialize ();
+ ActionRecorder recorder;
+ auto const requested = h.controller.receiveCompleted ();
+ recorder.record (requested);
+ auto const id = first (requested, ActionKind::RequestScheduleProposal)->planId;
+ auto const drawn = hoppingProposal (Disposition::Transmit);
+ auto const apply = h.controller.proposalDelivered (id, drawn);
+ recorder.record (apply);
+ h.controller.bandChangeOutcome (id, true);
+
+ recorder.record (h.controller.receiveCompleted ());
+ recorder.record (h.controller.proposalDelivered (id, drawn));
+ recorder.record (h.controller.bandChangeOutcome (id, false));
+ QCOMPARE (recorder.countFor (id, ActionKind::RequestScheduleProposal), 1);
+ QCOMPARE (recorder.countFor (id, ActionKind::ApplyBandChange), 1);
+}
+
+QTEST_GUILESS_MAIN (TestBeaconTxController)
+
+#include "test_beacon_tx_controller.moc"
diff --git a/tests/unit/common/test_callsign_validator.cpp b/tests/unit/common/test_callsign_validator.cpp
new file mode 100644
index 00000000..6715dfd7
--- /dev/null
+++ b/tests/unit/common/test_callsign_validator.cpp
@@ -0,0 +1,48 @@
+#include <QtTest>
+
+#include "validators/CallsignValidator.hpp"
+
+class TestCallsignValidator final
+ : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ void normalizeStoredInput_data ();
+ void normalizeStoredInput ();
+};
+
+void TestCallsignValidator::normalizeStoredInput_data ()
+{
+ QTest::addColumn<QString> ("input");
+ QTest::addColumn<int> ("max_length");
+ QTest::addColumn<bool> ("allow_compound");
+ QTest::addColumn<QString> ("expected");
+
+ QTest::newRow ("valid") << QString {"K1JT"} << 6 << false << QString {"K1JT"};
+ QTest::newRow ("lowercase") << QString {"k1jt"} << 6 << false << QString {"K1JT"};
+ QTest::newRow ("boundary whitespace") << QString {" k1jt "} << 6 << false << QString {"K1JT"};
+ QTest::newRow ("trim before truncation") << QString {" K1JT73"} << 6 << false << QString {"K1JT73"};
+ QTest::newRow ("truncate valid") << QString {"K1JT73X"} << 6 << false << QString {"K1JT73"};
+ QTest::newRow ("compound allowed") << QString {"K1JT/P"} << 6 << true << QString {"K1JT/P"};
+ QTest::newRow ("compound rejected") << QString {"K1JT/P"} << 6 << false << QString {};
+ QTest::newRow ("punctuation") << QString {"K1?JT"} << 6 << false << QString {};
+ QTest::newRow ("internal whitespace") << QString {"K1 JT"} << 6 << false << QString {};
+ QTest::newRow ("non-ASCII") << QString::fromUtf8 ("K1\xc3\x98JT") << 6 << false << QString {};
+ QTest::newRow ("empty") << QString {} << 6 << false << QString {};
+}
+
+void TestCallsignValidator::normalizeStoredInput ()
+{
+ QFETCH (QString, input);
+ QFETCH (int, max_length);
+ QFETCH (bool, allow_compound);
+ QFETCH (QString, expected);
+
+ QCOMPARE (CallsignValidator::normalizeStoredInput (
+ input, max_length, allow_compound), expected);
+}
+
+QTEST_GUILESS_MAIN (TestCallsignValidator)
+
+#include "test_callsign_validator.moc"
diff --git a/tests/unit/common/test_configuration_dialog_layout.cpp b/tests/unit/common/test_configuration_dialog_layout.cpp
new file mode 100644
index 00000000..019147af
--- /dev/null
+++ b/tests/unit/common/test_configuration_dialog_layout.cpp
@@ -0,0 +1,521 @@
+#include <QApplication>
+#include <QDialog>
+#include <QDialogButtonBox>
+#include <QFrame>
+#include <QGroupBox>
+#include <QLabel>
+#include <QLayout>
+#include <QPushButton>
+#include <QScrollArea>
+#include <QScrollBar>
+#include <QStyle>
+#include <QStringList>
+#include <QTabBar>
+#include <QTabWidget>
+#include <QTableView>
+#include <QTest>
+#include <QWheelEvent>
+
+#include "models/DecodeHighlightingModel.hpp"
+#include "widgets/SettingsDialogLayout.hpp"
+
+#include "ui_Configuration.h"
+
+namespace
+{
+ struct DialogFixture
+ {
+ explicit DialogFixture (int font_delta = 0)
+ {
+ if (font_delta)
+ {
+ auto font = dialog.font ();
+ font.setPointSize (font.pointSize () + font_delta);
+ dialog.setFont (font);
+ }
+
+ ui.setupUi (&dialog);
+ highlighting_model.set_font (dialog.font ());
+ ui.highlighting_list_view->setModel (&highlighting_model);
+ SettingsDialogLayout::install (ui);
+ }
+
+ QDialog dialog;
+ Ui::configuration_dialog ui;
+ DecodeHighlightingModel highlighting_model;
+ };
+
+ QList<QWidget *> scrollablePages (Ui::configuration_dialog const& ui)
+ {
+ return {
+ ui.general_tab,
+ ui.radio_tab,
+ ui.audio_tab,
+ ui.reporting_tab,
+ ui.colors_tab,
+ ui.advanced_tab,
+ ui.alerts_tab,
+ ui.filters_tab,
+ };
+ }
+
+ QList<QWidget *> allPages (Ui::configuration_dialog const& ui)
+ {
+ return {
+ ui.general_tab,
+ ui.radio_tab,
+ ui.audio_tab,
+ ui.tx_macros_tab,
+ ui.reporting_tab,
+ ui.frequencies_tab,
+ ui.colors_tab,
+ ui.advanced_tab,
+ ui.alerts_tab,
+ ui.filters_tab,
+ };
+ }
+
+ void settleLayouts ()
+ {
+ QCoreApplication::sendPostedEvents ();
+ QApplication::processEvents ();
+ }
+
+ void showDialog (QDialog& dialog, QSize size)
+ {
+ dialog.ensurePolished ();
+ dialog.layout ()->activate ();
+ dialog.resize (size);
+ dialog.show ();
+ settleLayouts ();
+ }
+
+ QRect geometryIn (QWidget const * widget, QWidget const * ancestor)
+ {
+ return {widget->mapTo (ancestor, {}), widget->size ()};
+ }
+
+ bool isFullyInside (QWidget const * widget, QWidget const * ancestor)
+ {
+ return ancestor->contentsRect ().contains (geometryIn (widget, ancestor));
+ }
+
+ bool isFullyVisible (QWidget const * widget, QScrollArea const * scroll_area)
+ {
+ return scroll_area->viewport ()->rect ().contains (
+ geometryIn (widget, scroll_area->viewport ()));
+ }
+
+ QString sizeText (QSize size)
+ {
+ return QString {"%1x%2"}.arg (size.width ()).arg (size.height ());
+ }
+
+ QString scrollDiagnostics (QWidget const * page, QDialog const& dialog,
+ QScrollArea const * scroll_area)
+ {
+ auto const * content = scroll_area->widget ();
+ return QString {"%1 style=%2 font=%3/%4pt dialog=%5 viewport=%6 "
+ "content=%7 contentHint=%8 contentMinimumHint=%9 ranges=%10x%11"}
+ .arg (page->objectName (), qApp->style ()->objectName (), dialog.font ().family ())
+ .arg (dialog.font ().pointSizeF ())
+ .arg (sizeText (dialog.size ()), sizeText (scroll_area->viewport ()->size ()),
+ sizeText (content->size ()), sizeText (content->sizeHint ()),
+ sizeText (content->minimumSizeHint ()))
+ .arg (scroll_area->horizontalScrollBar ()->maximum ())
+ .arg (scroll_area->verticalScrollBar ()->maximum ());
+ }
+
+ void sendWheelEvent (QWidget * target, QPoint angle_delta)
+ {
+ auto const local_position = QPointF {target->rect ().center ()};
+ auto const global_position = QPointF {target->mapToGlobal (local_position.toPoint ())};
+ QWheelEvent event {local_position, global_position, {}, angle_delta,
+ Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, false};
+ QApplication::sendEvent (target, &event);
+ settleLayouts ();
+ }
+}
+
+class TestConfigurationDialogLayout final
+ : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ void pagesRetainIdentityAndScrollingPolicy ();
+ void windowSizeIsBoundedByAvailableGeometry ();
+ void compactControlsKeepNaturalGeometry_data ();
+ void compactControlsKeepNaturalGeometry ();
+ void constrainedDialogKeepsNavigationAndActionsReachable_data ();
+ void constrainedDialogKeepsNavigationAndActionsReachable ();
+ void preferredDialogSizeKeepsPagesUsable_data ();
+ void preferredDialogSizeKeepsPagesUsable ();
+ void keyboardFocusRevealsOffscreenControls ();
+ void wheelEventsScrollThePage ();
+ void colorsPageOwnsVerticalScrolling ();
+};
+
+void TestConfigurationDialogLayout::pagesRetainIdentityAndScrollingPolicy ()
+{
+ DialogFixture fixture;
+ auto& ui = fixture.ui;
+
+ auto const pages = allPages (ui);
+ QStringList const page_names {
+ "general_tab",
+ "radio_tab",
+ "audio_tab",
+ "tx_macros_tab",
+ "reporting_tab",
+ "frequencies_tab",
+ "colors_tab",
+ "advanced_tab",
+ "alerts_tab",
+ "filters_tab",
+ };
+
+ QCOMPARE (ui.configuration_tabs->count (), page_names.size ());
+ for (int index = 0; index < pages.size (); ++index)
+ {
+ QCOMPARE (ui.configuration_tabs->widget (index), pages.at (index));
+ QCOMPARE (pages.at (index)->objectName (), page_names.at (index));
+ QVERIFY (!ui.configuration_tabs->tabText (index).isEmpty ());
+ }
+
+ SettingsDialogLayout::install (ui);
+ for (auto * page : scrollablePages (ui))
+ {
+ auto * scroll_area = SettingsDialogLayout::pageScrollArea (page);
+ QVERIFY (scroll_area);
+ QCOMPARE (scroll_area->parentWidget (), page);
+ QCOMPARE (scroll_area->objectName (), page->objectName () + "_scroll_area");
+ QCOMPARE (scroll_area->focusPolicy (), Qt::NoFocus);
+ QCOMPARE (scroll_area->viewport ()->focusPolicy (), Qt::NoFocus);
+ QCOMPARE (scroll_area->horizontalScrollBar ()->focusPolicy (), Qt::NoFocus);
+ QCOMPARE (scroll_area->verticalScrollBar ()->focusPolicy (), Qt::NoFocus);
+ QCOMPARE (scroll_area->frameShape (), QFrame::NoFrame);
+ QCOMPARE (scroll_area->horizontalScrollBarPolicy (), Qt::ScrollBarAsNeeded);
+ QCOMPARE (scroll_area->verticalScrollBarPolicy (), Qt::ScrollBarAsNeeded);
+ QVERIFY (scroll_area->widgetResizable ());
+ QVERIFY (scroll_area->widget ());
+ QCOMPARE (scroll_area->widget ()->focusPolicy (), Qt::NoFocus);
+ QCOMPARE (page->findChildren<QScrollArea *> (QString {}, Qt::FindDirectChildrenOnly).size (), 1);
+ QVERIFY (scroll_area->widget ()->findChildren<QScrollArea *>().isEmpty ());
+ }
+
+ auto * general_scroll_area = SettingsDialogLayout::pageScrollArea (ui.general_tab);
+ QVERIFY (general_scroll_area->widget ()->isAncestorOf (ui.callsign_line_edit));
+ QCOMPARE (ui.callsign_label->buddy (), ui.callsign_line_edit);
+ auto * colors_scroll_area = SettingsDialogLayout::pageScrollArea (ui.colors_tab);
+ QVERIFY (colors_scroll_area->widget ()->isAncestorOf (ui.highlighting_list_view));
+ QCOMPARE (ui.highlighting_list_view->verticalScrollBarPolicy (), Qt::ScrollBarAlwaysOff);
+ QCOMPARE (SettingsDialogLayout::pageScrollArea (ui.tx_macros_tab), nullptr);
+ QCOMPARE (SettingsDialogLayout::pageScrollArea (ui.frequencies_tab), nullptr);
+ QVERIFY (ui.configuration_tabs->tabBar ()->usesScrollButtons ());
+}
+
+void TestConfigurationDialogLayout::windowSizeIsBoundedByAvailableGeometry ()
+{
+ QMargins const frame_margins {10, 20, 10, 20};
+ QSize const available {1200, 900};
+
+ QCOMPARE (SettingsDialogLayout::boundedWindowSize ({800, 600}, available, frame_margins),
+ QSize (800, 600));
+ QCOMPARE (SettingsDialogLayout::boundedWindowSize ({1400, 1000}, available, frame_margins),
+ QSize (1180, 860));
+ QCOMPARE (SettingsDialogLayout::boundedWindowSize ({1400, 500}, available, frame_margins),
+ QSize (1180, 500));
+ QCOMPARE (SettingsDialogLayout::boundedWindowSize ({100, 100}, {10, 10}, frame_margins),
+ QSize (1, 1));
+}
+
+void TestConfigurationDialogLayout::compactControlsKeepNaturalGeometry_data ()
+{
+ QTest::addColumn<int> ("font_delta");
+ QTest::newRow ("default-font") << 0;
+ QTest::newRow ("larger-accessibility-font") << 4;
+}
+
+void TestConfigurationDialogLayout::compactControlsKeepNaturalGeometry ()
+{
+ QFETCH (int, font_delta);
+
+ DialogFixture fixture {font_delta};
+ auto& dialog = fixture.dialog;
+ auto& ui = fixture.ui;
+ showDialog (dialog, {640, 480});
+
+ ui.configuration_tabs->setCurrentWidget (ui.general_tab);
+ settleLayouts ();
+ QVERIFY (qAbs (ui.grid_line_edit->geometry ().center ().y ()
+ - ui.use_dynamic_grid->geometry ().center ().y ()) <= 2);
+
+ ui.configuration_tabs->setCurrentWidget (ui.advanced_tab);
+ settleLayouts ();
+ for (auto const& group_and_controls : {
+ qMakePair (ui.groupBox_10,
+ QList<QWidget *> {ui.cbx2ToneSpacing, ui.cbx4ToneSpacing}),
+ qMakePair (ui.groupBox_7,
+ QList<QWidget *> {ui.rbLowSidelobes, ui.rbMaxSensitivity}),
+ })
+ {
+ auto * group = group_and_controls.first;
+ QCOMPARE (group->sizePolicy ().verticalPolicy (), QSizePolicy::Minimum);
+ QVERIFY (group->height () >= group->sizeHint ().height ());
+ for (auto * control : group_and_controls.second)
+ {
+ QVERIFY (isFullyInside (control, group));
+ }
+ }
+}
+
+void TestConfigurationDialogLayout::constrainedDialogKeepsNavigationAndActionsReachable_data ()
+{
+ QTest::addColumn<int> ("font_delta");
+ QTest::newRow ("default-font") << 0;
+ QTest::newRow ("larger-accessibility-font") << 4;
+}
+
+void TestConfigurationDialogLayout::constrainedDialogKeepsNavigationAndActionsReachable ()
+{
+ QFETCH (int, font_delta);
+
+ QWidget host;
+ DialogFixture fixture {font_delta};
+ auto& dialog = fixture.dialog;
+ auto& ui = fixture.ui;
+ dialog.setParent (&host, Qt::Widget);
+ host.show ();
+ QSize const constrained_size {640, 480};
+ showDialog (dialog, constrained_size);
+
+ QCOMPARE (dialog.size (), constrained_size);
+ QVERIFY (ui.configuration_tabs->isVisibleTo (&dialog));
+ QVERIFY (isFullyInside (ui.configuration_tabs, &dialog));
+ QVERIFY (ui.configuration_dialog_button_box->isVisibleTo (&dialog));
+ QVERIFY (isFullyInside (ui.configuration_dialog_button_box, &dialog));
+
+ auto * ok = ui.configuration_dialog_button_box->button (QDialogButtonBox::Ok);
+ auto * cancel = ui.configuration_dialog_button_box->button (QDialogButtonBox::Cancel);
+ QVERIFY (ok);
+ QVERIFY (cancel);
+ auto const button_box_geometry = geometryIn (ui.configuration_dialog_button_box, &dialog);
+
+ for (int index = 0; index < ui.configuration_tabs->count (); ++index)
+ {
+ ui.configuration_tabs->setCurrentIndex (index);
+ settleLayouts ();
+
+ QCOMPARE (ui.configuration_tabs->currentWidget (), allPages (ui).at (index));
+ QVERIFY (ui.configuration_tabs->currentWidget ()->isVisibleTo (&dialog));
+ QVERIFY (ui.configuration_tabs->tabBar ()->rect ().intersects (
+ ui.configuration_tabs->tabBar ()->tabRect (index)));
+ QVERIFY (isFullyInside (ui.configuration_dialog_button_box, &dialog));
+ QCOMPARE (geometryIn (ui.configuration_dialog_button_box, &dialog), button_box_geometry);
+ QVERIFY (ok->isVisibleTo (&dialog));
+ QVERIFY (cancel->isVisibleTo (&dialog));
+ QVERIFY (isFullyInside (ok, &dialog));
+ QVERIFY (isFullyInside (cancel, &dialog));
+
+ if (auto * scroll_area = SettingsDialogLayout::pageScrollArea (
+ ui.configuration_tabs->currentWidget ()))
+ {
+ auto const minimum_hint = scroll_area->widget ()->minimumSizeHint ();
+ auto const message = scrollDiagnostics (ui.configuration_tabs->currentWidget (),
+ dialog, scroll_area);
+ QVERIFY2 (scroll_area->widget ()->width () >= minimum_hint.width (),
+ qPrintable (message));
+ QVERIFY2 (scroll_area->widget ()->height () >= minimum_hint.height (),
+ qPrintable (message));
+ }
+ }
+
+ ui.configuration_tabs->setCurrentWidget (ui.frequencies_tab);
+ settleLayouts ();
+ for (auto * table : {ui.frequencies_table_view, ui.stations_table_view})
+ {
+ QVERIFY (table->height () >= table->minimumHeight ());
+ QVERIFY (table->viewport ()->height () >= table->fontMetrics ().height ());
+ QVERIFY (isFullyInside (table, ui.frequencies_tab));
+ }
+
+ ui.configuration_tabs->setCurrentWidget (ui.advanced_tab);
+ settleLayouts ();
+ auto * advanced_scroll_area = SettingsDialogLayout::pageScrollArea (ui.advanced_tab);
+ QVERIFY (advanced_scroll_area->verticalScrollBar ()->maximum () > 0);
+ advanced_scroll_area->verticalScrollBar ()->setValue (
+ advanced_scroll_area->verticalScrollBar ()->maximum ());
+ advanced_scroll_area->horizontalScrollBar ()->setValue (
+ advanced_scroll_area->horizontalScrollBar ()->maximum ());
+ settleLayouts ();
+ QCOMPARE (geometryIn (ui.configuration_dialog_button_box, &dialog), button_box_geometry);
+
+ dialog.resize ({420, 480});
+ settleLayouts ();
+ QVERIFY (ui.configuration_tabs->tabBar ()->width ()
+ < ui.configuration_tabs->tabBar ()->sizeHint ().width ());
+ for (int index = 0; index < ui.configuration_tabs->count (); ++index)
+ {
+ ui.configuration_tabs->setCurrentIndex (index);
+ settleLayouts ();
+ QVERIFY (ui.configuration_tabs->tabBar ()->rect ().intersects (
+ ui.configuration_tabs->tabBar ()->tabRect (index)));
+ QVERIFY (isFullyInside (ui.configuration_dialog_button_box, &dialog));
+ }
+}
+
+void TestConfigurationDialogLayout::preferredDialogSizeKeepsPagesUsable_data ()
+{
+ QTest::addColumn<int> ("font_delta");
+ QTest::newRow ("default-font") << 0;
+ QTest::newRow ("larger-accessibility-font") << 4;
+}
+
+void TestConfigurationDialogLayout::preferredDialogSizeKeepsPagesUsable ()
+{
+ QFETCH (int, font_delta);
+
+ QWidget host;
+ DialogFixture fixture {font_delta};
+ auto& dialog = fixture.dialog;
+ auto& ui = fixture.ui;
+ dialog.setParent (&host, Qt::Widget);
+ host.show ();
+ showDialog (dialog, {827, 705});
+ auto const preferred_size = SettingsDialogLayout::preferredWindowSize (dialog, ui);
+ QVERIFY (preferred_size.width () >= dialog.sizeHint ().width ());
+ QVERIFY (preferred_size.height () >= dialog.sizeHint ().height ());
+ showDialog (dialog, preferred_size);
+
+ int vertically_scrolling_pages = 0;
+ for (auto * page : scrollablePages (ui))
+ {
+ ui.configuration_tabs->setCurrentWidget (page);
+ settleLayouts ();
+ auto * scroll_area = SettingsDialogLayout::pageScrollArea (page);
+ auto const message = scrollDiagnostics (page, dialog, scroll_area);
+ QVERIFY2 (scroll_area->horizontalScrollBar ()->maximum () == 0,
+ qPrintable (message));
+ if (scroll_area->verticalScrollBar ()->maximum () > 0)
+ {
+ ++vertically_scrolling_pages;
+ }
+ }
+ QVERIFY (vertically_scrolling_pages <= 1);
+
+ ui.configuration_tabs->setCurrentWidget (ui.general_tab);
+ settleLayouts ();
+ QVERIFY (ui.station_group_box->height () <= ui.station_group_box->sizeHint ().height () + 2);
+
+ dialog.resize (preferred_size.width (), qMax (480, preferred_size.height () - 200));
+ settleLayouts ();
+ for (auto * page : scrollablePages (ui))
+ {
+ ui.configuration_tabs->setCurrentWidget (page);
+ settleLayouts ();
+ auto * scroll_area = SettingsDialogLayout::pageScrollArea (page);
+ auto const message = scrollDiagnostics (page, dialog, scroll_area);
+ QVERIFY2 (scroll_area->horizontalScrollBar ()->maximum () == 0,
+ qPrintable (message));
+ }
+}
+
+void TestConfigurationDialogLayout::keyboardFocusRevealsOffscreenControls ()
+{
+ DialogFixture fixture;
+ auto& dialog = fixture.dialog;
+ auto& ui = fixture.ui;
+ ui.configuration_tabs->setCurrentWidget (ui.advanced_tab);
+ showDialog (dialog, {620, 360});
+ QApplication::setActiveWindow (&dialog);
+ settleLayouts ();
+
+ auto * advanced_scroll_area = SettingsDialogLayout::pageScrollArea (ui.advanced_tab);
+ auto * vertical_scroll_bar = advanced_scroll_area->verticalScrollBar ();
+ QVERIFY (vertical_scroll_bar->maximum () > 0);
+ vertical_scroll_bar->setValue (vertical_scroll_bar->minimum ());
+ advanced_scroll_area->horizontalScrollBar ()->setValue (
+ advanced_scroll_area->horizontalScrollBar ()->minimum ());
+ settleLayouts ();
+
+ QVERIFY (!isFullyVisible (ui.pbTestCloudlog, advanced_scroll_area));
+ auto const button_box_geometry = geometryIn (ui.configuration_dialog_button_box, &dialog);
+ ui.pbTestCloudlog->setFocus (Qt::TabFocusReason);
+
+ QTRY_COMPARE (QApplication::focusWidget (), ui.pbTestCloudlog);
+ QTRY_VERIFY (vertical_scroll_bar->value () > vertical_scroll_bar->minimum ());
+ QTRY_VERIFY (isFullyVisible (ui.pbTestCloudlog, advanced_scroll_area));
+ QCOMPARE (geometryIn (ui.configuration_dialog_button_box, &dialog), button_box_geometry);
+
+ ui.configuration_tabs->setCurrentWidget (ui.filters_tab);
+ dialog.resize ({420, 480});
+ settleLayouts ();
+ auto * filters_scroll_area = SettingsDialogLayout::pageScrollArea (ui.filters_tab);
+ auto * horizontal_scroll_bar = filters_scroll_area->horizontalScrollBar ();
+ QVERIFY (horizontal_scroll_bar->maximum () > 0);
+ auto * ok = ui.configuration_dialog_button_box->button (QDialogButtonBox::Ok);
+ ok->setFocus (Qt::TabFocusReason);
+ QTRY_COMPARE (QApplication::focusWidget (), ok);
+ horizontal_scroll_bar->setValue (horizontal_scroll_bar->maximum ());
+ filters_scroll_area->verticalScrollBar ()->setValue (
+ filters_scroll_area->verticalScrollBar ()->minimum ());
+ settleLayouts ();
+ auto const filters_button_box_geometry = geometryIn (
+ ui.configuration_dialog_button_box, &dialog);
+
+ auto * left_side_control = ui.Territory1;
+ auto const initial_horizontal_position = horizontal_scroll_bar->value ();
+ QVERIFY (!isFullyVisible (left_side_control, filters_scroll_area));
+ left_side_control->setFocus (Qt::TabFocusReason);
+ QTRY_COMPARE (QApplication::focusWidget (), left_side_control);
+ QTRY_VERIFY (horizontal_scroll_bar->value () < initial_horizontal_position);
+ QTRY_VERIFY (isFullyVisible (left_side_control, filters_scroll_area));
+ QCOMPARE (geometryIn (ui.configuration_dialog_button_box, &dialog),
+ filters_button_box_geometry);
+}
+
+void TestConfigurationDialogLayout::wheelEventsScrollThePage ()
+{
+ DialogFixture fixture;
+ auto& dialog = fixture.dialog;
+ auto& ui = fixture.ui;
+ ui.configuration_tabs->setCurrentWidget (ui.advanced_tab);
+ showDialog (dialog, {620, 360});
+
+ auto * scroll_area = SettingsDialogLayout::pageScrollArea (ui.advanced_tab);
+ auto * scroll_bar = scroll_area->verticalScrollBar ();
+ QVERIFY (scroll_bar->maximum () > 0);
+ auto const button_box_geometry = geometryIn (ui.configuration_dialog_button_box, &dialog);
+
+ scroll_bar->setValue (scroll_bar->minimum ());
+ sendWheelEvent (scroll_area->viewport (), {0, -120});
+ QVERIFY (scroll_bar->value () > scroll_bar->minimum ());
+ QCOMPARE (geometryIn (ui.configuration_dialog_button_box, &dialog), button_box_geometry);
+
+}
+
+void TestConfigurationDialogLayout::colorsPageOwnsVerticalScrolling ()
+{
+ DialogFixture fixture;
+ auto& dialog = fixture.dialog;
+ auto& ui = fixture.ui;
+ ui.configuration_tabs->setCurrentWidget (ui.colors_tab);
+ showDialog (dialog, {620, 360});
+
+ auto * page_scroll_area = SettingsDialogLayout::pageScrollArea (ui.colors_tab);
+ auto * page_scroll_bar = page_scroll_area->verticalScrollBar ();
+ QCOMPARE (ui.highlighting_list_view->model ()->rowCount (), 16);
+ QCOMPARE (ui.highlighting_list_view->verticalScrollBarPolicy (), Qt::ScrollBarAlwaysOff);
+ QCOMPARE (ui.highlighting_list_view->verticalScrollBar ()->maximum (), 0);
+ QVERIFY (page_scroll_bar->maximum () > 0);
+
+ page_scroll_bar->setValue (page_scroll_bar->minimum ());
+ sendWheelEvent (ui.highlighting_list_view->viewport (), {0, -120});
+ QVERIFY (page_scroll_bar->value () > page_scroll_bar->minimum ());
+ QCOMPARE (ui.highlighting_list_view->verticalScrollBar ()->value (), 0);
+}
+
+QTEST_MAIN (TestConfigurationDialogLayout)
+
+#include "test_configuration_dialog_layout.moc"
diff --git a/tests/unit/common/test_decode_output_plan.cpp b/tests/unit/common/test_decode_output_plan.cpp
new file mode 100644
index 00000000..8e54f0c9
--- /dev/null
+++ b/tests/unit/common/test_decode_output_plan.cpp
@@ -0,0 +1,1146 @@
+#include <QtTest>
+
+#include "DecodeOutputPlan.hpp"
+#include "Decoder/decodedtext.h"
+
+class TestDecodeOutputPlan final
+ : public QObject
+{
+ Q_OBJECT
+
+ using ActionKind = DecodeOutputPlan::ActionKind;
+ using SpecOp = SpecialOperatingActivity;
+
+ enum FilterOption
+ {
+ InitiallyFiltered = 1 << 0,
+ AlwaysPass = 1 << 1,
+ Blacklist = 1 << 2,
+ Whitelist = 1 << 3,
+ Bypass = 1 << 4,
+ WaitAndPounceOnly = 1 << 5,
+ ScoringPounce = 1 << 6,
+ NonScoringPounce = 1 << 7,
+ HideIgnored = 1 << 8,
+ HideWorkedToday = 1 << 9
+ };
+
+ enum FilterOutcome
+ {
+ KeywordFiltered = 1 << 0,
+ FinallyFiltered = 1 << 1,
+ ContinueProcessing = 1 << 2,
+ AlwaysPassed = 1 << 3,
+ ResetPounceScores = 1 << 4,
+ DisplayLeft = 1 << 5
+ };
+
+ static QString actionName(ActionKind kind)
+ {
+ switch (kind) {
+ case ActionKind::ShowQsyMessage: return "qsy";
+ case ActionKind::AccumulateFoxActivity: return "fox-activity";
+ case ActionKind::IncrementDecodeCount: return "count";
+ case ActionKind::WriteAll: return "all.txt";
+ case ActionKind::UploadWsprSpot: return "wspr";
+ case ActionKind::UpdateArrlActivity: return "arrl";
+ case ActionKind::FlushFoxActivity: return "flush-fox";
+ }
+ return "unknown";
+ }
+
+ static QStringList actionNames(QVector<DecodeOutputPlan::Action> const& actions)
+ {
+ QStringList names;
+ for (auto const& action : actions) names.append(actionName(action.kind));
+ return names;
+ }
+
+ static DecodeOutputPlan::PreparationContext preparationContext()
+ {
+ DecodeOutputPlan::PreparationContext context;
+ context.mode = "FT8";
+ context.myCall = "K1ABC";
+ context.qsyEnabled = true;
+ return context;
+ }
+
+ static DecodeOutputPlan::RoutingContext routingContext()
+ {
+ DecodeOutputPlan::RoutingContext context;
+ context.mode = "FT8";
+ context.myCall = "K1ABC";
+ context.baseCall = "K1ABC";
+ context.hisCall = "W1AW";
+ context.rxFrequency = 1500;
+ context.wideGraphRxFrequency = 1500;
+ return context;
+ }
+
+private slots:
+ void wireFormatRegressionCorpus_data()
+ {
+ QTest::addColumn<QByteArray>("rawLine");
+ QTest::addColumn<QByteArray>("expectedNormalizedLine");
+ QTest::addColumn<QString>("mode");
+ QTest::addColumn<int>("specOp");
+ QTest::addColumn<bool>("activeStationsAvailable");
+ QTest::addColumn<int>("expectedDisposition");
+ QTest::addColumn<bool>("expectedAveraged");
+ QTest::addColumn<int>("expectedAverageCount");
+ QTest::addColumn<bool>("expectedFrequencySpread");
+ QTest::addColumn<float>("expectedSpread");
+ QTest::addColumn<bool>("expectedDecoded");
+ QTest::addColumn<int>("expectedSingleDecodes");
+ QTest::addColumn<int>("expectedAveragedDecodes");
+ QTest::addColumn<QStringList>("expectedActions");
+
+ auto legacyNormalized = [] (QByteArray line) {
+ line.insert(qMin(44, line.size()), QByteArray(14, ' '));
+ return line;
+ };
+ auto addRow = [] (char const * name, QByteArray const& rawLine,
+ QByteArray const& normalizedLine, QString const& mode,
+ SpecOp specOp, bool activeStationsAvailable,
+ DecodeOutputPlan::LineDisposition disposition,
+ bool averaged, int averageCount, bool haveSpread, float spread,
+ bool decoded, int singleDecodes, int averagedDecodes,
+ QStringList const& actions) {
+ QTest::newRow(name) << rawLine << normalizedLine << mode << static_cast<int>(specOp)
+ << activeStationsAvailable << static_cast<int>(disposition)
+ << averaged << averageCount << haveSpread << spread << decoded
+ << singleDecodes << averagedDecodes << actions;
+ };
+
+ using Disposition = DecodeOutputPlan::LineDisposition;
+ QStringList const decodeActions {"qsy", "count", "all.txt"};
+ QStringList const finishActions {"qsy"};
+
+ QByteArray const ft8 {
+ "133430 -2 -0.8 1197 ~ CQ F5RXL IN94 \r\n"};
+ addRow("real FT8", ft8, ft8.left(ft8.size() - 2), "FT8", SpecOp::NONE, false,
+ Disposition::Decode, false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const ft8Ap = QByteArray {"060500 -10 0.3 1500 ~ "}
+ + QByteArray {"CQ W1AW FN31"}.leftJustified(36, ' ') + "? a7\n";
+ addRow("FT8 AP low confidence", ft8Ap, ft8Ap.left(ft8Ap.size() - 1),
+ "FT8", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const ft4 {
+ "000002 -10 -0.2 296 + N1TRK N4FKH 569 VA \n"};
+ addRow("real FT4 contest", ft4, ft4.left(ft4.size() - 1),
+ "FT4", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const jt9 {"1742 -5 1.2 1505 @ JA1KAU PD0JAC -23 \n"};
+ auto jt9Normalized = jt9.left(jt9.size() - 1);
+ addRow("real JT9", jt9, legacyNormalized(jt9Normalized),
+ "JT9", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const jt65 = QByteArray {"2343 -11 0.8 1259 # "}
+ + QByteArray {"YV6BFE F6GUU R-08"}.leftJustified(22, ' ') + " \n";
+ auto jt65Normalized = jt65.left(jt65.size() - 1);
+ addRow("ordinary JT65", jt65, legacyNormalized(jt65Normalized),
+ "JT65", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const jt65Average = QByteArray {"2343 -18 0.3 1500 # "}
+ + QByteArray {"K1ABC W1AW R-10"}.leftJustified(22, ' ') + " d22\n";
+ auto jt65AverageNormalized = jt65Average.left(jt65Average.size() - 1);
+ addRow("averaged deep JT65", jt65Average, legacyNormalized(jt65AverageNormalized),
+ "JT65", SpecOp::NONE, false, Disposition::Decode,
+ true, 2, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const jt65NumericOnly {"2343 -20 0.3 1500\n"};
+ auto jt65NumericOnlyNormalized = jt65NumericOnly.left(jt65NumericOnly.size() - 1);
+ addRow("numeric-only JT65", jt65NumericOnly,
+ legacyNormalized(jt65NumericOnlyNormalized),
+ "JT65", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const q65 {
+ "1621 -24 2.8 697 : W7GJ N8JX EN73 q0 \n"};
+ addRow("real long-period Q65", q65, q65.left(q65.size() - 1),
+ "Q65", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const q65Average = QByteArray {"060500 -20 0.3 1500 : "}
+ + QByteArray {"K1ABC W1AW R-10"}.leftJustified(37, ' ') + " q23\n";
+ addRow("short-period averaged Q65", q65Average,
+ q65Average.left(q65Average.size() - 1),
+ "Q65", SpecOp::NONE, false, Disposition::Decode,
+ true, 3, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const fst4Short = QByteArray {"060500 -18 0.3 1500 ` "}
+ .append(QByteArray {"CQ W1AW FN31"}.leftJustified(37, ' '))
+ .append(" ").leftJustified(70, ' ');
+ addRow("short-period FST4", fst4Short + "\n", fst4Short,
+ "FST4", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray fst4Spread = QByteArray {"0058 16 0.4 1331 ` "}
+ .append(QByteArray {"CQ K9KFR EN71"}.leftJustified(37, ' '))
+ .append(" ").leftJustified(70, ' ');
+ fst4Spread.replace(64, 6, " 1.250");
+ addRow("long-period FST4 spread", fst4Spread + "\n", fst4Spread.left(64),
+ "FST4", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, true, 1.25f, false, 0, 0, decodeActions);
+
+ QByteArray const fst4w = QByteArray {"0058 -20 0.4 1500 ` "}
+ .append(QByteArray {"CQ W1AW FN31"}.leftJustified(37, ' '))
+ .append(" ").leftJustified(70, ' ');
+ addRow("accepted FST4W", fst4w + "\n", fst4w,
+ "FST4W", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0,
+ {"qsy", "count", "all.txt", "wspr"});
+
+ QByteArray const msk144 {
+ "120500 8 8.7 1488 & K1JT WA4CQG EM72 \n"};
+ auto msk144Normalized = msk144.left(msk144.size() - 1);
+ addRow("real MSK144", msk144, legacyNormalized(msk144Normalized),
+ "MSK144", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const fox = QByteArray {"060500 -10 0.3 1500 ~ "}
+ + QByteArray {"K1ABC RR73; W9XYZ <KH1DX> -12"}.leftJustified(37, ' ') + " \n";
+ addRow("FOX dual reply", fox, fox.left(fox.size() - 1),
+ "FT8", SpecOp::FOX, true, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0,
+ {"qsy", "fox-activity", "count", "all.txt"});
+
+ QByteArray const hound {"060500 -10 0.3 1500 ~ $VERIFY$ KH1DX 920749\n"};
+ addRow("variable-length SuperFox Hound", hound, hound.left(hound.size() - 1),
+ "FT8", SpecOp::HOUND, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const completion {"<DecodeFinished> 0 14 0\n"};
+ addRow("ordinary completion", completion, completion.left(completion.size() - 1),
+ "FT8", SpecOp::NONE, false, Disposition::Finish,
+ false, 0, false, 0.0f, true, 0, 0, finishActions);
+
+ QByteArray const q65Completion {"<DecodeFinished> 1 6 2003\n"};
+ addRow("packed Q65 completion", q65Completion,
+ q65Completion.left(q65Completion.size() - 1),
+ "Q65", SpecOp::NONE, false, Disposition::Finish,
+ false, 0, false, 0.0f, true, 2, 3, finishActions);
+
+ QByteArray const truncatedRecord {"060500 -20 0.3 1500\n"};
+ addRow("truncated decode record", truncatedRecord,
+ truncatedRecord.left(truncatedRecord.size() - 1),
+ "FT8", SpecOp::NONE, false, Disposition::Decode,
+ false, 0, false, 0.0f, false, 0, 0, decodeActions);
+
+ QByteArray const truncatedCompletion {"<DecodeFinished>\n"};
+ addRow("truncated completion", truncatedCompletion,
+ truncatedCompletion.left(truncatedCompletion.size() - 1),
+ "FT8", SpecOp::NONE, false, Disposition::Finish,
+ false, 0, false, 0.0f, false, 0, 0, finishActions);
+ }
+
+ void wireFormatRegressionCorpus()
+ {
+ QFETCH(QByteArray, rawLine);
+ QFETCH(QByteArray, expectedNormalizedLine);
+ QFETCH(QString, mode);
+ QFETCH(int, specOp);
+ QFETCH(bool, activeStationsAvailable);
+ QFETCH(int, expectedDisposition);
+ QFETCH(bool, expectedAveraged);
+ QFETCH(int, expectedAverageCount);
+ QFETCH(bool, expectedFrequencySpread);
+ QFETCH(float, expectedSpread);
+ QFETCH(bool, expectedDecoded);
+ QFETCH(int, expectedSingleDecodes);
+ QFETCH(int, expectedAveragedDecodes);
+ QFETCH(QStringList, expectedActions);
+
+ auto context = preparationContext();
+ context.mode = mode;
+ context.specOp = static_cast<SpecOp>(specOp);
+ context.activeStationsAvailable = activeStationsAvailable;
+
+ auto const plan = DecodeOutputPlan::prepareLine(rawLine, context);
+
+ QCOMPARE(plan.rawLine, rawLine);
+ QCOMPARE(plan.normalizedLine, expectedNormalizedLine);
+ QCOMPARE(static_cast<int>(plan.disposition), expectedDisposition);
+ QVERIFY(plan.reason.isEmpty());
+ if (expectedDisposition == static_cast<int>(DecodeOutputPlan::LineDisposition::Decode)) {
+ QCOMPARE(plan.logicMessage.string(), plan.decodedForLogic);
+ } else {
+ QVERIFY(plan.logicMessage.string().isEmpty());
+ }
+ QCOMPARE(plan.averaged, expectedAveraged);
+ QCOMPARE(plan.averageCount, expectedAverageCount);
+ QCOMPARE(plan.haveFrequencySpread, expectedFrequencySpread);
+ QCOMPARE(plan.frequencySpread, expectedSpread);
+ QCOMPARE(plan.batchHasDecodes, expectedDecoded);
+ QCOMPARE(plan.q65SingleDecodes, expectedSingleDecodes);
+ QCOMPARE(plan.q65AveragedDecodes, expectedAveragedDecodes);
+ QCOMPARE(actionNames(plan.actions), expectedActions);
+ }
+
+ void validityRejectionMatrix_data()
+ {
+ QTest::addColumn<QByteArray>("rawLine");
+ QTest::addColumn<bool>("reduceFalseDecodes");
+ QTest::addColumn<int>("specOp");
+ QTest::addColumn<bool>("diskData");
+ QTest::addColumn<bool>("noA7Decodes");
+ QTest::addColumn<int>("expectedDisposition");
+ QTest::addColumn<QString>("expectedReason");
+ QTest::addColumn<QStringList>("expectedActions");
+
+ auto const decode = static_cast<int>(DecodeOutputPlan::LineDisposition::Decode);
+ auto const ignore = static_cast<int>(DecodeOutputPlan::LineDisposition::Ignore);
+ auto const none = static_cast<int>(SpecOp::NONE);
+ auto const hound = static_cast<int>(SpecOp::HOUND);
+ auto const fox = static_cast<int>(SpecOp::FOX);
+ QStringList const acceptedActions {"qsy", "count", "all.txt"};
+ QStringList const rejectedActions {"qsy"};
+
+ auto addRow = [&] (char const * name, QByteArray const& line, bool reduce,
+ int operation, bool disk, bool suppressA7, int disposition,
+ QString const& reason, QStringList const& actions) {
+ QTest::newRow(name) << line << reduce << operation << disk << suppressA7
+ << disposition << reason << actions;
+ };
+
+ QString const suspiciousReason {"suspicious low-SNR decode rejected"};
+ addRow("two hashes below -12", "060500 -13 0.3 1500 ~ <W1AW> <K1ABC> R-10",
+ false, none, false, false, ignore, suspiciousReason, rejectedActions);
+ addRow("two portable calls below -12", "060500 -13 0.3 1500 ~ W1AW/P K1ABC/P R-10",
+ false, none, false, false, ignore, suspiciousReason, rejectedActions);
+ addRow("two rover calls below -12", "060500 -13 0.3 1500 ~ W1AW/R K1ABC/R R-10",
+ false, none, false, false, ignore, suspiciousReason, rejectedActions);
+ addRow("rover question below -12", "060500 -13 0.3 1500 ~ W1AW/R K1ABC ?",
+ false, none, false, false, ignore, suspiciousReason, rejectedActions);
+ addRow("semicolon report below -12", "060500 -13 0.3 1500 ~ W1AW; K1ABC R -10",
+ false, none, false, false, ignore, suspiciousReason, rejectedActions);
+ addRow("suspicious shape at -12", "060500 -12 0.3 1500 ~ <W1AW> <K1ABC> R-10",
+ false, none, false, false, decode, {}, acceptedActions);
+
+ QString const reduceReason {"reduce-false-decodes rule rejected line"};
+ addRow("suspicious shape at -16 enabled", "060500 -16 0.3 1500 ~ ABCDEFGH K1ABC -10",
+ true, none, false, false, ignore, reduceReason, rejectedActions);
+ addRow("suspicious shape at -16 disabled", "060500 -16 0.3 1500 ~ ABCDEFGH K1ABC -10",
+ false, none, false, false, decode, {}, acceptedActions);
+ addRow("suspicious shape at -15", "060500 -15 0.3 1500 ~ ABCDEFGH K1ABC -10",
+ true, none, false, false, decode, {}, acceptedActions);
+ addRow("rover report at -18", "060500 -18 0.3 1500 ~ W1AW/R K1ABC -10",
+ true, none, false, false, decode, {}, acceptedActions);
+ addRow("rover report below -18", "060500 -19 0.3 1500 ~ W1AW/R K1ABC -10",
+ true, none, false, false, ignore, reduceReason, rejectedActions);
+ addRow("3-dot timing shape at -15", "060500 -15 3.1 1500 ~ CQ W1AW FN31",
+ true, none, false, false, decode, {}, acceptedActions);
+ addRow("2-dot timing shape below -15", "060500 -16 2.1 1500 ~ CQ W1AW FN31",
+ true, none, false, false, ignore, reduceReason, rejectedActions);
+ addRow("3-dot timing shape at -20", "060500 -20 3.1 1500 ~ CQ W1AW FN31",
+ true, none, false, false, ignore, reduceReason, rejectedActions);
+ addRow("2-dot timing shape below -20", "060500 -21 2.1 1500 ~ CQ W1AW FN31",
+ true, none, false, false, ignore, reduceReason, rejectedActions);
+
+ addRow("ordinary low-SNR CQ", "060500 -24 0.3 1500 ~ CQ W1AW FN31",
+ true, none, false, false, decode, {}, acceptedActions);
+ addRow("ordinary low-SNR direct report", "060500 -24 0.3 1500 ~ K1ABC W1AW -10",
+ true, none, false, false, decode, {}, acceptedActions);
+ addRow("hound bypasses suspicious low-SNR", "060500 -24 0.3 1500 ~ <W1AW> <K1ABC> R-10",
+ false, hound, false, false, decode, {}, acceptedActions);
+ addRow("hound bypasses reduce false decodes", "060500 -24 0.3 1500 ~ ABCDEFGH K1ABC -10",
+ true, hound, false, false, decode, {}, acceptedActions);
+
+ QString const a7Reason {"a7 decode rejected"};
+ addRow("a7 suppression", "060500 -10 0.3 1500 ~ W1AW K1ABC -10 a7",
+ false, none, false, true, ignore, a7Reason, rejectedActions);
+ addRow("disk data bypasses a7 suppression", "060500 -10 0.3 1500 ~ W1AW K1ABC -10 a7",
+ false, none, true, true, decode, {}, acceptedActions);
+ addRow("special operation CQ a7 exemption", "060500 -10 0.3 1500 ~ CQ W1AW FN31 a7",
+ false, fox, false, false, decode, {}, acceptedActions);
+ addRow("special operation R a7 exemption", "060500 -10 0.3 1500 ~ W1AW K1ABC R -10 a7",
+ false, fox, false, false, decode, {}, acceptedActions);
+ addRow("special operation RR73 a7 exemption", "060500 -10 0.3 1500 ~ W1AW K1ABC RR73 a7",
+ false, fox, false, false, decode, {}, acceptedActions);
+ }
+
+ void validityRejectionMatrix()
+ {
+ QFETCH(QByteArray, rawLine);
+ QFETCH(bool, reduceFalseDecodes);
+ QFETCH(int, specOp);
+ QFETCH(bool, diskData);
+ QFETCH(bool, noA7Decodes);
+ QFETCH(int, expectedDisposition);
+ QFETCH(QString, expectedReason);
+ QFETCH(QStringList, expectedActions);
+
+ auto context = preparationContext();
+ context.reduceFalseDecodes = reduceFalseDecodes;
+ context.specOp = static_cast<SpecOp>(specOp);
+ context.diskData = diskData;
+ context.noA7Decodes = noA7Decodes;
+
+ auto const plan = DecodeOutputPlan::prepareLine(rawLine, context);
+
+ QCOMPARE(static_cast<int>(plan.disposition), expectedDisposition);
+ QCOMPARE(plan.reason, expectedReason);
+ QCOMPARE(actionNames(plan.actions), expectedActions);
+ }
+
+ void preparationActionInvariants_data()
+ {
+ QTest::addColumn<QByteArray>("rawLine");
+ QTest::addColumn<QString>("mode");
+ QTest::addColumn<int>("specOp");
+ QTest::addColumn<bool>("activeStationsAvailable");
+ QTest::addColumn<bool>("noA7Decodes");
+ QTest::addColumn<bool>("noOwnCall");
+ QTest::addColumn<bool>("displayPoints");
+ QTest::addColumn<int>("expectedDisposition");
+ QTest::addColumn<QStringList>("expectedEarlyActions");
+ QTest::addColumn<bool>("expectedUpdate");
+
+ auto addRow = [] (char const * name, QByteArray const& rawLine, QString const& mode,
+ SpecOp specOp, bool activeStationsAvailable, bool noA7Decodes,
+ bool noOwnCall, bool displayPoints,
+ DecodeOutputPlan::LineDisposition disposition,
+ QStringList const& earlyActions, bool update = false) {
+ QTest::newRow(name) << rawLine << mode << static_cast<int>(specOp)
+ << activeStationsAvailable << noA7Decodes << noOwnCall
+ << displayPoints << static_cast<int>(disposition)
+ << earlyActions << update;
+ };
+
+ using Disposition = DecodeOutputPlan::LineDisposition;
+ addRow("ignored false decode", "060500 -13 0.3 1500 ~ <W1AW> <K1ABC> R-10\n",
+ "FT8", SpecOp::NONE, false, false, false, false,
+ Disposition::Ignore, {"qsy"});
+ addRow("rejected FOX a7 retains early actions",
+ "060500 -10 0.3 1500 ~ W1AW K1ABC -10 a7\n",
+ "FT8", SpecOp::FOX, true, true, false, false,
+ Disposition::Ignore, {"qsy", "fox-activity"});
+ addRow("decode completion", "<DecodeFinished> 1 6 2003\n",
+ "FT8", SpecOp::NONE, false, false, false, false,
+ Disposition::Finish, {"qsy"});
+ addRow("FST4W completion", "<DecodeFinished> 0 0 0\n",
+ "FST4W", SpecOp::NONE, false, false, false, false,
+ Disposition::Finish, {"qsy"});
+ addRow("ignored FST4W own call", "060500 -10 0.3 1500 ` CQ K1ABC FN31\n",
+ "FST4W", SpecOp::NONE, false, false, true, false,
+ Disposition::Ignore, {"qsy"});
+ addRow("accepted FST4W ordinary decode", "060500 -10 0.3 1500 ` CQ W1AW FN31\n",
+ "FST4W", SpecOp::NONE, false, false, false, false,
+ Disposition::Decode, {"qsy"});
+ addRow("accepted FT8 display-points update", "060500 -10 0.3 1500 ~ CQ W1AW FN31\n",
+ "FT8", SpecOp::NONE, false, false, false, true,
+ Disposition::Decode, {"qsy"}, true);
+ }
+
+ void preparationActionInvariants()
+ {
+ QFETCH(QByteArray, rawLine);
+ QFETCH(QString, mode);
+ QFETCH(int, specOp);
+ QFETCH(bool, activeStationsAvailable);
+ QFETCH(bool, noA7Decodes);
+ QFETCH(bool, noOwnCall);
+ QFETCH(bool, displayPoints);
+ QFETCH(int, expectedDisposition);
+ QFETCH(QStringList, expectedEarlyActions);
+ QFETCH(bool, expectedUpdate);
+
+ auto context = preparationContext();
+ context.mode = mode;
+ context.specOp = static_cast<SpecOp>(specOp);
+ context.activeStationsAvailable = activeStationsAvailable;
+ context.noA7Decodes = noA7Decodes;
+ context.noOwnCall = noOwnCall;
+ context.displayPoints = displayPoints;
+
+ auto const plan = DecodeOutputPlan::prepareLine(rawLine, context);
+ auto const names = actionNames(plan.actions);
+ QStringList earlyActions;
+ for (auto const& action : plan.actions) {
+ if (action.kind == ActionKind::ShowQsyMessage
+ || action.kind == ActionKind::AccumulateFoxActivity) {
+ earlyActions.append(actionName(action.kind));
+ QCOMPARE(action.text, QString {rawLine});
+ }
+ }
+
+ bool const accepted = expectedDisposition
+ == static_cast<int>(DecodeOutputPlan::LineDisposition::Decode);
+ QCOMPARE(static_cast<int>(plan.disposition), expectedDisposition);
+ QCOMPARE(earlyActions, expectedEarlyActions);
+ QCOMPARE(names.count("count"), accepted ? 1 : 0);
+ QCOMPARE(names.count("all.txt"), accepted ? 1 : 0);
+ QCOMPARE(names.count("wspr"), accepted && mode == "FST4W" ? 1 : 0);
+ QCOMPARE(names.count("arrl"), expectedUpdate ? 1 : 0);
+ QVERIFY(!names.contains("flush-fox"));
+ }
+
+ void retainsRawFoxActivityBeforeRejectedA7Decode()
+ {
+ auto context = preparationContext();
+ context.specOp = SpecOp::FOX;
+ context.activeStationsAvailable = true;
+ context.noA7Decodes = true;
+ QByteArray const rawLine {"060500 -20 0.3 1500 ~ CQ W1AW FN31 a7\n"};
+
+ auto const plan = DecodeOutputPlan::prepareLine(rawLine, context);
+
+ QCOMPARE(plan.disposition, DecodeOutputPlan::LineDisposition::Ignore);
+ QCOMPARE(plan.reason, QString {"a7 decode rejected"});
+ QCOMPARE(actionNames(plan.actions), QStringList({"qsy", "fox-activity"}));
+ }
+
+ void displayPointsRemovesA7BeforeFalseDecodeClassification()
+ {
+ auto context = preparationContext();
+ context.displayPoints = true;
+ context.noA7Decodes = true;
+ QByteArray const line {"060500 -20 0.3 1500 ~ CQ W1AW FN31 a7"};
+
+ auto const plan = DecodeOutputPlan::prepareLine(line, context);
+
+ QCOMPARE(plan.disposition, DecodeOutputPlan::LineDisposition::Decode);
+ QVERIFY(!plan.normalizedLine.contains("a7"));
+ }
+
+ void wantedOnlyFoxActivityRetainsRawNewline()
+ {
+ auto context = preparationContext();
+ context.specOp = SpecOp::FOX;
+ context.activeStationsAvailable = true;
+ context.activeStationsWantedOnly = true;
+ QByteArray const line {"060500 -10 0.3 1500 ~ W1AW K1ABC -10\n"};
+
+ auto const plan = DecodeOutputPlan::prepareLine(line, context);
+
+ QCOMPARE(actionNames(plan.actions).first(), QString {"qsy"});
+ QCOMPARE(actionNames(plan.actions).at(1), QString {"fox-activity"});
+ QCOMPARE(plan.actions.at(1).text, QString {line});
+ }
+
+ void ignoresFst4wOwnCallAfterQsyInspection()
+ {
+ auto context = preparationContext();
+ context.mode = "FST4W";
+ context.noOwnCall = true;
+ QByteArray const rawLine {"060500 -10 0.3 1500 ` CQ K1ABC FN31\n"};
+
+ auto const plan = DecodeOutputPlan::prepareLine(rawLine, context);
+
+ QCOMPARE(plan.disposition, DecodeOutputPlan::LineDisposition::Ignore);
+ QCOMPARE(actionNames(plan.actions), QStringList({"qsy"}));
+ }
+
+ void legacyPaddingDoesNotChangeDecodedRepresentations()
+ {
+ auto context = preparationContext();
+ context.mode = "JT65";
+ QByteArray const line {
+ "0605 -10 0.3 1500 # TU; K1ABC W1AW R-10 "};
+
+ auto const plan = DecodeOutputPlan::prepareLine(line, context);
+
+ QCOMPARE(plan.normalizedLine.size(), line.size() + 14);
+ QCOMPARE(plan.decodedOriginal, QString {line});
+ QVERIFY(plan.decodedOriginal.contains("TU; "));
+ QVERIFY(!plan.decodedForLogic.contains("TU; "));
+ QCOMPARE(plan.logicMessage.string(), plan.decodedForLogic);
+ }
+
+ void rejectsEarlyDuplicateBeforeLogging()
+ {
+ auto context = preparationContext();
+ context.nominalFrequency = 50313000;
+ QByteArray const line {"060500 -20 0.3 1500 ~ CQ W1AW FN31"};
+ context.earlyDecodes = QString::fromUtf8(line.mid(23, 19));
+
+ auto const plan = DecodeOutputPlan::prepareLine(line, context);
+
+ QCOMPARE(plan.disposition, DecodeOutputPlan::LineDisposition::Ignore);
+ QCOMPARE(plan.reason, QString {"early duplicate rejected"});
+ QCOMPARE(actionNames(plan.actions), QStringList({"qsy"}));
+ }
+
+ void shortLineIsNotAnEarlyDuplicate()
+ {
+ auto context = preparationContext();
+ context.nominalFrequency = 50313000;
+ context.earlyDecodes = "060500 -20 0.3 1500 ~ CQ W1AW FN31";
+ QByteArray const line {"060500 -20 0.3 1500"};
+
+ auto const plan = DecodeOutputPlan::prepareLine(line, context);
+
+ QCOMPARE(plan.disposition, DecodeOutputPlan::LineDisposition::Decode);
+ }
+
+ void decodeFinishedIsDetectedBeforeDuplicateRejection()
+ {
+ auto context = preparationContext();
+ context.nominalFrequency = 50313000;
+ QByteArray const line {"<DecodeFinished> 1 6 2003"};
+ context.earlyDecodes = QString::fromUtf8(line);
+
+ auto const plan = DecodeOutputPlan::prepareLine(line, context);
+
+ QCOMPARE(plan.disposition, DecodeOutputPlan::LineDisposition::Finish);
+ QVERIFY(plan.batchHasDecodes);
+ }
+
+ void parsesAveragingMarkers_data()
+ {
+ QTest::addColumn<QByteArray>("line");
+ QTest::addColumn<int>("count");
+ QTest::newRow("f2") << QByteArray {"0605 -10 0.3 1500 # K1ABC W1AW R-10 f2"} << 2;
+ QTest::newRow("f-star") << QByteArray {"0605 -10 0.3 1500 # K1ABC W1AW R-10 f*"} << 10;
+ QTest::newRow("d2") << QByteArray {"0605 -10 0.3 1500 # K1ABC W1AW R-10 d 2"} << 2;
+ QTest::newRow("a2") << QByteArray {"0605 -10 0.3 1500 # K1ABC W1AW R-10 a 2"} << 2;
+ QTest::newRow("q2") << QByteArray {"0605 -10 0.3 1500 # K1ABC W1AW R-10 q 2"} << 2;
+ }
+
+ void parsesAveragingMarkers()
+ {
+ QFETCH(QByteArray, line);
+ QFETCH(int, count);
+ auto context = preparationContext();
+ context.mode = "JT65";
+
+ auto const plan = DecodeOutputPlan::prepareLine(line, context);
+
+ QVERIFY(plan.averaged);
+ QCOMPARE(plan.averageCount, count);
+ }
+
+ void decodeFinishedWireFormats_data()
+ {
+ QTest::addColumn<QByteArray>("line");
+ QTest::addColumn<bool>("decoded");
+ QTest::addColumn<int>("singleDecodes");
+ QTest::addColumn<int>("averagedDecodes");
+
+ QTest::newRow("ft8 fixture")
+ << QByteArray {"<DecodeFinished> 0 14 0"} << true << 0 << 0;
+ QTest::newRow("jt9 fixture")
+ << QByteArray {"<DecodeFinished> 0 6 0"} << true << 0 << 0;
+ QTest::newRow("msk144 no messages")
+ << QByteArray {"<DecodeFinished> 0 0 0"} << false << 0 << 0;
+ QTest::newRow("q65 packed counts")
+ << QByteArray {"<DecodeFinished> 1 6 2003"} << true << 2 << 3;
+ }
+
+ void decodeFinishedWireFormats()
+ {
+ QFETCH(QByteArray, line);
+ QFETCH(bool, decoded);
+ QFETCH(int, singleDecodes);
+ QFETCH(int, averagedDecodes);
+
+ auto const plan = DecodeOutputPlan::prepareLine(line, preparationContext());
+
+ QCOMPARE(plan.disposition, DecodeOutputPlan::LineDisposition::Finish);
+ QCOMPARE(plan.batchHasDecodes, decoded);
+ QCOMPARE(plan.q65SingleDecodes, singleDecodes);
+ QCOMPARE(plan.q65AveragedDecodes, averagedDecodes);
+ QCOMPARE(actionNames(plan.actions), QStringList({"qsy"}));
+ }
+
+ void blacklistCanRejectOrContinueWithScoreReset()
+ {
+ DecodedText const message {"060500 -10 0.3 1500 ~ CQ W1AW FN31"};
+ DecodeOutputPlan::KeywordFilterContext context;
+ context.mode = "FT8";
+ context.blacklistEnabled = true;
+ context.blacklistKeywords = QStringList {"W1AW"};
+
+ auto decision = DecodeOutputPlan::decideKeywordFilter(message, context);
+ QVERIFY(decision.filtered);
+ QVERIFY(!decision.continueProcessing);
+ QVERIFY(!decision.resetPounceScores);
+
+ context.waitAndPounceOnly = true;
+ context.pounce = true;
+ context.respondPolicy = AutoRespondPolicy::MaxDistance;
+ decision = DecodeOutputPlan::decideKeywordFilter(message, context);
+ QVERIFY(decision.filtered);
+ QVERIFY(decision.continueProcessing);
+ QVERIFY(decision.resetPounceScores);
+ }
+
+ void filterPrecedenceMatrix_data()
+ {
+ QTest::addColumn<int>("options");
+ QTest::addColumn<int>("expectedOutcomes");
+ QTest::addColumn<QString>("expectedKeywordReason");
+ QTest::addColumn<QString>("expectedVisibilityReason");
+
+ auto addRow = [] (char const * name, int options, int outcomes,
+ QString const& keywordReason = {},
+ QString const& visibilityReason = {}) {
+ QTest::newRow(name) << options << outcomes << keywordReason << visibilityReason;
+ };
+
+ addRow("baseline", 0, ContinueProcessing | DisplayLeft);
+ addRow("blacklist rejects message", Blacklist, KeywordFiltered | FinallyFiltered,
+ "blacklist matched");
+ addRow("whitelist miss rejects message", Whitelist, KeywordFiltered | FinallyFiltered,
+ "whitelist did not match");
+ addRow("blacklist precedes whitelist", Blacklist | Whitelist,
+ KeywordFiltered | FinallyFiltered, "blacklist matched");
+ addRow("always-pass precedes keyword lists", AlwaysPass | Blacklist | Whitelist,
+ ContinueProcessing | AlwaysPassed | DisplayLeft);
+ addRow("always-pass preserves earlier filter", InitiallyFiltered | AlwaysPass | Blacklist,
+ KeywordFiltered | FinallyFiltered | ContinueProcessing | AlwaysPassed);
+ addRow("always-pass does not bypass ignore list", AlwaysPass | HideIgnored,
+ FinallyFiltered | ContinueProcessing | AlwaysPassed, {}, "ignore-list filter");
+ addRow("always-pass does not bypass worked-today", AlwaysPass | HideWorkedToday,
+ FinallyFiltered | ContinueProcessing | AlwaysPassed, {}, "recently-worked filter");
+ addRow("bypass suppresses all filters but resets scoring pounce",
+ Blacklist | Whitelist | Bypass | ScoringPounce | HideIgnored | HideWorkedToday,
+ ContinueProcessing | ResetPounceScores | DisplayLeft, "blacklist matched");
+ addRow("wait-and-pounce filter continues and displays",
+ Blacklist | WaitAndPounceOnly | ScoringPounce,
+ KeywordFiltered | FinallyFiltered | ContinueProcessing | ResetPounceScores | DisplayLeft,
+ "blacklist matched");
+ addRow("non-scoring pounce does not reset", Blacklist | WaitAndPounceOnly | NonScoringPounce,
+ KeywordFiltered | FinallyFiltered | ContinueProcessing | DisplayLeft,
+ "blacklist matched");
+ addRow("rejected message does not reset scoring pounce", Blacklist | ScoringPounce,
+ KeywordFiltered | FinallyFiltered, "blacklist matched");
+ }
+
+ void filterPrecedenceMatrix()
+ {
+ QFETCH(int, options);
+ QFETCH(int, expectedOutcomes);
+ QFETCH(QString, expectedKeywordReason);
+ QFETCH(QString, expectedVisibilityReason);
+
+ DecodedText const message {"060500 -10 0.3 1500 ~ CQ W1AW FN31"};
+ DecodeOutputPlan::KeywordFilterContext keywordContext;
+ keywordContext.mode = "FT8";
+ keywordContext.alreadyFiltered = options & InitiallyFiltered;
+ keywordContext.alwaysPass = options & AlwaysPass;
+ keywordContext.passKeywords = QStringList {"W1AW"};
+ keywordContext.blacklistEnabled = options & Blacklist;
+ keywordContext.blacklistKeywords = QStringList {"W1AW"};
+ keywordContext.whitelistEnabled = options & Whitelist;
+ keywordContext.whitelistKeywords = QStringList {"K9XYZ"};
+ keywordContext.bypass = options & Bypass;
+ keywordContext.waitAndPounceOnly = options & WaitAndPounceOnly;
+ keywordContext.pounce = options & (ScoringPounce | NonScoringPounce);
+ keywordContext.respondPolicy = options & ScoringPounce
+ ? AutoRespondPolicy::MaxDistance : AutoRespondPolicy::First;
+
+ auto const keywordDecision = DecodeOutputPlan::decideKeywordFilter(message, keywordContext);
+ bool finalFiltered = keywordDecision.filtered;
+ QString visibilityReason;
+ if (keywordDecision.continueProcessing) {
+ DecodeOutputPlan::VisibilityFilterContext visibilityContext;
+ visibilityContext.alreadyFiltered = finalFiltered;
+ visibilityContext.alwaysPassed = keywordDecision.alwaysPassed;
+ visibilityContext.bypass = keywordContext.bypass;
+ visibilityContext.hideIgnored = options & HideIgnored;
+ visibilityContext.ignoreList = "W1AW,";
+ visibilityContext.hideWorkedToday = options & HideWorkedToday;
+ visibilityContext.today = "2026-07-11";
+ visibilityContext.txLog = "2026-07-11,12:34:56,W1AW,FN31";
+ auto const visibilityDecision = DecodeOutputPlan::decideVisibilityFilter(message,
+ visibilityContext);
+ finalFiltered = visibilityDecision.filtered;
+ visibilityReason = visibilityDecision.reason;
+ }
+ bool const displayLeft = keywordDecision.continueProcessing
+ && DecodeOutputPlan::shouldDisplayLeft(false, "FT8", SpecOp::NONE, finalFiltered,
+ keywordContext.waitAndPounceOnly);
+
+ QCOMPARE(keywordDecision.filtered, bool(expectedOutcomes & KeywordFiltered));
+ QCOMPARE(finalFiltered, bool(expectedOutcomes & FinallyFiltered));
+ QCOMPARE(keywordDecision.continueProcessing, bool(expectedOutcomes & ContinueProcessing));
+ QCOMPARE(keywordDecision.alwaysPassed, bool(expectedOutcomes & AlwaysPassed));
+ QCOMPARE(keywordDecision.resetPounceScores, bool(expectedOutcomes & ResetPounceScores));
+ QCOMPARE(keywordDecision.reason, expectedKeywordReason);
+ QCOMPARE(visibilityReason, expectedVisibilityReason);
+ QCOMPARE(displayLeft, bool(expectedOutcomes & DisplayLeft));
+ }
+
+ void wordFilterUsesConfiguredSecondPayloadWord()
+ {
+ DecodedText const message {"060500 -10 0.3 1500 ~ CQ DX W1AW FN31"};
+ DecodeOutputPlan::KeywordFilterContext context;
+ context.mode = "FT8";
+ context.filterBySecondWord = true;
+ context.blacklistEnabled = true;
+ context.blacklistKeywords = QStringList {"W1AW"};
+
+ auto const decision = DecodeOutputPlan::decideKeywordFilter(message, context);
+
+ QCOMPARE(decision.selectedWord, QString {"W1AW"});
+ QVERIFY(decision.filtered);
+ QVERIFY(!decision.continueProcessing);
+ }
+
+ void alwaysPassSkipsGeographyLookupButNotIgnoreList()
+ {
+ DecodedText const message {"060500 -10 0.3 1500 ~ CQ W1AW FN31"};
+ DecodeOutputPlan::VisibilityFilterContext context;
+ context.alwaysPassed = true;
+ context.hideEurope = true;
+ int continentLookups = 0;
+ context.continent = [&continentLookups] (QString const&) {
+ ++continentLookups;
+ return QString {"EU"};
+ };
+
+ auto decision = DecodeOutputPlan::decideVisibilityFilter(message, context);
+ QVERIFY(!decision.filtered);
+ QCOMPARE(continentLookups, 0);
+
+ context.hideIgnored = true;
+ context.ignoreList = "W1AW,";
+ decision = DecodeOutputPlan::decideVisibilityFilter(message, context);
+ QVERIFY(decision.filtered);
+ QCOMPARE(decision.reason, QString {"ignore-list filter"});
+ QCOMPARE(continentLookups, 0);
+ }
+
+ void geographyAndRecentLogFiltersAreCharacterized()
+ {
+ DecodedText const message {"060500 -10 0.3 1500 ~ CQ W1AW FN31"};
+ DecodeOutputPlan::VisibilityFilterContext context;
+ context.hideEurope = true;
+ context.continent = [] (QString const&) { return QString {"EU"}; };
+
+ auto decision = DecodeOutputPlan::decideVisibilityFilter(message, context);
+ QVERIFY(decision.filtered);
+ QCOMPARE(decision.reason, QString {"geography or worked-before filter"});
+
+ context = DecodeOutputPlan::VisibilityFilterContext {};
+ context.hideWorkedToday = true;
+ context.today = "2026-07-11";
+ context.yesterday = "2026-07-10";
+ context.txLog = "2026-07-11,12:34:56,W1AW,FN31";
+ decision = DecodeOutputPlan::decideVisibilityFilter(message, context);
+ QVERIFY(decision.filtered);
+ QCOMPARE(decision.reason, QString {"recently-worked filter"});
+ }
+
+ void workedBeforeLookupRunsOnlyWhenEnabled()
+ {
+ DecodedText const message {"060500 -10 0.3 1500 ~ CQ W1AW FN31"};
+ DecodeOutputPlan::VisibilityFilterContext context;
+ int lookups = 0;
+ context.workedBeforeOnBand = [&lookups] (QString const&, QString const&) {
+ ++lookups;
+ return true;
+ };
+
+ auto decision = DecodeOutputPlan::decideVisibilityFilter(message, context);
+ QVERIFY(!decision.filtered);
+ QCOMPARE(lookups, 0);
+
+ context.hideWorkedBefore = true;
+ decision = DecodeOutputPlan::decideVisibilityFilter(message, context);
+ QVERIFY(decision.filtered);
+ QCOMPARE(lookups, 1);
+ }
+
+ void experimentalFilterMarksUnknownLowSnrPayload()
+ {
+ DecodedText const message {"060500 -24 0.3 1500 ~ BADWORD OTHER TEXT"};
+ DecodeOutputPlan::ExperimentalFilterContext context;
+ context.mode = "FT8";
+ context.reduceFalseDecodes = true;
+ context.allCallsigns = "W1AW K1ABC";
+
+ auto const decision = DecodeOutputPlan::decideExperimentalFilter(message, context);
+
+ QVERIFY(decision.filtered);
+ QVERIFY(!decision.reason.isEmpty());
+ }
+
+ void routesNearDecodeToRightWindow()
+ {
+ DecodedText const message {"060500 -10 0.3 1500 ~ CQ W1AW FN31"};
+ auto context = routingContext();
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, false, context);
+
+ QVERIFY(decision.displayRight);
+ }
+
+ void farDecodeDoesNotRouteRight()
+ {
+ DecodedText const message {"060500 -10 0.3 1900 ~ CQ W1AW FN31"};
+ auto context = routingContext();
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, false, context);
+
+ QVERIFY(!decision.displayRight);
+ }
+
+ void currentQsoPairRoutingRequiresConfiguredCalls_data()
+ {
+ QTest::addColumn<QString>("line");
+ QTest::addColumn<QString>("mode");
+ QTest::addColumn<QString>("baseCall");
+ QTest::addColumn<QString>("hisCall");
+ QTest::addColumn<bool>("displayRight");
+
+ QTest::newRow("FT8 with empty calls")
+ << QString {"060500 -10 0.3 1900 ~ CQ W9XYZ EN50"} << QString {"FT8"}
+ << QString {} << QString {} << false;
+ QTest::newRow("FT4 with empty calls")
+ << QString {"060500 -10 0.3 1900 + CQ W9XYZ EN50"} << QString {"FT4"}
+ << QString {} << QString {} << false;
+ QTest::newRow("empty local call")
+ << QString {"060500 -10 0.3 1900 ~ CQ W1AW FN31"} << QString {"FT8"}
+ << QString {} << QString {"W1AW"} << false;
+ QTest::newRow("empty QSO partner")
+ << QString {"060500 -10 0.3 1900 ~ CQ K1ABC FN42"} << QString {"FT8"}
+ << QString {"K1ABC"} << QString {} << false;
+ QTest::newRow("configured FT8 QSO pair")
+ << QString {"060500 -10 0.3 1900 ~ CQ K1ABC W1AW"} << QString {"FT8"}
+ << QString {"K1ABC"} << QString {"W1AW"} << true;
+ QTest::newRow("configured FT4 QSO pair")
+ << QString {"060500 -10 0.3 1900 + CQ K1ABC W1AW"} << QString {"FT4"}
+ << QString {"K1ABC"} << QString {"W1AW"} << true;
+ }
+
+ void currentQsoPairRoutingRequiresConfiguredCalls()
+ {
+ QFETCH(QString, line);
+ QFETCH(QString, mode);
+ QFETCH(QString, baseCall);
+ QFETCH(QString, hisCall);
+ QFETCH(bool, displayRight);
+
+ DecodedText const message {line};
+ auto context = routingContext();
+ context.mode = mode;
+ context.baseCall = baseCall;
+ context.myCall = baseCall;
+ context.hisCall = hisCall;
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, false, context);
+
+ QCOMPARE(decision.displayRight, displayRight);
+ }
+
+ void routesAveragedQ65ToRight()
+ {
+ DecodedText const message {"060500 -10 0.3 1500 : K1ABC W1AW R-10"};
+ auto context = routingContext();
+ context.mode = "Q65";
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, true, context);
+
+ QVERIFY(decision.displayRight);
+ }
+
+ void blockedRightDisplayOverridesRouting()
+ {
+ DecodedText const message {"060500 -10 0.3 1500 ~ CQ W1AW FN31"};
+ auto context = routingContext();
+ context.blockRightDisplay = true;
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, false, context);
+
+ QVERIFY(!decision.displayRight);
+ }
+
+ void houndNotForUsDoesNotRouteRight()
+ {
+ DecodedText const message {"060500 -10 0.3 1500 ~ CQ W1AW FN31"};
+ auto context = routingContext();
+ context.specOp = SpecOp::HOUND;
+ context.wideGraphRxFrequency = 2000;
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, false, context);
+
+ QVERIFY(!decision.displayRight);
+ }
+
+ void routingOperatorIntentMatrix_data()
+ {
+ QTest::addColumn<QString>("line");
+ QTest::addColumn<QString>("mode");
+ QTest::addColumn<int>("specOp");
+ QTest::addColumn<QString>("myCall");
+ QTest::addColumn<QString>("baseCall");
+ QTest::addColumn<QString>("hisCall");
+ QTest::addColumn<int>("rxFrequency");
+ QTest::addColumn<int>("wideGraphRxFrequency");
+ QTest::addColumn<bool>("averaged");
+ QTest::addColumn<bool>("enableVhfFeatures");
+ QTest::addColumn<bool>("expectedForUs");
+ QTest::addColumn<bool>("expectedDisplayRight");
+
+ auto addRow = [] (char const * name, QString const& line, QString const& mode,
+ SpecOp specOp, QString const& myCall, QString const& baseCall,
+ QString const& hisCall, int rxFrequency, int wideGraphRxFrequency,
+ bool averaged, bool enableVhfFeatures, bool forUs, bool displayRight) {
+ QTest::newRow(name) << line << mode << static_cast<int>(specOp) << myCall << baseCall
+ << hisCall << rxFrequency << wideGraphRxFrequency << averaged
+ << enableVhfFeatures << forUs << displayRight;
+ };
+
+ addRow("compound local call does not claim base-call match",
+ "060500 -10 0.3 1900 ~ K1ABC/R W1AW R-10", "FT8", SpecOp::NONE,
+ "K1ABC/P", "K1ABC", "W1AW", 1500, 1500, false, false, false, false);
+ addRow("FT8 base-call and DX-call pair routes",
+ "060500 -10 0.3 1900 ~ CQ K1ABC W1AW", "FT8", SpecOp::NONE,
+ "K1ABC", "K1ABC", "W1AW", 1500, 1500, false, false, false, true);
+ addRow("FT4 base-call and DX-call pair routes",
+ "060500 -10 0.3 1900 + CQ K1ABC W1AW", "FT4", SpecOp::NONE,
+ "K1ABC", "K1ABC", "W1AW", 1500, 1500, false, false, false, true);
+ addRow("unaveraged Q65 not for operator stays out",
+ "060500 -10 0.3 1500 : W9XYZ W1AW R-10", "Q65", SpecOp::NONE,
+ "K1ABC", "K1ABC", "W1AW", 1500, 1500, false, false, false, false);
+ addRow("near JT65 routes without VHF features",
+ "060500 -10 0.3 1505 # CQ W1AW FN31", "JT65", SpecOp::NONE,
+ "K1ABC", "K1ABC", "W1AW", 1500, 1500, false, false, false, true);
+ addRow("near JT65 stays out with VHF features",
+ "060500 -10 0.3 1505 # CQ W1AW FN31", "JT65", SpecOp::NONE,
+ "K1ABC", "K1ABC", "W1AW", 1500, 1500, false, true, false, false);
+ addRow("FOX treats DE report as for operator",
+ "060500 -10 0.3 1900 ~ DE W1AW R-10", "FT8", SpecOp::FOX,
+ "K1ABC", "K1ABC", "W1AW", 1500, 1500, false, false, true, true);
+ addRow("Hound suppresses near decode not for operator",
+ "060500 -10 0.3 1500 ~ W9XYZ W1AW R-10", "FT8", SpecOp::HOUND,
+ "K1ABC", "K1ABC", "W1AW", 1500, 1500, false, false, false, false);
+ addRow("Hound retains decode for operator",
+ "060500 -10 0.3 1900 ~ K1ABC W1AW R-10", "FT8", SpecOp::HOUND,
+ "K1ABC", "K1ABC", "W1AW", 1500, 1500, false, false, true, true);
+ }
+
+ void routingOperatorIntentMatrix()
+ {
+ QFETCH(QString, line);
+ QFETCH(QString, mode);
+ QFETCH(int, specOp);
+ QFETCH(QString, myCall);
+ QFETCH(QString, baseCall);
+ QFETCH(QString, hisCall);
+ QFETCH(int, rxFrequency);
+ QFETCH(int, wideGraphRxFrequency);
+ QFETCH(bool, averaged);
+ QFETCH(bool, enableVhfFeatures);
+ QFETCH(bool, expectedForUs);
+ QFETCH(bool, expectedDisplayRight);
+
+ DecodedText const message {line};
+ auto context = routingContext();
+ context.mode = mode;
+ context.specOp = static_cast<SpecOp>(specOp);
+ context.myCall = myCall;
+ context.baseCall = baseCall;
+ context.hisCall = hisCall;
+ context.rxFrequency = rxFrequency;
+ context.wideGraphRxFrequency = wideGraphRxFrequency;
+ context.enableVhfFeatures = enableVhfFeatures;
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, averaged, context);
+
+ QCOMPARE(decision.forUs, expectedForUs);
+ QCOMPARE(decision.displayRight, expectedDisplayRight);
+ }
+
+ void foxReportRequiresStandaloneReportToken_data()
+ {
+ QTest::addColumn<QString>("line");
+ QTest::addColumn<bool>("displayRight");
+ QTest::newRow("report")
+ << QString {"060500 -10 0.3 1900 ~ K1ABC W1AW R-10"} << true;
+ QTest::newRow("embedded-report-shape")
+ << QString {"060500 -10 0.3 1900 ~ K1ABC W1AW XR-10"} << false;
+ }
+
+ void foxReportRequiresStandaloneReportToken()
+ {
+ QFETCH(QString, line);
+ QFETCH(bool, displayRight);
+ DecodedText const message {line};
+ auto context = routingContext();
+ context.specOp = SpecOp::FOX;
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, false, context);
+
+ QCOMPARE(decision.displayRight, displayRight);
+ }
+
+ void competingFoxAlertRequiresFullyFormedDecode_data()
+ {
+ QTest::addColumn<QString>("line");
+ QTest::addColumn<bool>("competing");
+ QTest::newRow("short-free-text-report")
+ << QString {"060500 -10 0.3 950 ~ R-10"} << false;
+ QTest::newRow("other-hound-report")
+ << QString {"060500 -10 0.3 950 ~ K1XYZ W9AAA R-10"} << true;
+ QTest::newRow("for-us-report")
+ << QString {"060500 -10 0.3 950 ~ K1ABC W9AAA R-10"} << false;
+ QTest::newRow("above-fox-band")
+ << QString {"060500 -10 0.3 1500 ~ K1XYZ W9AAA R-10"} << false;
+ }
+
+ void competingFoxAlertRequiresFullyFormedDecode()
+ {
+ QFETCH(QString, line);
+ QFETCH(bool, competing);
+ DecodedText const message {line};
+ auto context = routingContext();
+ context.specOp = SpecOp::FOX;
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, false, context);
+
+ QCOMPARE(decision.competingFoxReport, competing);
+ }
+
+ void safelyMalformedDecodeDoesNotRouteRight()
+ {
+ DecodedText const message {"malformed"};
+ auto context = routingContext();
+
+ auto const decision = DecodeOutputPlan::decideRouting(message, message, false, context);
+
+ QVERIFY(!decision.displayRight);
+ QVERIFY(!decision.forUs);
+ }
+
+ void displayLeftSkipsAveragedFoxAndFilteredLines()
+ {
+ using DecodeOutputPlan::shouldDisplayLeft;
+ QVERIFY(shouldDisplayLeft(false, "FT8", SpecOp::NONE, false, false));
+ QVERIFY(!shouldDisplayLeft(true, "FT8", SpecOp::NONE, false, false));
+ QVERIFY(!shouldDisplayLeft(false, "FT8", SpecOp::FOX, false, false));
+ QVERIFY(!shouldDisplayLeft(false, "FT8", SpecOp::NONE, true, false));
+ QVERIFY(shouldDisplayLeft(false, "FT8", SpecOp::NONE, true, true));
+ }
+
+ void pskPostingRequiresStandardMessageOutsideHoundMode()
+ {
+ using DecodeOutputPlan::shouldPostPsk;
+ QVERIFY(shouldPostPsk("FT8", SpecOp::NONE, false, true, true));
+ QVERIFY(!shouldPostPsk("FT8", SpecOp::NONE, false, true, false));
+ QVERIFY(!shouldPostPsk("FT8", SpecOp::NONE, false, false, true));
+ QVERIFY(!shouldPostPsk("FT8", SpecOp::HOUND, false, true, true));
+ QVERIFY(shouldPostPsk("FT8", SpecOp::HOUND, true, true, true));
+ QVERIFY(shouldPostPsk("FST4W", SpecOp::NONE, false, false, true));
+ }
+
+ void flushesFoxActivityOnlyForFoxBatch()
+ {
+ auto const actions = DecodeOutputPlan::finishBatchActions("FT8", SpecOp::FOX,
+ true, "one\ntwo\n");
+ QCOMPARE(actionNames(actions), QStringList({"flush-fox"}));
+ QCOMPARE(actions[0].text, QString {"one\ntwo\n"});
+ QVERIFY(DecodeOutputPlan::finishBatchActions("FT8", SpecOp::NONE,
+ true, "one\n").isEmpty());
+ }
+};
+
+QTEST_MAIN(TestDecodeOutputPlan)
+#include "test_decode_output_plan.moc"
diff --git a/tests/unit/common/test_decoded_message_fields.cpp b/tests/unit/common/test_decoded_message_fields.cpp
new file mode 100644
index 00000000..5b12da63
--- /dev/null
+++ b/tests/unit/common/test_decoded_message_fields.cpp
@@ -0,0 +1,58 @@
+#include <QtTest>
+
+#include "Decoder/decodedtext.h"
+
+class TestDecodedMessageFields final : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void parsesMessage_data();
+ void parsesMessage();
+};
+
+void TestDecodedMessageFields::parsesMessage_data()
+{
+ QTest::addColumn<QString> ("message");
+ QTest::addColumn<QString> ("destination");
+ QTest::addColumn<QString> ("sender");
+ QTest::addColumn<QString> ("grid");
+ QTest::addColumn<bool> ("cq");
+
+ QTest::newRow ("cq") << "CQ K1ABC FN42" << "CQ" << "K1ABC" << "FN42" << true;
+ QTest::newRow ("cq-dx") << "CQ DX K1ABC FN42" << "CQ DX" << "K1ABC" << "FN42" << true;
+ QTest::newRow ("compact-cq-dx") << "CQDX K1ABC FN42" << "CQDX" << "K1ABC" << "FN42" << true;
+ QTest::newRow ("dx-prefix") << "CQ DX1ABC JO00" << "CQ" << "DX1ABC" << "JO00" << true;
+ QTest::newRow ("letter-modifier") << "CQ POTA W1AW FN31" << "CQ POTA" << "W1AW" << "FN31" << true;
+ QTest::newRow ("test-modifier") << "CQ TEST KA1GT FN54" << "CQ TEST" << "KA1GT" << "FN54" << true;
+ QTest::newRow ("numeric-modifier") << "CQ 123 K1ABC FN42" << "CQ 123" << "K1ABC" << "FN42" << true;
+ QTest::newRow ("directed-grid") << "K1ABC W1AW FN31" << "K1ABC" << "W1AW" << "FN31" << false;
+ QTest::newRow ("directed-report") << "K1ABC W1AW -10" << "K1ABC" << "W1AW" << "" << false;
+ QTest::newRow ("portable-suffix") << "CQ W3SZ/2 FN20" << "CQ" << "W3SZ/2" << "FN20" << true;
+ QTest::newRow ("rover-suffix") << "CQ K1ABC/R FN42" << "CQ" << "K1ABC/R" << "FN42" << true;
+ QTest::newRow ("portable-marker") << "CQ K1ABC/P FN42" << "CQ" << "K1ABC/P" << "FN42" << true;
+ QTest::newRow ("compound-prefix") << "CQ 3DA0RS JJ22" << "CQ" << "3DA0RS" << "JJ22" << true;
+ QTest::newRow ("bracketed-call") << "CQ <PJ4/KA1ABC> FK52" << "CQ" << "PJ4/KA1ABC" << "FK52" << true;
+ QTest::newRow ("later-grid") << "K1ABC W1AW R 520001 FN31AA" << "K1ABC" << "W1AW" << "FN31AA" << false;
+ QTest::newRow ("incomplete") << "CQ TEST" << "CQ" << "TEST" << "" << true;
+ QTest::newRow ("free-text") << "HELLO WORLD" << "HELLO" << "WORLD" << "" << false;
+}
+
+void TestDecodedMessageFields::parsesMessage()
+{
+ QFETCH (QString, message);
+ QFETCH (QString, destination);
+ QFETCH (QString, sender);
+ QFETCH (QString, grid);
+ QFETCH (bool, cq);
+
+ auto const fields = parseDecodedMessage (message);
+ QCOMPARE (fields.destination, destination);
+ QCOMPARE (fields.sender, sender);
+ QCOMPARE (fields.grid, grid);
+ QCOMPARE (fields.cq, cq);
+}
+
+QTEST_GUILESS_MAIN (TestDecodedMessageFields)
+
+#include "test_decoded_message_fields.moc"
diff --git a/tests/unit/common/test_decoded_message_reaction.cpp b/tests/unit/common/test_decoded_message_reaction.cpp
new file mode 100644
index 00000000..606f46d8
--- /dev/null
+++ b/tests/unit/common/test_decoded_message_reaction.cpp
@@ -0,0 +1,385 @@
+#include <QtTest>
+
+#include "QsoReactionTestSupport.hpp"
+
+namespace
+{
+ using namespace QsoReactionTestSupport;
+
+ Snapshot baseContext()
+ {
+ auto context = neutralStationSnapshot();
+ context.mode = "FT8";
+ context.tx1Enabled = true;
+ context.nominalQsyAllowed = true;
+ return context;
+ }
+
+ QString legacyDecode(QString const& mode, QString const& payload,
+ QString const& flags, bool lowConfidence)
+ {
+ auto field = payload.leftJustified(22, ' ', true);
+ if (lowConfidence) field[21] = '?';
+
+ auto line = QString {"0605 -10 0.3 0815 "} + mode + " " + field;
+ if (!flags.isEmpty()) line += " " + flags;
+ return line;
+ }
+
+ bool isFastCqQsyEffect(Effect::Kind kind)
+ {
+ return kind == Effect::Kind::ApplyFastCqQsy
+ || kind == Effect::Kind::RejectNominalQsy;
+ }
+}
+
+class TestDecodedMessageReaction final
+ : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void classifiesLegacy72Messages_data()
+ {
+ QTest::addColumn<QString>("mode");
+ QTest::addColumn<QString>("payload");
+ QTest::addColumn<QString>("flags");
+ QTest::addColumn<bool>("lowConfidence");
+ QTest::addColumn<bool>("expected");
+
+ QTest::newRow("jt4-type1-prefix")
+ << "$" << "1A/KA1ABC WB9XYZ" << "f" << false << true;
+ QTest::newRow("jt9-type1-suffix")
+ << "@" << "KA1ABC WB9XYZ/A" << "f1" << false << true;
+ QTest::newRow("jt9-short-standard")
+ << "@" << "A1 B1" << "" << false << true;
+ QTest::newRow("jt65-ap-type1-prefix")
+ << "#" << "1A/KA1ABC WB9XYZ" << "a1" << false << true;
+ QTest::newRow("jt65-standard")
+ << "#" << "KA1ABC WB9XYZ R-22" << "d*2" << false << true;
+ QTest::newRow("jt4-type2-prefix")
+ << "$" << "CQ ZL4/KA1ABC" << "f" << false << true;
+ QTest::newRow("jt65-type2-suffix")
+ << "#" << "CQ WB9XYZ/VE4" << "a12" << false << true;
+ QTest::newRow("jt4-deep-low-confidence")
+ << "$" << "KA1ABC WB9XYZ R-22" << "d1" << true << true;
+ QTest::newRow("question-without-deep-flag")
+ << "$" << "KA1ABC WB9XYZ R-22" << "" << true << false;
+ QTest::newRow("jt65-ooo")
+ << "#" << "KA1ABC WB9XYZ EN34 OOO" << "" << false << true;
+ QTest::newRow("jt65-short-ooo")
+ << "#" << "A1 B1 OOO" << "" << false << true;
+ QTest::newRow("jt9-ooo-is-not-sideband")
+ << "@" << "KA1ABC WB9XYZ EN34 OOO" << "" << false << false;
+ QTest::newRow("trailing-structured-field")
+ << "#" << "A1A B1B 73 X" << "d1" << false << false;
+ QTest::newRow("blank")
+ << "@" << "" << "" << false << false;
+ QTest::newRow("single-token-call")
+ << "@" << "A1AAA" << "" << false << false;
+ QTest::newRow("short-token")
+ << "@" << "1B" << "" << false << false;
+ QTest::newRow("single-digit")
+ << "@" << "0" << "" << false << false;
+ QTest::newRow("leading-space-short-token")
+ << "@" << " A1" << "" << false << false;
+ QTest::newRow("leading-space-d-token")
+ << "@" << " D12" << "" << false << false;
+ }
+
+ void classifiesLegacy72Messages()
+ {
+ QFETCH(QString, mode);
+ QFETCH(QString, payload);
+ QFETCH(QString, flags);
+ QFETCH(bool, lowConfidence);
+ QFETCH(bool, expected);
+
+ DecodedText message {legacyDecode(mode, payload, flags, lowConfidence)};
+
+ QCOMPARE(message.isStandardMessage(), expected);
+ }
+
+ void rejectsDecodeWithTooFewFields()
+ {
+ auto context = baseContext();
+ DecodedText message {"CQ K1ABC FN42"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(decision.reason, QString {"decode has too few fields"});
+ }
+
+ void rejectsMismatchedModeMarker()
+ {
+ auto context = baseContext();
+ context.mode = "JT65";
+ DecodedText message {"0605 -10 0.3 0815 @ K1ABC W1AW -10"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(decision.reason, QString {"decode mode marker does not match current mode"});
+ }
+
+ void txDecodeOnlyAdjustsRxFrequencyByDefault()
+ {
+ auto context = baseContext();
+ DecodedText message {"0605 Tx 1259 # CQ K1ABC FN42"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(intEffect(decision, Effect::Kind::SetRxFrequency), 1259);
+ QVERIFY(!hasEffect(decision, Effect::Kind::SetTxFrequency));
+ }
+
+ void txDecodeWithCtrlAlsoAdjustsTxFrequencyWhenNotHeld()
+ {
+ auto context = baseContext();
+ context.modifiers.ctrl = true;
+ DecodedText message {"0605 Tx 1259 # CQ K1ABC FN42"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(intEffect(decision, Effect::Kind::SetRxFrequency), 1259);
+ QCOMPARE(intEffect(decision, Effect::Kind::SetTxFrequency), 1259);
+ }
+
+ void fastCqWithListeningFrequencyRequestsQsy()
+ {
+ auto context = baseContext();
+ context.mode = "MSK144";
+ context.fastMode = true;
+ context.transceiverOnline = true;
+ context.nominalFrequency = 50260000;
+ DecodedText message {"060522 -10 0.3 0815 & CQ 260 W1AW FN31"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ bool foundQsy = false;
+ for (auto const& action : decision.effects) {
+ if (action.kind == DecodedMessageReaction::QsoReactionEffect::Kind::ApplyFastCqQsy
+ && action.frequency == 50260000
+ && action.text == "QSY 50.260"
+ && action.boolValue
+ && !action.userInitiated) foundQsy = true;
+ }
+
+ QVERIFY(foundQsy);
+ }
+
+ void blockedFastCqSuppressesOnlyNominalQsyEffects()
+ {
+ auto allowedContext = baseContext();
+ allowedContext.mode = "MSK144";
+ allowedContext.fastMode = true;
+ allowedContext.transceiverOnline = true;
+ allowedContext.nominalFrequency = 50260000;
+ auto blockedContext = allowedContext;
+ blockedContext.nominalQsyAllowed = false;
+ DecodedText message {"060522 -10 0.3 0815 & CQ 260 W1AW FN31"};
+
+ auto const allowed = DecodedMessageReaction::planProcessMessage(message, allowedContext);
+ auto const blocked = DecodedMessageReaction::planProcessMessage(message, blockedContext);
+
+ QCOMPARE(effectCount(allowed, Effect::Kind::ApplyFastCqQsy), 1);
+ QCOMPARE(effectCount(blocked, Effect::Kind::ApplyFastCqQsy), 0);
+ QVERIFY(blocked.disposition == allowed.disposition);
+ QCOMPARE(blocked.reason, allowed.reason);
+
+ QVector<Effect const *> allowedUnrelated;
+ for (auto const& effect : allowed.effects) {
+ if (!isFastCqQsyEffect(effect.kind)) allowedUnrelated.append(&effect);
+ }
+ QCOMPARE(blocked.effects.size(), allowedUnrelated.size());
+ for (int i = 0; i < blocked.effects.size(); ++i) {
+ auto const& actual = blocked.effects.at(i);
+ auto const& expected = *allowedUnrelated.at(i);
+ QVERIFY(actual.kind == expected.kind);
+ QCOMPARE(actual.intValue, expected.intValue);
+ QCOMPARE(actual.frequency, expected.frequency);
+ QCOMPARE(actual.text, expected.text);
+ QCOMPARE(actual.boolValue, expected.boolValue);
+ QCOMPARE(actual.userInitiated, expected.userInitiated);
+ QVERIFY(actual.progress == expected.progress);
+ QVERIFY(actual.contestHint == expected.contestHint);
+ }
+ }
+
+ void blockedManualFastCqRejectsBeforeStartingQso()
+ {
+ auto context = baseContext();
+ context.mode = "MSK144";
+ context.fastMode = true;
+ context.transceiverOnline = true;
+ context.nominalFrequency = 50260000;
+ context.nominalQsyAllowed = false;
+ context.selectionOrigin = DecodedMessageReaction::SelectionOrigin::ManualLeftPane;
+ DecodedText message {"060522 -10 0.3 0815 & CQ 260 W1AW FN31"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QCOMPARE(decision.effects.size(), 1);
+ QVERIFY(decision.effects.first().kind == Effect::Kind::RejectNominalQsy);
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(decision.reason, QString {"fast CQ requires a blocked nominal QSY"});
+ }
+
+ void fastCqQsyPermissionDefaultsClosed()
+ {
+ auto context = neutralStationSnapshot();
+ context.mode = "MSK144";
+ context.fastMode = true;
+ context.transceiverOnline = true;
+ context.nominalFrequency = 50260000;
+ DecodedText message {"060522 -10 0.3 0815 & CQ 260 W1AW FN31"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QCOMPARE(effectCount(decision, Effect::Kind::ApplyFastCqQsy), 0);
+ }
+
+ void doubleClickDoesNotStartQsoWithOwnBaseCall()
+ {
+ auto context = baseContext();
+ context.doubleClicked = true;
+ DecodedText message {"0605 -10 0.3 0815 ~ W1AW K1ABC FN42"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(decision.reason, QString {"double-click would start QSO with own base call"});
+ }
+
+ void udpReplyIsIgnoredWhileTransmittingOur73()
+ {
+ auto context = baseContext();
+ context.selectionOrigin = DecodedMessageReaction::SelectionOrigin::Udp;
+ context.transmittingSignoff = true;
+ DecodedText message {"0605 -10 0.3 0815 ~ K1ABC W1AW RR73"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(decision.reason, QString {"udp reply ignored while transmitting 73"});
+ }
+
+ void udpInvalidCqReplyIsRejectedWhileTransmittingOur73()
+ {
+ auto context = baseContext();
+ context.selectionOrigin = DecodedMessageReaction::SelectionOrigin::Udp;
+ context.transmittingSignoff = true;
+ DecodedText message {"0605 -10 0.3 0815 ~ CQ N0CALL FN31"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(decision.reason, QString {"non-standard free text is not processable"});
+ }
+
+ void udpDifferentSignoffIsHonoredWhileTransmittingOur73()
+ {
+ auto context = baseContext();
+ context.selectionOrigin = DecodedMessageReaction::SelectionOrigin::Udp;
+ context.transmittingSignoff = true;
+ DecodedText message {"0605 -10 0.3 0815 ~ K1ABC N0CALL RR73"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::Reacted);
+ }
+
+ void manualDoubleClickStillHonoredWhileTransmittingOur73()
+ {
+ // Answering the partner's RR73 with a 73 by double-clicking it is an
+ // explicit operator override and must keep working even mid-transmission.
+ auto context = baseContext();
+ context.doubleClicked = true;
+ context.selectionOrigin = DecodedMessageReaction::SelectionOrigin::ManualLeftPane;
+ context.transmittingSignoff = true;
+ DecodedText message {"0605 -10 0.3 0815 ~ K1ABC W1AW RR73"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::Reacted);
+ }
+
+ void udpReplyHonoredWhenNotSigningOff()
+ {
+ auto context = baseContext();
+ context.doubleClicked = true;
+ context.selectionOrigin = DecodedMessageReaction::SelectionOrigin::Udp;
+ context.transmittingSignoff = false;
+ DecodedText message {"0605 -10 0.3 0815 ~ CQ W1AW FN31"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::Reacted);
+ }
+
+ void houndIgnoresOtherHoundNegativeReport()
+ {
+ auto context = baseContext();
+ context.specOp = SpecialOperatingActivity::HOUND;
+ DecodedText message {"0605 -10 0.3 0815 ~ K1JT W10AAA R-10"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(decision.reason, QString {"hound ignores other hounds"});
+ }
+
+ void houndIgnoresOtherHoundPositiveReport()
+ {
+ auto context = baseContext();
+ context.specOp = SpecialOperatingActivity::HOUND;
+ DecodedText message {"0605 -10 0.3 0815 ~ K1JT W10AAA R+03"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(decision.reason, QString {"hound ignores other hounds"});
+ }
+
+ void suffixedCallKeepsPriorQsoPartnerSnapshot()
+ {
+ auto context = baseContext();
+ context.dxCall = "N0CALL";
+ DecodedText message {"0605 -10 0.3 0815 ~ K1ABC W1AW/R -10"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::Reacted);
+ int clearGrid = -1;
+ int setCall = -1;
+ for (int i = 0; i < decision.effects.size(); ++i) {
+ if (decision.effects[i].kind == DecodedMessageReaction::QsoReactionEffect::Kind::ClearDxGrid) {
+ clearGrid = i;
+ }
+ if (decision.effects[i].kind == DecodedMessageReaction::QsoReactionEffect::Kind::SetDxCall
+ && decision.effects[i].text == "W1AW/R") {
+ setCall = i;
+ }
+ }
+ QVERIFY(clearGrid >= 0);
+ QVERIFY(setCall > clearGrid);
+ }
+
+ void maxSignalSignoffKeepsSelectedCall()
+ {
+ auto context = baseContext();
+ context.respondPolicy = AutoRespondPolicy::MaxSignal;
+ DecodedText message {"0605 -10 0.3 0815 ~ K1ABC W1AW/R 73"};
+
+ auto const decision = DecodedMessageReaction::planProcessMessage(message, context);
+
+ QVERIFY(decision.disposition == DecodedMessageReaction::ReactionDisposition::Reacted);
+ QVERIFY(!hasEffect(decision, Effect::Kind::SetDxCall));
+ }
+};
+
+QTEST_MAIN(TestDecodedMessageReaction)
+#include "test_decoded_message_reaction.moc"
diff --git a/tests/unit/common/test_decoded_time.cpp b/tests/unit/common/test_decoded_time.cpp
new file mode 100644
index 00000000..e6115823
--- /dev/null
+++ b/tests/unit/common/test_decoded_time.cpp
@@ -0,0 +1,54 @@
+#include <QtTest>
+
+#include "Network/DecodedTime.hpp"
+
+namespace
+{
+ QDateTime nowUtc()
+ {
+ return {QDate {2026, 8, 17}, QTime {12, 34, 56}, Qt::UTC};
+ }
+}
+
+class TestDecodedTime final : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void acceptsFourAndSixDigitTimes()
+ {
+ auto const fourDigitExpected = QDateTime {QDate {2026, 8, 17}, QTime {12, 34}, Qt::UTC};
+ QCOMPARE(DecodedTime::spotTime("1234", nowUtc(), 60), fourDigitExpected);
+ auto const sixDigitExpected = nowUtc();
+ QCOMPARE(DecodedTime::spotTime("123456", nowUtc(), 60), sixDigitExpected);
+ }
+
+ void preservesMidnightConvention()
+ {
+ auto const firstExpected = QDateTime {QDate {2026, 8, 16}, QTime {23, 59}, Qt::UTC};
+ auto const secondExpected = QDateTime {QDate {2026, 8, 16}, QTime {23, 59, 45}, Qt::UTC};
+ auto const thirdExpected = QDateTime {QDate {2026, 8, 17}, QTime {23, 59, 30}, Qt::UTC};
+ QCOMPARE(DecodedTime::spotTime("2359", nowUtc(), 60), firstExpected);
+ QCOMPARE(DecodedTime::spotTime("235945", nowUtc(), 15), secondExpected);
+ QCOMPARE(DecodedTime::spotTime("235930", nowUtc(), 15), thirdExpected);
+ }
+
+ void roundsFractionalPeriodForMidnight()
+ {
+ auto const expected = QDateTime {QDate {2026, 8, 16}, QTime {23, 59, 52}, Qt::UTC};
+ QCOMPARE(DecodedTime::spotTime("235952", nowUtc(), 7.5), expected);
+ }
+
+ void rejectsMalformedTimes()
+ {
+ for (auto const& encodedTime : {QString {}, QString {"123"}, QString {"1234567"},
+ QString {"2460"}, QString {"1260"},
+ QString {"126099"}, QString {"12x4"}}) {
+ QVERIFY(!DecodedTime::spotTime(encodedTime, nowUtc(), 60).isValid());
+ }
+ }
+};
+
+QTEST_APPLESS_MAIN(TestDecodedTime)
+
+#include "test_decoded_time.moc"
diff --git a/tests/unit/common/test_displaytext.cpp b/tests/unit/common/test_displaytext.cpp
new file mode 100644
index 00000000..d7fc4b94
--- /dev/null
+++ b/tests/unit/common/test_displaytext.cpp
@@ -0,0 +1,397 @@
+#include <QApplication>
+#include <QMouseEvent>
+#include <QScrollBar>
+#include <QTest>
+#include <QTextBlock>
+#include <QTextCursor>
+#include <QToolButton>
+
+#include "commons.h"
+#include "widgets/displaytext.h"
+
+namespace
+{
+ dec_data_t test_dec_data {};
+ int constexpr tone_buffer_size {250};
+}
+
+// The transceiver objects linked through wsjt_qt reference globals normally owned by MainWindow.
+dec_data_t& dec_data = test_dec_data;
+int volatile itone[tone_buffer_size] {};
+int volatile icw[tone_buffer_size] {};
+
+float gran ()
+{
+ return 0.0f;
+}
+
+class TestDisplayText final
+ : public QObject
+{
+ Q_OBJECT
+
+private:
+ static QPoint positionWithin (DisplayText const& display, QString const& text)
+ {
+ auto cursor = display.document ()->find (text);
+ cursor.setPosition (cursor.selectionStart () + text.size () / 2);
+ return display.cursorRect (cursor).center ();
+ }
+
+ static void sendMouseEvent (DisplayText& display, QEvent::Type type, QPoint const& position,
+ Qt::MouseButton button, Qt::MouseButtons buttons,
+ Qt::KeyboardModifiers modifiers = Qt::NoModifier)
+ {
+ QMouseEvent event {type, position, button, buttons, modifiers};
+ QApplication::sendEvent (display.viewport (), &event);
+ }
+
+ static void sendClick (DisplayText& display, QPoint const& position)
+ {
+ sendMouseEvent (display, QEvent::MouseButtonPress, position, Qt::LeftButton, Qt::LeftButton);
+ sendMouseEvent (display, QEvent::MouseButtonRelease, position, Qt::LeftButton, Qt::NoButton);
+ }
+
+ static void sendDoubleClick (DisplayText& display, QPoint const& position,
+ Qt::KeyboardModifiers modifiers = Qt::NoModifier)
+ {
+ sendMouseEvent (display, QEvent::MouseButtonDblClick, position, Qt::LeftButton,
+ Qt::LeftButton, modifiers);
+ sendMouseEvent (display, QEvent::MouseButtonRelease, position, Qt::LeftButton,
+ Qt::NoButton, modifiers);
+ }
+
+ static void populateForScrolling (DisplayText& display, int count = 80)
+ {
+ for (int i = 0; i < count; ++i)
+ {
+ display.insertText (QString {"%1 decode"}.arg (i, 3, 10, QLatin1Char {'0'}));
+ }
+ QApplication::processEvents ();
+ }
+
+ static QString topVisibleLine (DisplayText const& display)
+ {
+ return display.cursorForPosition (QPoint {1, 1}).block ().text ();
+ }
+
+private slots:
+ void insertionDoesNotRetargetDoubleClick ()
+ {
+ DisplayText display;
+ display.resize (640, 240);
+ display.insertText ("K1ABC intended decode");
+ display.show ();
+ QApplication::processEvents ();
+
+ auto const position = positionWithin (display, "K1ABC");
+ QCOMPARE (display.cursorForPosition (position).block ().text (), QString {"K1ABC intended decode"});
+
+ QString selected_line;
+ QString selected_word;
+ Qt::KeyboardModifiers selected_modifiers;
+ int selection_count {0};
+ connect (&display, &DisplayText::selectCallsign,
+ [&] (QString const& line, QString const& word, Qt::KeyboardModifiers modifiers) {
+ selected_line = line;
+ selected_word = word;
+ selected_modifiers = modifiers;
+ ++selection_count;
+ });
+
+ sendClick (display, position);
+ display.insertText ("K9XYZ newest decode");
+
+ QCOMPARE (display.textCursor ().block ().text (), QString {"K9XYZ newest decode"});
+ QCOMPARE (display.cursorForPosition (position).block ().text (), QString {"K1ABC intended decode"});
+
+ sendDoubleClick (display, position, Qt::ControlModifier);
+
+ QCOMPARE (selection_count, 1);
+ QCOMPARE (selected_line, QString {"K1ABC intended decode"});
+ QCOMPARE (selected_word, QString {"K1ABC"});
+ QCOMPARE (selected_modifiers, Qt::KeyboardModifiers {Qt::ControlModifier});
+ }
+
+ void movedContentKeepsFirstPressedTarget ()
+ {
+ DisplayText display;
+ display.resize (640, 240);
+ display.insertText ("K1ABC intended decode");
+ display.show ();
+ QApplication::processEvents ();
+
+ auto const position = positionWithin (display, "K1ABC");
+ QString selected_line;
+ QString selected_word;
+ connect (&display, &DisplayText::selectCallsign,
+ [&] (QString const& line, QString const& word, Qt::KeyboardModifiers) {
+ selected_line = line;
+ selected_word = word;
+ });
+
+ sendClick (display, position);
+ QTextCursor insertion {display.document ()};
+ insertion.insertText ("K9XYZ inserted above\n");
+ QApplication::processEvents ();
+
+ QCOMPARE (display.cursorForPosition (position).block ().text (), QString {"K9XYZ inserted above"});
+
+ sendDoubleClick (display, position);
+
+ QCOMPARE (selected_line, QString {"K1ABC intended decode"});
+ QCOMPARE (selected_word, QString {"K1ABC"});
+ }
+
+ void doubleClickWithoutPressUsesEventPosition ()
+ {
+ DisplayText display;
+ display.resize (640, 240);
+ display.insertText ("N0CALL direct target");
+ display.show ();
+ QApplication::processEvents ();
+
+ auto const position = positionWithin (display, "N0CALL");
+ QString selected_line;
+ QString selected_word;
+ connect (&display, &DisplayText::selectCallsign,
+ [&] (QString const& line, QString const& word, Qt::KeyboardModifiers) {
+ selected_line = line;
+ selected_word = word;
+ });
+
+ sendDoubleClick (display, position);
+
+ QCOMPARE (selected_line, QString {"N0CALL direct target"});
+ QCOMPARE (selected_word, QString {"N0CALL"});
+ }
+
+ void eraseCancelsCapturedTarget ()
+ {
+ DisplayText display;
+ display.resize (640, 240);
+ display.insertText ("K1ABC stale target");
+ display.show ();
+ QApplication::processEvents ();
+
+ auto const stale_position = positionWithin (display, "K1ABC");
+ int selection_count {0};
+ connect (&display, &DisplayText::selectCallsign,
+ [&] (QString const&, QString const&, Qt::KeyboardModifiers) {
+ ++selection_count;
+ });
+
+ sendClick (display, stale_position);
+ display.erase ();
+ display.insertText ("K9XYZ replacement target");
+ QApplication::processEvents ();
+
+ sendDoubleClick (display, positionWithin (display, "K9XYZ"));
+
+ QCOMPARE (selection_count, 0);
+ }
+
+ void canceledDoubleClickRestoresDirectFallback ()
+ {
+ DisplayText display;
+ display.resize (640, 240);
+ display.insertText ("K1ABC stale target");
+ display.show ();
+ QApplication::processEvents ();
+
+ auto const stale_position = positionWithin (display, "K1ABC");
+ QString selected_line;
+ QString selected_word;
+ int selection_count {0};
+ connect (&display, &DisplayText::selectCallsign,
+ [&] (QString const& line, QString const& word, Qt::KeyboardModifiers) {
+ selected_line = line;
+ selected_word = word;
+ ++selection_count;
+ });
+
+ sendClick (display, stale_position);
+ display.clear ();
+ display.insertText ("K9XYZ replacement target");
+ QApplication::processEvents ();
+ auto const replacement_position = positionWithin (display, "K9XYZ");
+
+ sendDoubleClick (display, replacement_position);
+ QCOMPARE (selection_count, 0);
+
+ sendDoubleClick (display, replacement_position);
+ QCOMPARE (selection_count, 1);
+ QCOMPARE (selected_line, QString {"K9XYZ replacement target"});
+ QCOMPARE (selected_word, QString {"K9XYZ"});
+ }
+
+ void pressAfterClearCapturesReplacement ()
+ {
+ DisplayText display;
+ display.resize (640, 240);
+ display.insertText ("K1ABC stale target");
+ display.show ();
+ QApplication::processEvents ();
+
+ auto const stale_position = positionWithin (display, "K1ABC");
+ QString selected_line;
+ QString selected_word;
+ connect (&display, &DisplayText::selectCallsign,
+ [&] (QString const& line, QString const& word, Qt::KeyboardModifiers) {
+ selected_line = line;
+ selected_word = word;
+ });
+
+ sendClick (display, stale_position);
+ display.clear ();
+ display.insertText ("K9XYZ replacement target");
+ QApplication::processEvents ();
+ auto const replacement_position = positionWithin (display, "K9XYZ");
+
+ sendClick (display, replacement_position);
+ sendDoubleClick (display, replacement_position);
+
+ QCOMPARE (selected_line, QString {"K9XYZ replacement target"});
+ QCOMPARE (selected_word, QString {"K9XYZ"});
+ }
+
+ void stickyScrollPreservesParkedContent ()
+ {
+ DisplayText display;
+ display.set_configuration (nullptr);
+ display.resize (360, 140);
+ display.show ();
+ populateForScrolling (display);
+
+ auto * scroll_bar = display.verticalScrollBar ();
+ auto * return_button = display.findChild<QToolButton *> ("returnToLiveActivityButton");
+ QVERIFY (return_button);
+ QCOMPARE (scroll_bar->value (), scroll_bar->maximum ());
+
+ scroll_bar->triggerAction (QAbstractSlider::SliderPageStepSub);
+ QApplication::processEvents ();
+ QVERIFY (scroll_bar->value () < scroll_bar->maximum ());
+ QVERIFY (return_button->isVisible ());
+ auto const parked_line = topVisibleLine (display);
+
+ display.insertText ("new live decode");
+ QApplication::processEvents ();
+
+ QCOMPARE (topVisibleLine (display), parked_line);
+ QVERIFY (return_button->isVisible ());
+ }
+
+ void formerLivePositionDoesNotResumeFollowing ()
+ {
+ DisplayText display;
+ display.set_configuration (nullptr);
+ display.resize (360, 140);
+ display.show ();
+ populateForScrolling (display);
+
+ auto * scroll_bar = display.verticalScrollBar ();
+ auto * return_button = display.findChild<QToolButton *> ("returnToLiveActivityButton");
+ QVERIFY (return_button);
+ auto const former_live_position = scroll_bar->maximum ();
+
+ scroll_bar->triggerAction (QAbstractSlider::SliderPageStepSub);
+ display.insertText ("first newer decode");
+ QApplication::processEvents ();
+ QVERIFY (scroll_bar->maximum () > former_live_position);
+
+ scroll_bar->setSliderPosition (former_live_position);
+ QVERIFY (QMetaObject::invokeMethod (scroll_bar, "sliderMoved",
+ Q_ARG (int, former_live_position)));
+ QApplication::processEvents ();
+ QCOMPARE (scroll_bar->value (), former_live_position);
+ QVERIFY (return_button->isVisible ());
+ auto const parked_line = topVisibleLine (display);
+
+ display.insertText ("second newer decode");
+ QApplication::processEvents ();
+
+ QCOMPARE (topVisibleLine (display), parked_line);
+ QVERIFY (scroll_bar->value () < scroll_bar->maximum ());
+ }
+
+ void returnControlIsAccessibleAndViewportBounded ()
+ {
+ DisplayText display;
+ display.set_configuration (nullptr);
+ display.resize (360, 140);
+ display.show ();
+ populateForScrolling (display);
+
+ auto * scroll_bar = display.verticalScrollBar ();
+ auto * return_button = display.findChild<QToolButton *> ("returnToLiveActivityButton");
+ QVERIFY (return_button);
+ scroll_bar->triggerAction (QAbstractSlider::SliderPageStepSub);
+ QApplication::processEvents ();
+
+ auto large_font = return_button->font ();
+ large_font.setPointSize (30);
+ return_button->setFont (large_font);
+ display.resize (120, 80);
+ QApplication::processEvents ();
+
+ QVERIFY (return_button->isVisible ());
+ QCOMPARE (return_button->focusPolicy (), Qt::StrongFocus);
+ QVERIFY (return_button->styleSheet ().isEmpty ());
+ QVERIFY (display.viewport ()->rect ().contains (return_button->geometry ()));
+
+ QTest::keyClick (return_button, Qt::Key_Space);
+
+ QCOMPARE (scroll_bar->value (), scroll_bar->maximum ());
+ QVERIFY (!return_button->isVisible ());
+ }
+
+ void unconfiguredDisplayKeepsOriginalFollowBehavior ()
+ {
+ DisplayText display;
+ display.resize (360, 140);
+ display.show ();
+ populateForScrolling (display);
+
+ auto * scroll_bar = display.verticalScrollBar ();
+ auto * return_button = display.findChild<QToolButton *> ("returnToLiveActivityButton");
+ QVERIFY (return_button);
+ scroll_bar->triggerAction (QAbstractSlider::SliderPageStepSub);
+ QApplication::processEvents ();
+ QVERIFY (scroll_bar->value () < scroll_bar->maximum ());
+
+ display.insertText ("queue update");
+ QApplication::processEvents ();
+
+ QCOMPARE (display.textCursor ().block ().text (), QString {"queue update"});
+ QVERIFY (display.viewport ()->rect ().intersects (display.cursorRect (display.textCursor ())));
+ QVERIFY (!return_button->isVisible ());
+ }
+
+ void fontChangePreservesParkedContent ()
+ {
+ DisplayText display;
+ display.set_configuration (nullptr);
+ display.resize (360, 140);
+ display.show ();
+ populateForScrolling (display);
+
+ auto * scroll_bar = display.verticalScrollBar ();
+ auto * return_button = display.findChild<QToolButton *> ("returnToLiveActivityButton");
+ QVERIFY (return_button);
+ scroll_bar->triggerAction (QAbstractSlider::SliderPageStepSub);
+ QApplication::processEvents ();
+ auto const parked_line = topVisibleLine (display);
+
+ auto larger_font = display.contentFont ();
+ larger_font.setPointSize (larger_font.pointSize () + 2);
+ display.setContentFont (larger_font);
+ QApplication::processEvents ();
+
+ QCOMPARE (topVisibleLine (display), parked_line);
+ QVERIFY (return_button->isVisible ());
+ }
+};
+
+QTEST_MAIN (TestDisplayText)
+
+#include "test_displaytext.moc"
diff --git a/tests/unit/common/test_emulate_split_transceiver.cpp b/tests/unit/common/test_emulate_split_transceiver.cpp
new file mode 100644
index 00000000..1ed8f189
--- /dev/null
+++ b/tests/unit/common/test_emulate_split_transceiver.cpp
@@ -0,0 +1,129 @@
+#include <memory>
+
+#include <QtTest>
+
+#include "Transceiver/EmulateSplitTransceiver.hpp"
+
+class FakeTransceiver final
+ : public Transceiver
+{
+ Q_OBJECT
+
+public:
+ FakeTransceiver ()
+ : Transceiver {nullptr, nullptr}
+ {
+ }
+
+ void set (TransceiverState const& state, unsigned sequence_number) noexcept override
+ {
+ last_state = state;
+ last_sequence_number = sequence_number;
+ }
+
+ void start (unsigned sequence_number) noexcept override
+ {
+ last_sequence_number = sequence_number;
+ }
+
+ void stop () noexcept override {}
+
+ void send_update (TransceiverState const& state, unsigned sequence_number)
+ {
+ Q_EMIT update (state, sequence_number);
+ }
+
+ void send_receive_audio (ReceiveAudio audio) { Q_EMIT receiveAudio (audio); }
+
+ TransceiverState last_state;
+ unsigned last_sequence_number {0};
+};
+
+class TestEmulateSplitTransceiver : public QObject
+{
+ Q_OBJECT
+
+private:
+ Q_SLOT void forwardsReceiveAudio ()
+ {
+ auto * raw_fake = new FakeTransceiver;
+ EmulateSplitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {raw_fake}};
+ ReceiveAudio observed;
+ connect (&transceiver, &Transceiver::receiveAudio,
+ this, [&observed] (ReceiveAudio audio) { observed = std::move (audio); });
+ auto block = std::make_shared<ReceiveAudioBlock> ();
+
+ raw_fake->send_receive_audio (block);
+
+ QCOMPARE (observed, ReceiveAudio {block});
+ }
+
+ Q_SLOT void fakeSplitDoesNotPublishTransientTxDialAsRxDial ()
+ {
+ auto * raw_fake = new FakeTransceiver;
+ EmulateSplitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {raw_fake}};
+ QSignalSpy updates {&transceiver, &Transceiver::update};
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.frequency (7074000);
+ requested.tx_frequency (7072500);
+ requested.split (true);
+ requested.ptt (true);
+
+ transceiver.set (requested, 17);
+
+ QCOMPARE (raw_fake->last_state.frequency (), requested.tx_frequency ());
+ QCOMPARE (raw_fake->last_state.tx_frequency (), Transceiver::Frequency {0});
+ QVERIFY (!raw_fake->last_state.split ());
+
+ Transceiver::TransceiverState wrapped_update;
+ wrapped_update.online (true);
+ wrapped_update.frequency (requested.tx_frequency ());
+ wrapped_update.split (false);
+ wrapped_update.ptt (false);
+
+ raw_fake->send_update (wrapped_update, 17);
+
+ QCOMPARE (updates.size (), 1);
+ auto const published = qvariant_cast<Transceiver::TransceiverState> (updates.takeFirst ().at (0));
+ QCOMPARE (published.frequency (), requested.frequency ());
+ QCOMPARE (published.tx_frequency (), requested.tx_frequency ());
+ QVERIFY (published.split ());
+ QVERIFY (!published.ptt ());
+ }
+
+ Q_SLOT void receiveModeStillFollowsManualRigQsy ()
+ {
+ auto * raw_fake = new FakeTransceiver;
+ EmulateSplitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {raw_fake}};
+ QSignalSpy updates {&transceiver, &Transceiver::update};
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.frequency (7074000);
+ requested.tx_frequency (7072500);
+ requested.split (true);
+ requested.ptt (false);
+
+ transceiver.set (requested, 18);
+
+ Transceiver::TransceiverState wrapped_update;
+ wrapped_update.online (true);
+ wrapped_update.frequency (14074000);
+ wrapped_update.split (false);
+ wrapped_update.ptt (false);
+
+ raw_fake->send_update (wrapped_update, 18);
+
+ QCOMPARE (updates.size (), 1);
+ auto const published = qvariant_cast<Transceiver::TransceiverState> (updates.takeFirst ().at (0));
+ QCOMPARE (published.frequency (), wrapped_update.frequency ());
+ QCOMPARE (published.tx_frequency (), requested.tx_frequency ());
+ QVERIFY (published.split ());
+ QVERIFY (!published.ptt ());
+ }
+};
+
+QTEST_MAIN (TestEmulateSplitTransceiver)
+#include "test_emulate_split_transceiver.moc"
diff --git a/tests/unit/common/test_fox_guard_bands.cpp b/tests/unit/common/test_fox_guard_bands.cpp
new file mode 100644
index 00000000..a7d1839c
--- /dev/null
+++ b/tests/unit/common/test_fox_guard_bands.cpp
@@ -0,0 +1,92 @@
+#include <QtTest>
+
+#include "FoxGuardBands.hpp"
+
+class TestFoxGuardBands
+ : public QObject
+{
+ Q_OBJECT
+
+private:
+ Q_SLOT void standard_ft8_first_and_last_guards_block ()
+ {
+ auto const first = FoxGuardBands::check (1840000);
+ QVERIFY (first.blocked);
+ QCOMPARE (static_cast<int> (first.kind), static_cast<int> (FoxGuardBands::GuardKind::StandardFT8));
+ QCOMPARE (first.guard_frequency, Radio::Frequency {1840000});
+
+ auto const last = FoxGuardBands::check (70154000);
+ QVERIFY (last.blocked);
+ QCOMPARE (static_cast<int> (last.kind), static_cast<int> (FoxGuardBands::GuardKind::StandardFT8));
+ QCOMPARE (last.guard_frequency, Radio::Frequency {70154000});
+ }
+
+ Q_SLOT void wspr_first_and_last_guards_block ()
+ {
+ auto const first = FoxGuardBands::check (1836600);
+ QVERIFY (first.blocked);
+ QCOMPARE (static_cast<int> (first.kind), static_cast<int> (FoxGuardBands::GuardKind::WSPR));
+ QCOMPARE (first.guard_frequency, Radio::Frequency {1836600});
+
+ auto const last = FoxGuardBands::check (28124600);
+ QVERIFY (last.blocked);
+ QCOMPARE (static_cast<int> (last.kind), static_cast<int> (FoxGuardBands::GuardKind::WSPR));
+ QCOMPARE (last.guard_frequency, Radio::Frequency {28124600});
+ }
+
+ Q_SLOT void standard_ft8_boundaries_are_exclusive_at_3000_hz ()
+ {
+ auto const below = FoxGuardBands::check (14074000 - 2999);
+ QVERIFY (below.blocked);
+ QCOMPARE (static_cast<int> (below.kind), static_cast<int> (FoxGuardBands::GuardKind::StandardFT8));
+ QCOMPARE (below.guard_frequency, Radio::Frequency {14074000});
+
+ auto const above = FoxGuardBands::check (14074000 + 2999);
+ QVERIFY (above.blocked);
+ QCOMPARE (static_cast<int> (above.kind), static_cast<int> (FoxGuardBands::GuardKind::StandardFT8));
+ QCOMPARE (above.guard_frequency, Radio::Frequency {14074000});
+
+ QVERIFY (!FoxGuardBands::check (14074000 - 3000).blocked);
+ QVERIFY (!FoxGuardBands::check (14074000 + 3000).blocked);
+ }
+
+ Q_SLOT void wspr_boundaries_match_existing_thresholds ()
+ {
+ auto const guard_frequency = Radio::Frequency {28124600};
+
+ auto const lower = FoxGuardBands::check (guard_frequency - 3499);
+ QVERIFY (lower.blocked);
+ QCOMPARE (static_cast<int> (lower.kind), static_cast<int> (FoxGuardBands::GuardKind::WSPR));
+ QCOMPARE (lower.guard_frequency, guard_frequency);
+
+ auto const upper = FoxGuardBands::check (guard_frequency + 299);
+ QVERIFY (upper.blocked);
+ QCOMPARE (static_cast<int> (upper.kind), static_cast<int> (FoxGuardBands::GuardKind::WSPR));
+ QCOMPARE (upper.guard_frequency, guard_frequency);
+
+ QVERIFY (!FoxGuardBands::check (guard_frequency - 3500).blocked);
+ QVERIFY (!FoxGuardBands::check (guard_frequency + 300).blocked);
+ }
+
+ Q_SLOT void standard_ft8_match_wins_over_wspr_match ()
+ {
+ auto const match = FoxGuardBands::check (1000000, {1000000}, {1000000});
+
+ QVERIFY (match.blocked);
+ QCOMPARE (static_cast<int> (match.kind), static_cast<int> (FoxGuardBands::GuardKind::StandardFT8));
+ QCOMPARE (match.guard_frequency, Radio::Frequency {1000000});
+ }
+
+ Q_SLOT void unrelated_frequency_is_unblocked ()
+ {
+ auto const match = FoxGuardBands::check (123456789);
+
+ QVERIFY (!match.blocked);
+ QCOMPARE (static_cast<int> (match.kind), static_cast<int> (FoxGuardBands::GuardKind::None));
+ QCOMPARE (match.guard_frequency, Radio::Frequency {0});
+ }
+};
+
+QTEST_MAIN (TestFoxGuardBands);
+
+#include "test_fox_guard_bands.moc"
diff --git a/tests/unit/common/test_fox_operator_actions.cpp b/tests/unit/common/test_fox_operator_actions.cpp
new file mode 100644
index 00000000..f6870fa1
--- /dev/null
+++ b/tests/unit/common/test_fox_operator_actions.cpp
@@ -0,0 +1,124 @@
+#include <QMap>
+#include <QQueue>
+#include <QTest>
+
+#include "FoxOperatorActions.hpp"
+
+namespace
+{
+ QString queueLine (QString const& call, QString const& details)
+ {
+ return (call + QString (12, ' ')).left (12) + details;
+ }
+
+ struct Qso
+ {
+ int ncall;
+ int sentinel;
+ };
+}
+
+class TestFoxOperatorActions final
+ : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void moveToFrontUsesLiveQueueLine ()
+ {
+ auto const first = queueLine ("W1AAA", "-02 FN31");
+ auto const live_target = queueLine ("K1ABC", "+04 FN42");
+ QQueue<QString> queue;
+ queue.enqueue (first);
+ queue.enqueue (live_target);
+
+ QVERIFY (FoxOperatorActions::moveQueuedHoundToFront (
+ queue, queueLine ("K1ABC", "+01 stale snapshot")));
+
+ QCOMPARE (queue.size (), 2);
+ QCOMPARE (queue.at (0), live_target);
+ QCOMPARE (queue.at (1), first);
+ }
+
+ void moveToFrontRejectsMissingHound ()
+ {
+ auto const live_line = queueLine ("W1AAA", "-02 FN31");
+ QQueue<QString> queue;
+ queue.enqueue (live_line);
+
+ QVERIFY (!FoxOperatorActions::moveQueuedHoundToFront (
+ queue, queueLine ("K1ABC", "+01 stale snapshot")));
+
+ QCOMPARE (queue.size (), 1);
+ QCOMPARE (queue.at (0), live_line);
+ }
+
+ void removeUsesLiveQueueCallsign ()
+ {
+ auto const retained = queueLine ("W1AAA", "-02 FN31");
+ QQueue<QString> queue;
+ queue.enqueue (retained);
+ queue.enqueue (queueLine ("K1ABC", "+04 FN42"));
+ queue.enqueue (queueLine ("K1ABC", "+02 FN41"));
+
+ QVERIFY (FoxOperatorActions::removeQueuedHound (
+ queue, queueLine ("K1ABC", "+01 stale snapshot")));
+
+ QCOMPARE (queue.size (), 1);
+ QCOMPARE (queue.at (0), retained);
+ }
+
+ void removeRejectsMissingHound ()
+ {
+ auto const live_line = queueLine ("W1AAA", "-02 FN31");
+ QQueue<QString> queue;
+ queue.enqueue (live_line);
+
+ QVERIFY (!FoxOperatorActions::removeQueuedHound (
+ queue, queueLine ("K1ABC", "+01 stale snapshot")));
+
+ QCOMPARE (queue.size (), 1);
+ QCOMPARE (queue.at (0), live_line);
+ }
+
+ void timeoutRequiresActiveCallAndQso ()
+ {
+ QQueue<QString> in_progress;
+ in_progress.enqueue ("K1ABC");
+ QMap<QString, Qso> qsos {{"K1ABC", {2, 73}}};
+
+ QVERIFY (FoxOperatorActions::timeoutIfActive (
+ in_progress, qsos, queueLine ("K1ABC", "3 (rx)"), 6));
+
+ QCOMPARE (qsos.value ("K1ABC").ncall, 6);
+ QCOMPARE (qsos.value ("K1ABC").sentinel, 73);
+ }
+
+ void timeoutRejectsCallNoLongerInProgress ()
+ {
+ QQueue<QString> in_progress;
+ QMap<QString, Qso> qsos {{"K1ABC", {2, 73}}};
+
+ QVERIFY (!FoxOperatorActions::timeoutIfActive (
+ in_progress, qsos, queueLine ("K1ABC", "3 (rx)"), 6));
+
+ QCOMPARE (qsos.value ("K1ABC").ncall, 2);
+ QCOMPARE (qsos.value ("K1ABC").sentinel, 73);
+ }
+
+ void timeoutDoesNotCreateMissingQso ()
+ {
+ QQueue<QString> in_progress;
+ in_progress.enqueue ("K1ABC");
+ QMap<QString, Qso> qsos;
+
+ QVERIFY (!FoxOperatorActions::timeoutIfActive (
+ in_progress, qsos, queueLine ("K1ABC", "3 (rx)"), 6));
+
+ QVERIFY (qsos.isEmpty ());
+ }
+};
+
+QTEST_MAIN (TestFoxOperatorActions)
+
+#include "test_fox_operator_actions.moc"
diff --git a/tests/unit/common/test_frequency_editors.cpp b/tests/unit/common/test_frequency_editors.cpp
new file mode 100644
index 00000000..1d5dfd50
--- /dev/null
+++ b/tests/unit/common/test_frequency_editors.cpp
@@ -0,0 +1,273 @@
+#include <QtTest>
+
+#include <cmath>
+#include <limits>
+#include <memory>
+
+#include <QComboBox>
+#include <QDateTime>
+#include <QFocusEvent>
+#include <QLineEdit>
+#include <QModelIndex>
+#include <QString>
+
+#include "Radio.hpp"
+#include "models/Bands.hpp"
+#include "models/FrequencyList.hpp"
+#include "models/IARURegions.hpp"
+#include "models/Modes.hpp"
+#include "models/StationList.hpp"
+#include "validators/LiveFrequencyValidator.hpp"
+#include "widgets/FrequencyDeltaLineEdit.hpp"
+#include "widgets/FrequencyLineEdit.hpp"
+
+namespace
+{
+ constexpr Radio::Frequency preferred_3cm_frequency {10368200000ULL};
+ constexpr Radio::Frequency entered_3cm_frequency {10368799000ULL};
+ constexpr Radio::Frequency preferred_20m_frequency {14074000ULL};
+
+ class LiveFrequencyEditorFixture
+ {
+ public:
+ LiveFrequencyEditorFixture ()
+ : frequencies {&bands}
+ {
+ frequencies.add ({preferred_3cm_frequency, Modes::Q65, IARURegions::ALL,
+ {}, {}, {}, {}, true});
+ frequencies.add ({preferred_20m_frequency, Modes::FT8, IARURegions::ALL,
+ {}, {}, {}, {}, true});
+ band_editor.setEditable (true);
+ band_editor.setModel (&frequencies);
+ band_editor.setModelColumn (FrequencyList_v2_101::frequency_mhz_column);
+ validator = std::make_unique<LiveFrequencyValidator> (
+ &band_editor, &bands, &frequencies, &nominal_frequency, false);
+ band_editor.setValidator (validator.get ());
+ band_editor.setCurrentText (bands.find (nominal_frequency));
+
+ QObject::connect (validator.get (), &LiveFrequencyValidator::valid,
+ [&] (Radio::Frequency frequency) {
+ requests.append (frequency);
+ bands_at_request.append (band_editor.currentText ());
+ if (accept_requests)
+ {
+ nominal_frequency = frequency;
+ }
+ else
+ {
+ band_editor.setCurrentText (bands.find (nominal_frequency));
+ }
+ });
+ }
+
+ void enter (QString const& text, QString const& completed_text = {})
+ {
+ band_editor.setFocus ();
+ band_editor.lineEdit ()->selectAll ();
+ QTest::keyClicks (band_editor.lineEdit (), text);
+ if (!completed_text.isEmpty ()) band_editor.lineEdit ()->setText (completed_text);
+ QTest::keyClick (band_editor.lineEdit (), Qt::Key_Return);
+ QCoreApplication::processEvents ();
+ }
+
+ void send_focus_out ()
+ {
+ QFocusEvent event {QEvent::FocusOut, Qt::MouseFocusReason};
+ QCoreApplication::sendEvent (band_editor.lineEdit (), &event);
+ QCoreApplication::processEvents ();
+ }
+
+ Bands bands;
+ FrequencyList_v2_101 frequencies;
+ Radio::Frequency nominal_frequency {preferred_3cm_frequency};
+ QComboBox band_editor;
+ QVector<Radio::Frequency> requests;
+ QVector<QString> bands_at_request;
+ bool accept_requests {true};
+ std::unique_ptr<LiveFrequencyValidator> validator;
+ };
+}
+
+class TestFrequencyEditors
+ : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ void frequency_line_edit_requires_positive_frequency ();
+ void frequency_line_edit_accepts_frequency_above_signed_range ();
+ void frequency_conversion_rejects_unsigned_limit ();
+ void frequency_delta_line_edit_accepts_signed_offsets ();
+ void station_list_rejects_invalid_offset_variants ();
+ void frequency_list_rejects_invalid_frequency_variants ();
+ void live_frequency_entry_requests_one_qsy_data ();
+ void live_frequency_entry_requests_one_qsy ();
+ void live_frequency_band_entry_requests_working_frequency ();
+ void live_frequency_rejected_request_preserves_selection ();
+ void live_frequency_focus_loss_without_edit_is_harmless ();
+};
+
+void TestFrequencyEditors::frequency_line_edit_requires_positive_frequency ()
+{
+ FrequencyLineEdit editor;
+
+ bool ok {true};
+ editor.setText ("0");
+ QCOMPARE (editor.frequency (&ok), Radio::Frequency {0});
+ QVERIFY (!ok);
+
+ editor.setText ("0.000001");
+ QCOMPARE (editor.frequency (&ok), Radio::Frequency {1});
+ QVERIFY (ok);
+}
+
+void TestFrequencyEditors::frequency_line_edit_accepts_frequency_above_signed_range ()
+{
+ FrequencyLineEdit editor;
+ editor.setText ("9223372036864.000000");
+
+ QVERIFY (editor.hasAcceptableInput ());
+ bool ok {false};
+ QCOMPARE (editor.frequency (&ok), Radio::Frequency {9223372036864000000ULL});
+ QVERIFY (ok);
+}
+
+void TestFrequencyEditors::frequency_conversion_rejects_unsigned_limit ()
+{
+ auto const limit = std::ldexp (1., std::numeric_limits<Radio::Frequency>::digits);
+ bool ok {true};
+
+ QCOMPARE (Radio::frequency (limit, 0, &ok), Radio::Frequency {0});
+ QVERIFY (!ok);
+}
+
+void TestFrequencyEditors::frequency_delta_line_edit_accepts_signed_offsets ()
+{
+ FrequencyDeltaLineEdit editor;
+
+ bool ok {false};
+ editor.setText ("0");
+ QCOMPARE (editor.frequency_delta (&ok), Radio::FrequencyDelta {0});
+ QVERIFY (ok);
+
+ editor.setText ("-0.001");
+ QCOMPARE (editor.frequency_delta (&ok), Radio::FrequencyDelta {-1000});
+ QVERIFY (ok);
+}
+
+void TestFrequencyEditors::station_list_rejects_invalid_offset_variants ()
+{
+ Bands bands;
+ StationList stations {&bands, {{"20m", 1000, "Yagi"}}};
+ auto const offset_index = stations.index (0, StationList::offset_column);
+
+ QVERIFY (!stations.setData (offset_index, QString {"abc"}, Qt::EditRole));
+ QCOMPARE (stations.data (offset_index, Qt::EditRole).value<Radio::FrequencyDelta> (),
+ Radio::FrequencyDelta {1000});
+
+ QVERIFY (stations.setData (offset_index, Radio::FrequencyDelta {-2000}, Qt::EditRole));
+ QCOMPARE (stations.data (offset_index, Qt::EditRole).value<Radio::FrequencyDelta> (),
+ Radio::FrequencyDelta {-2000});
+}
+
+void TestFrequencyEditors::frequency_list_rejects_invalid_frequency_variants ()
+{
+ Bands bands;
+ FrequencyList_v2_101 frequencies {&bands};
+ auto const added_index = frequencies.add ({14074000, Modes::FT8, IARURegions::ALL,
+ QString {}, QString {}, QDateTime {}, QDateTime {}, false});
+ auto const frequency_index = frequencies.index (added_index.row (), FrequencyList_v2_101::frequency_column);
+
+ QVERIFY (!frequencies.setData (QModelIndex {}, Radio::Frequency {14075000}, Qt::EditRole));
+ QVERIFY (!frequencies.setData (frequency_index, QString {"abc"}, Qt::EditRole));
+ QCOMPARE (frequencies.data (frequency_index, Qt::EditRole).value<Radio::Frequency> (),
+ Radio::Frequency {14074000});
+
+ QVERIFY (!frequencies.setData (frequency_index, Radio::Frequency {0}, Qt::EditRole));
+ QCOMPARE (frequencies.data (frequency_index, Qt::EditRole).value<Radio::Frequency> (),
+ Radio::Frequency {14074000});
+
+ QVERIFY (frequencies.setData (frequency_index, Radio::Frequency {14075000}, Qt::EditRole));
+ QCOMPARE (frequencies.data (frequency_index, Qt::EditRole).value<Radio::Frequency> (),
+ Radio::Frequency {14075000});
+}
+
+void TestFrequencyEditors::live_frequency_entry_requests_one_qsy_data ()
+{
+ QTest::addColumn<QString> ("entry");
+ QTest::addColumn<QString> ("completed_text");
+ QTest::addColumn<Radio::Frequency> ("expected_frequency");
+
+ QTest::newRow ("full-frequency")
+ << QString {"10368.799000"} << QString {} << entered_3cm_frequency;
+ QTest::newRow ("relative-khz")
+ << QString {"799k"} << QString {} << entered_3cm_frequency;
+ QTest::newRow ("completed-working-frequency")
+ << QString {"14.074"} << QString {"14.074000"} << preferred_20m_frequency;
+}
+
+void TestFrequencyEditors::live_frequency_entry_requests_one_qsy ()
+{
+ QFETCH (QString, entry);
+ QFETCH (QString, completed_text);
+ QFETCH (Radio::Frequency, expected_frequency);
+ LiveFrequencyEditorFixture fixture;
+
+ fixture.enter (entry, completed_text);
+
+ QCOMPARE (fixture.requests, QVector<Radio::Frequency> {expected_frequency});
+ QCOMPARE (fixture.bands_at_request,
+ QVector<QString> {fixture.bands.find (expected_frequency)});
+ QCOMPARE (fixture.band_editor.currentText (), fixture.bands.find (expected_frequency));
+
+ fixture.send_focus_out ();
+ QCOMPARE (fixture.requests, QVector<Radio::Frequency> {expected_frequency});
+
+ fixture.send_focus_out ();
+ QCOMPARE (fixture.requests, QVector<Radio::Frequency> {expected_frequency});
+}
+
+void TestFrequencyEditors::live_frequency_band_entry_requests_working_frequency ()
+{
+ LiveFrequencyEditorFixture fixture;
+ fixture.nominal_frequency = 14074000;
+ fixture.band_editor.setCurrentText (fixture.bands.find (fixture.nominal_frequency));
+
+ fixture.enter ("3cm");
+
+ QCOMPARE (fixture.requests, QVector<Radio::Frequency> {preferred_3cm_frequency});
+ QCOMPARE (fixture.bands_at_request, QVector<QString> {QString {"3cm"}});
+ QCOMPARE (fixture.band_editor.currentText (), QString {"3cm"});
+}
+
+void TestFrequencyEditors::live_frequency_rejected_request_preserves_selection ()
+{
+ LiveFrequencyEditorFixture fixture;
+ fixture.accept_requests = false;
+
+ fixture.enter ("14.074", "14.074000");
+
+ QCOMPARE (fixture.requests, QVector<Radio::Frequency> {preferred_20m_frequency});
+ QCOMPARE (fixture.bands_at_request, QVector<QString> {QString {"20m"}});
+ QCOMPARE (fixture.band_editor.currentText (), QString {"3cm"});
+
+ fixture.send_focus_out ();
+ QCOMPARE (fixture.requests, QVector<Radio::Frequency> {preferred_20m_frequency});
+ QCOMPARE (fixture.band_editor.currentText (), QString {"3cm"});
+}
+
+void TestFrequencyEditors::live_frequency_focus_loss_without_edit_is_harmless ()
+{
+ LiveFrequencyEditorFixture fixture;
+ fixture.band_editor.lineEdit ()->setText ("10368.200000");
+ fixture.band_editor.setFocus ();
+ QCoreApplication::processEvents ();
+
+ fixture.send_focus_out ();
+ QCOMPARE (fixture.band_editor.currentText (), QString {"3cm"});
+ QVERIFY (fixture.requests.isEmpty ());
+}
+
+QTEST_MAIN (TestFrequencyEditors)
+
+#include "test_frequency_editors.moc"
diff --git a/tests/unit/common/test_hamlib_mode.cpp b/tests/unit/common/test_hamlib_mode.cpp
new file mode 100644
index 00000000..ddae2878
--- /dev/null
+++ b/tests/unit/common/test_hamlib_mode.cpp
@@ -0,0 +1,78 @@
+#include <QtTest>
+
+#include "Transceiver/HamlibMode.hpp"
+
+class TestHamlibMode : public QObject
+{
+ Q_OBJECT
+
+private:
+ Q_SLOT void fromHamlib_data ()
+ {
+ QTest::addColumn<rmode_t> ("hamlib_mode");
+ QTest::addColumn<Transceiver::MODE> ("transceiver_mode");
+
+ QTest::newRow ("PKTUSB") << rmode_t {RIG_MODE_PKTUSB} << Transceiver::DIG_U;
+ QTest::newRow ("USBD1") << rmode_t {RIG_MODE_USBD1} << Transceiver::DIG_U;
+ QTest::newRow ("USBD2") << rmode_t {RIG_MODE_USBD2} << Transceiver::DIG_U;
+ QTest::newRow ("USBD3") << rmode_t {RIG_MODE_USBD3} << Transceiver::DIG_U;
+ QTest::newRow ("PKTLSB") << rmode_t {RIG_MODE_PKTLSB} << Transceiver::DIG_L;
+ QTest::newRow ("LSBD1") << rmode_t {RIG_MODE_LSBD1} << Transceiver::DIG_L;
+ QTest::newRow ("LSBD2") << rmode_t {RIG_MODE_LSBD2} << Transceiver::DIG_L;
+ QTest::newRow ("LSBD3") << rmode_t {RIG_MODE_LSBD3} << Transceiver::DIG_L;
+ }
+
+ Q_SLOT void fromHamlib ()
+ {
+ QFETCH (rmode_t, hamlib_mode);
+ QFETCH (Transceiver::MODE, transceiver_mode);
+
+ QCOMPARE (HamlibMode::from_hamlib (hamlib_mode), transceiver_mode);
+ }
+
+ Q_SLOT void toHamlib ()
+ {
+ QCOMPARE (HamlibMode::to_hamlib (Transceiver::DIG_U), RIG_MODE_PKTUSB);
+ QCOMPARE (HamlibMode::to_hamlib (Transceiver::DIG_L), RIG_MODE_PKTLSB);
+ }
+
+ Q_SLOT void satisfiesRequest_data ()
+ {
+ QTest::addColumn<rmode_t> ("requested");
+ QTest::addColumn<rmode_t> ("current");
+ QTest::addColumn<bool> ("satisfied");
+
+ QTest::newRow ("exact-PKTUSB") << rmode_t {RIG_MODE_PKTUSB} << rmode_t {RIG_MODE_PKTUSB} << true;
+ QTest::newRow ("PKTUSB-USBD1") << rmode_t {RIG_MODE_PKTUSB} << rmode_t {RIG_MODE_USBD1} << true;
+ QTest::newRow ("PKTUSB-USBD2") << rmode_t {RIG_MODE_PKTUSB} << rmode_t {RIG_MODE_USBD2} << true;
+ QTest::newRow ("PKTUSB-USBD3") << rmode_t {RIG_MODE_PKTUSB} << rmode_t {RIG_MODE_USBD3} << true;
+ QTest::newRow ("PKTLSB-LSBD1") << rmode_t {RIG_MODE_PKTLSB} << rmode_t {RIG_MODE_LSBD1} << true;
+ QTest::newRow ("PKTLSB-LSBD2") << rmode_t {RIG_MODE_PKTLSB} << rmode_t {RIG_MODE_LSBD2} << true;
+ QTest::newRow ("PKTLSB-LSBD3") << rmode_t {RIG_MODE_PKTLSB} << rmode_t {RIG_MODE_LSBD3} << true;
+ QTest::newRow ("PKTUSB-USB") << rmode_t {RIG_MODE_PKTUSB} << rmode_t {RIG_MODE_USB} << false;
+ QTest::newRow ("USB-USBD2") << rmode_t {RIG_MODE_USB} << rmode_t {RIG_MODE_USBD2} << false;
+ QTest::newRow ("USBD1-USBD2") << rmode_t {RIG_MODE_USBD1} << rmode_t {RIG_MODE_USBD2} << false;
+ QTest::newRow ("PKTUSB-LSBD2") << rmode_t {RIG_MODE_PKTUSB} << rmode_t {RIG_MODE_LSBD2} << false;
+ QTest::newRow ("PKTLSB-USBD2") << rmode_t {RIG_MODE_PKTLSB} << rmode_t {RIG_MODE_USBD2} << false;
+ }
+
+ Q_SLOT void satisfiesRequest ()
+ {
+ QFETCH (rmode_t, requested);
+ QFETCH (rmode_t, current);
+ QFETCH (bool, satisfied);
+
+ QCOMPARE (HamlibMode::satisfies_request (requested, current), satisfied);
+ }
+
+ Q_SLOT void changeRequired ()
+ {
+ QVERIFY (!HamlibMode::change_required (Transceiver::UNK, RIG_MODE_USBD2));
+ QVERIFY (!HamlibMode::change_required (Transceiver::DIG_U, RIG_MODE_USBD2));
+ QVERIFY (HamlibMode::change_required (Transceiver::DIG_U, RIG_MODE_USB));
+ QVERIFY (HamlibMode::change_required (Transceiver::USB, RIG_MODE_USBD2));
+ }
+};
+
+QTEST_MAIN (TestHamlibMode)
+#include "test_hamlib_mode.moc"
diff --git a/tests/unit/common/test_hamlib_vfo_role_state.cpp b/tests/unit/common/test_hamlib_vfo_role_state.cpp
new file mode 100644
index 00000000..44edb39a
--- /dev/null
+++ b/tests/unit/common/test_hamlib_vfo_role_state.cpp
@@ -0,0 +1,83 @@
+#include <tuple>
+
+#include <QtTest>
+
+#include "Transceiver/HamlibVfoRoleState.hpp"
+
+class TestHamlibVfoRoleState : public QObject
+{
+ Q_OBJECT
+
+private:
+ Q_SLOT void receivingOnVfoAUsesNormalRoles ()
+ {
+ HamlibVfoRoleState state;
+ state.observe_active_vfo (RIG_VFO_A, false);
+
+ auto const vfos = state.resolve (RIG_VFO_A, RIG_VFO_B);
+ QCOMPARE (std::get<0> (vfos), RIG_VFO_A);
+ QCOMPARE (std::get<1> (vfos), RIG_VFO_B);
+ }
+
+ Q_SLOT void receivingOnVfoBReversesRoles ()
+ {
+ HamlibVfoRoleState state;
+ state.observe_active_vfo (RIG_VFO_B, false);
+
+ auto const vfos = state.resolve (RIG_VFO_A, RIG_VFO_B);
+ QCOMPARE (std::get<0> (vfos), RIG_VFO_B);
+ QCOMPARE (std::get<1> (vfos), RIG_VFO_A);
+ }
+
+ Q_SLOT void splitPttPreservesNormalRoles ()
+ {
+ HamlibVfoRoleState state;
+ state.observe_active_vfo (RIG_VFO_A, false);
+ state.observe_active_vfo (RIG_VFO_B, true);
+
+ auto const vfos = state.resolve (RIG_VFO_A, RIG_VFO_B);
+ QCOMPARE (std::get<0> (vfos), RIG_VFO_A);
+ QCOMPARE (std::get<1> (vfos), RIG_VFO_B);
+ }
+
+ Q_SLOT void splitPttPreservesReversedRoles ()
+ {
+ HamlibVfoRoleState state;
+ state.observe_active_vfo (RIG_VFO_B, false);
+ state.observe_active_vfo (RIG_VFO_A, true);
+
+ auto const vfos = state.resolve (RIG_VFO_A, RIG_VFO_B);
+ QCOMPARE (std::get<0> (vfos), RIG_VFO_B);
+ QCOMPARE (std::get<1> (vfos), RIG_VFO_A);
+ }
+
+ Q_SLOT void observationResumesAfterSplitPtt ()
+ {
+ HamlibVfoRoleState state;
+ state.observe_active_vfo (RIG_VFO_A, false);
+ state.observe_active_vfo (RIG_VFO_B, true);
+ state.observe_active_vfo (RIG_VFO_B, false);
+
+ auto const vfos = state.resolve (RIG_VFO_A, RIG_VFO_B);
+ QCOMPARE (std::get<0> (vfos), RIG_VFO_B);
+ QCOMPARE (std::get<1> (vfos), RIG_VFO_A);
+ }
+
+ Q_SLOT void resetRestoresNormalRoles ()
+ {
+ HamlibVfoRoleState state;
+ auto vfos = state.resolve (RIG_VFO_A, RIG_VFO_B);
+ QCOMPARE (std::get<0> (vfos), RIG_VFO_A);
+ QCOMPARE (std::get<1> (vfos), RIG_VFO_B);
+
+ state.observe_active_vfo (RIG_VFO_B, false);
+ state.reset ();
+
+ vfos = state.resolve (RIG_VFO_A, RIG_VFO_B);
+ QCOMPARE (std::get<0> (vfos), RIG_VFO_A);
+ QCOMPARE (std::get<1> (vfos), RIG_VFO_B);
+ }
+};
+
+QTEST_APPLESS_MAIN (TestHamlibVfoRoleState)
+#include "test_hamlib_vfo_role_state.moc"
diff --git a/tests/unit/common/test_highlighting_rules.cpp b/tests/unit/common/test_highlighting_rules.cpp
new file mode 100644
index 00000000..77e56852
--- /dev/null
+++ b/tests/unit/common/test_highlighting_rules.cpp
@@ -0,0 +1,86 @@
+#include <QtTest>
+
+#include "HighlightingRules.hpp"
+
+class TestHighlightingRules
+ : public QObject
+{
+ Q_OBJECT
+
+private:
+ Q_SLOT void directional_call_matching_data ()
+ {
+ QTest::addColumn<QString> ("configured_entries");
+ QTest::addColumn<QString> ("directional_call");
+ QTest::addColumn<bool> ("matches");
+
+ QTest::newRow ("first entry") << "DX,POTA,SOTA," << "DX" << true;
+ QTest::newRow ("middle entry") << "DX,POTA,SOTA," << "POTA" << true;
+ QTest::newRow ("last entry") << "DX,POTA,SOTA," << "SOTA" << true;
+ QTest::newRow ("last without trailing comma") << "DX,POTA,SOTA" << "SOTA" << true;
+ QTest::newRow ("documented spaces") << "DX, POTA, SOTA," << "POTA" << true;
+ QTest::newRow ("single entry") << "POTA" << "POTA" << true;
+ QTest::newRow ("single trailing comma") << "POTA," << "POTA" << true;
+ QTest::newRow ("legacy leading comma") << ",POTA," << "POTA" << true;
+ QTest::newRow ("empty fields") << ",, POTA ,," << "POTA" << true;
+ QTest::newRow ("lowercase entry") << "dx,pota," << "POTA" << true;
+ QTest::newRow ("callsign suffix") << "K1DX," << "DX" << false;
+ QTest::newRow ("longer token") << "NOTPOTA," << "POTA" << false;
+ QTest::newRow ("prefix syntax") << "VK;ZL;T88;" << "VK" << false;
+ QTest::newRow ("missing entry") << "DX,POTA," << "SOTA" << false;
+ QTest::newRow ("empty configuration") << "" << "DX" << false;
+ QTest::newRow ("empty directional call") << "DX," << "" << false;
+ }
+
+ Q_SLOT void directional_call_matching ()
+ {
+ QFETCH (QString, configured_entries);
+ QFETCH (QString, directional_call);
+ QFETCH (bool, matches);
+
+ QCOMPARE (HighlightingRules::matchesDirectionalCall (configured_entries, directional_call), matches);
+ }
+
+ Q_SLOT void callsign_prefix_matching_data ()
+ {
+ QTest::addColumn<QString> ("configured_entries");
+ QTest::addColumn<QString> ("call");
+ QTest::addColumn<bool> ("matches");
+
+ QTest::newRow ("exact callsign") << "W1AW," << "W1AW" << true;
+ QTest::newRow ("exact callsign, no match") << "W1AW," << "K1ABC" << false;
+ QTest::newRow ("3-char prefix") << ";OK9;" << "OK9ABC" << true;
+ QTest::newRow ("3-char prefix, unanchored substring is not a match") << ";HOK9;" << "OK9ABC" << false;
+ QTest::newRow ("2-char prefix") << ";VK;" << "VK2ABC" << true;
+ QTest::newRow ("bare 1-char prefix matches digit-second call") << ";K;" << "K1ABC" << true;
+ QTest::newRow ("bare 1-char prefix does not match compound entity") << ";K;" << "KH6ABC" << false;
+ QTest::newRow ("wildcard 1-char prefix matches digit-second call") << ";K*;" << "K1ABC" << true;
+ QTest::newRow ("wildcard 1-char prefix matches compound entity") << ";K*;" << "KH6ABC" << true;
+ QTest::newRow ("exclusion overrides wildcard for 3-char prefix") << ";K*;!KH6!" << "KH6ABC" << false;
+ QTest::newRow ("exclusion overrides wildcard for 2-char prefix") << ";K*;!KL!" << "KL7ABC" << false;
+ QTest::newRow ("all three named exclusions apply") << ";K*;!KH6!KL!KP!" << "KP4ABC" << false;
+ QTest::newRow ("exclusion does not affect plain matches") << ";K*;!KH6!" << "K1ABC" << true;
+ QTest::newRow ("exclusion does not affect an unrelated 2-char prefix") << ";K*;VK;!KH6!" << "VK2ABC" << true;
+ QTest::newRow ("no configured entries") << "" << "K1ABC" << false;
+ QTest::newRow ("call too short") << ";K*;" << "K1" << false;
+ QTest::newRow ("documented format's first prefix has no leading semicolon")
+ << "VK;ZL;T88;" << "VK2ABC" << true;
+ QTest::newRow ("exact callsign does not match as a substring tail of a longer entry")
+ << "AK1ABC," << "K1ABC" << false;
+ QTest::newRow ("exact callsign still matches when properly delimited alongside a longer entry")
+ << "AK1ABC,K1ABC," << "K1ABC" << true;
+ }
+
+ Q_SLOT void callsign_prefix_matching ()
+ {
+ QFETCH (QString, configured_entries);
+ QFETCH (QString, call);
+ QFETCH (bool, matches);
+
+ QCOMPARE (HighlightingRules::matchesCallsignPrefix (configured_entries, call), matches);
+ }
+};
+
+QTEST_MAIN (TestHighlightingRules);
+
+#include "test_highlighting_rules.moc"
diff --git a/tests/unit/common/test_hound_transmission_policy.cpp b/tests/unit/common/test_hound_transmission_policy.cpp
new file mode 100644
index 00000000..5a71417b
--- /dev/null
+++ b/tests/unit/common/test_hound_transmission_policy.cpp
@@ -0,0 +1,179 @@
+#include <QtTest/QtTest>
+
+#include "HoundTransmissionPolicy.hpp"
+
+class TestHoundTransmissionPolicy final : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void planFoxReportReply_data ();
+ void planFoxReportReply ();
+ void planInitialCallingFrequency_data ();
+ void planInitialCallingFrequency ();
+ void planReplyTransmission_data ();
+ void planReplyTransmission ();
+};
+
+void TestHoundTransmissionPolicy::planFoxReportReply_data ()
+{
+ QTest::addColumn<int> ("protocol");
+ QTest::addColumn<bool> ("tune");
+ QTest::addColumn<bool> ("autoEnabled");
+ QTest::addColumn<int> ("priorReplyState");
+ QTest::addColumn<bool> ("applyReply");
+ QTest::addColumn<bool> ("enableAuto");
+ QTest::addColumn<int> ("frequencyAction");
+ QTest::addColumn<int> ("nextReplyState");
+
+ using namespace HoundTransmissionPolicy;
+ QTest::newRow ("classic") << int (Protocol::Classic) << false << false
+ << int (ReplyState::None) << true << true << int (FrequencyAction::Set)
+ << int (ReplyState::FirstReplyPending);
+ QTest::newRow ("auto already enabled") << int (Protocol::Classic) << false << true
+ << int (ReplyState::None) << true << false << int (FrequencyAction::Set)
+ << int (ReplyState::FirstReplyPending);
+ QTest::newRow ("SuperHound") << int (Protocol::SuperFox) << false << false
+ << int (ReplyState::None) << true << true << int (FrequencyAction::Keep)
+ << int (ReplyState::FirstReplyPending);
+ QTest::newRow ("tune") << int (Protocol::Classic) << true << false
+ << int (ReplyState::FirstReplySent) << false << false << int (FrequencyAction::Keep)
+ << int (ReplyState::FirstReplySent);
+}
+
+void TestHoundTransmissionPolicy::planFoxReportReply ()
+{
+ QFETCH (int, protocol);
+ QFETCH (bool, tune);
+ QFETCH (bool, autoEnabled);
+ QFETCH (int, priorReplyState);
+ QFETCH (bool, applyReply);
+ QFETCH (bool, enableAuto);
+ QFETCH (int, frequencyAction);
+ QFETCH (int, nextReplyState);
+
+ using namespace HoundTransmissionPolicy;
+ State state;
+ state.replyState = static_cast<ReplyState> (priorReplyState);
+ state.foxFrequency = 321;
+ ReplyInput input;
+ input.protocol = static_cast<Protocol> (protocol);
+ input.tune = tune;
+ input.autoEnabled = autoEnabled;
+ input.sentReport = -17;
+ input.decodedFoxFrequency = 654;
+ input.trPeriod = 15.0;
+
+ auto const plan = HoundTransmissionPolicy::planFoxReportReply (state, input);
+ QCOMPARE (plan.applyReply, applyReply);
+ QCOMPARE (plan.enableAuto, enableAuto);
+ QCOMPARE (int (plan.frequencyDecision.action), frequencyAction);
+ QCOMPARE (int (plan.nextState.replyState), nextReplyState);
+ QCOMPARE (plan.nextState.foxFrequency, 654);
+ if (applyReply)
+ {
+ QCOMPARE (int (plan.txMessage), int (TxMessage::Tx3));
+ QCOMPARE (plan.report, -17);
+ QCOMPARE (plan.timeoutMilliseconds, 165000);
+ if (FrequencyAction::Set == plan.frequencyDecision.action)
+ {
+ QCOMPARE (plan.frequencyDecision.frequency, 654);
+ }
+ }
+ else
+ {
+ QCOMPARE (int (plan.txMessage), int (TxMessage::None));
+ QCOMPARE (plan.timeoutMilliseconds, 0);
+ }
+}
+
+void TestHoundTransmissionPolicy::planInitialCallingFrequency_data ()
+{
+ using namespace HoundTransmissionPolicy;
+ QTest::addColumn<bool> ("autoEnabled");
+ QTest::addColumn<bool> ("tune");
+ QTest::addColumn<int> ("selectedTxMessage");
+ QTest::addColumn<int> ("currentTxFrequency");
+ QTest::addColumn<int> ("frequencyAction");
+
+ QTest::newRow ("eligible at 998 Hz") << true << false << 1 << 998
+ << int (FrequencyAction::RandomizeCalling);
+ QTest::newRow ("Auto off") << false << false << 1 << 998 << int (FrequencyAction::Keep);
+ QTest::newRow ("Tune") << true << true << 1 << 998 << int (FrequencyAction::Keep);
+ QTest::newRow ("Tx3") << true << false << 3 << 998 << int (FrequencyAction::Keep);
+ QTest::newRow ("999 Hz") << true << false << 1 << 999 << int (FrequencyAction::Keep);
+}
+
+void TestHoundTransmissionPolicy::planInitialCallingFrequency ()
+{
+ QFETCH (bool, autoEnabled);
+ QFETCH (bool, tune);
+ QFETCH (int, selectedTxMessage);
+ QFETCH (int, currentTxFrequency);
+ QFETCH (int, frequencyAction);
+
+ using namespace HoundTransmissionPolicy;
+ ClassicTxStartInput input;
+ input.autoEnabled = autoEnabled;
+ input.tune = tune;
+ input.selectedTxMessage = selectedTxMessage;
+ input.currentTxFrequency = currentTxFrequency;
+ auto const plan = planClassicTxStart (State {}, input);
+ QCOMPARE (int (plan.frequencyDecision.action), frequencyAction);
+}
+
+void TestHoundTransmissionPolicy::planReplyTransmission_data ()
+{
+ QTest::addColumn<int> ("replyState");
+ QTest::addColumn<int> ("foxFrequency");
+ QTest::addColumn<int> ("selectedTxMessage");
+ QTest::addColumn<bool> ("tune");
+ QTest::addColumn<int> ("frequencyAction");
+ QTest::addColumn<int> ("frequency");
+ QTest::addColumn<int> ("nextReplyState");
+
+ using namespace HoundTransmissionPolicy;
+ QTest::newRow ("first reply") << int (ReplyState::FirstReplyPending) << 600 << 3 << false
+ << int (FrequencyAction::Keep) << 0 << int (ReplyState::FirstReplySent);
+ QTest::newRow ("retry at 600 Hz") << int (ReplyState::FirstReplySent) << 600 << 3 << false
+ << int (FrequencyAction::Set) << 900 << int (ReplyState::FirstReplySent);
+ QTest::newRow ("retry at 601 Hz") << int (ReplyState::FirstReplySent) << 601 << 3 << false
+ << int (FrequencyAction::Set) << 301 << int (ReplyState::FirstReplySent);
+ QTest::newRow ("non-Tx3 retry") << int (ReplyState::FirstReplySent) << 600 << 2 << false
+ << int (FrequencyAction::Keep) << 0 << int (ReplyState::FirstReplySent);
+ QTest::newRow ("Tune retry") << int (ReplyState::FirstReplySent) << 600 << 3 << true
+ << int (FrequencyAction::Set) << 900 << int (ReplyState::FirstReplySent);
+ QTest::newRow ("non-Tx3 advances pending") << int (ReplyState::FirstReplyPending) << 600 << 2 << true
+ << int (FrequencyAction::Keep) << 0 << int (ReplyState::FirstReplySent);
+}
+
+void TestHoundTransmissionPolicy::planReplyTransmission ()
+{
+ QFETCH (int, replyState);
+ QFETCH (int, foxFrequency);
+ QFETCH (int, selectedTxMessage);
+ QFETCH (bool, tune);
+ QFETCH (int, frequencyAction);
+ QFETCH (int, frequency);
+ QFETCH (int, nextReplyState);
+
+ using namespace HoundTransmissionPolicy;
+ State state;
+ state.replyState = static_cast<ReplyState> (replyState);
+ state.foxFrequency = foxFrequency;
+ ClassicTxStartInput input;
+ input.autoEnabled = true;
+ input.tune = tune;
+ input.selectedTxMessage = selectedTxMessage;
+ input.currentTxFrequency = 1500;
+
+ auto const plan = planClassicTxStart (state, input);
+ QCOMPARE (int (plan.frequencyDecision.action), frequencyAction);
+ QCOMPARE (plan.frequencyDecision.frequency, frequency);
+ QCOMPARE (int (plan.nextState.replyState), nextReplyState);
+ QCOMPARE (plan.nextState.foxFrequency, foxFrequency);
+}
+
+QTEST_GUILESS_MAIN (TestHoundTransmissionPolicy)
+
+#include "test_hound_transmission_policy.moc"
diff --git a/tests/unit/common/test_http_user_agent.cpp b/tests/unit/common/test_http_user_agent.cpp
new file mode 100644
index 00000000..6539f8c0
--- /dev/null
+++ b/tests/unit/common/test_http_user_agent.cpp
@@ -0,0 +1,53 @@
+#include <QtTest>
+
+#include "revision_utils.hpp"
+
+class TestHttpUserAgent final
+ : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ void labelsDisplayRevision ()
+ {
+ auto const display = display_revision ();
+ auto const build_revision = revision ();
+
+ if (build_revision.isEmpty ())
+ {
+ QVERIFY (display == "(revision unavailable)"
+ || display.contains (", build unavailable)"));
+ }
+ else if (display.startsWith ("(source "))
+ {
+ QVERIFY (display.endsWith (", build " + build_revision + ")"));
+ }
+ else
+ {
+ QCOMPARE (display, "(revision " + build_revision + ")");
+ }
+ }
+
+ void includesApplicationIdentityAndPlatformContext ()
+ {
+ auto const user_agent = http_user_agent ();
+
+ QVERIFY (user_agent.startsWith ("WSJT-X/"));
+ QVERIFY (user_agent.contains (version ()));
+
+ auto const build_revision = revision ();
+ if (!build_revision.isEmpty ())
+ {
+ QVERIFY (user_agent.contains ("_" + build_revision));
+ }
+
+ QVERIFY (user_agent.contains ('('));
+ QVERIFY (user_agent.contains (')'));
+ QVERIFY (!user_agent.contains ('\n'));
+ QVERIFY (!user_agent.contains ('\r'));
+ }
+};
+
+QTEST_GUILESS_MAIN (TestHttpUserAgent)
+
+#include "test_http_user_agent.moc"
diff --git a/tests/unit/common/test_livecq_callsign.cpp b/tests/unit/common/test_livecq_callsign.cpp
new file mode 100644
index 00000000..24d81939
--- /dev/null
+++ b/tests/unit/common/test_livecq_callsign.cpp
@@ -0,0 +1,39 @@
+#include <QtTest>
+
+#include "validators/LiveCQCallsign.hpp"
+
+class TestLiveCQCallsign final : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void acceptsThreeCharacterCalls()
+ {
+ QVERIFY(LiveCQ::isValidCallsign("N5L"));
+ QVERIFY(LiveCQ::isValidCallsign("K1A"));
+ QVERIFY(LiveCQ::isValidCallsign("GM/N5L"));
+ }
+
+ void preservesExistingValidCalls()
+ {
+ for (auto const& callsign : {QString {"K1ABC"}, QString {"YW18FIFA"},
+ QString {"QU1RK"}, QString {"<K1ABC>"},
+ QString {"K1ABC/P"}}) {
+ QVERIFY2(LiveCQ::isValidCallsign(callsign), qPrintable(callsign));
+ }
+ }
+
+ void rejectsEmptyShortAndInvalidCalls()
+ {
+ for (auto const& callsign : {QString {}, QString {"N"}, QString {"N5"},
+ QString {"KABC"}, QString {"Q1ABC"},
+ QString {"K1AB1"}, QString {"K1ABCDE"},
+ QString {"K1AB-C"}, QString {"K1AB?"}}) {
+ QVERIFY2(!LiveCQ::isValidCallsign(callsign), qPrintable(callsign));
+ }
+ }
+};
+
+QTEST_APPLESS_MAIN(TestLiveCQCallsign)
+
+#include "test_livecq_callsign.moc"
diff --git a/tests/unit/common/test_mainwindow_compact_controls.cpp b/tests/unit/common/test_mainwindow_compact_controls.cpp
new file mode 100644
index 00000000..a3a99fa5
--- /dev/null
+++ b/tests/unit/common/test_mainwindow_compact_controls.cpp
@@ -0,0 +1,114 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include <QApplication>
+#include <QImage>
+#include <QPainter>
+#include <QVBoxLayout>
+#include <QTest>
+#include "widgets/CompactButtonSize.hpp"
+#include "widgets/CurrentPageHeightStackedWidget.hpp"
+#include "widgets/TxDriveSlider.hpp"
+
+class CompactControlsTest : public QObject
+{
+ Q_OBJECT
+private Q_SLOTS:
+ void currentStackPageHeight ()
+ {
+ CurrentPageHeightStackedWidget stack;
+ auto makePage = [&stack] (int rows)
+ {
+ auto * page = new QWidget {&stack};
+ auto * layout = new QVBoxLayout {page};
+ for (int row = 0; row < rows; ++row)
+ layout->addWidget (new QPushButton {QString::number (row), page});
+ return page;
+ };
+ auto * shortPage = makePage (2);
+ auto * tallPage = makePage (6);
+ stack.addWidget (shortPage);
+ stack.addWidget (tallPage);
+ stack.ensurePolished ();
+
+ stack.setCurrentWidget (shortPage);
+ QCOMPARE (stack.sizeHint ().height (), shortPage->sizeHint ().height ());
+ QVERIFY (stack.sizeHint ().height () < tallPage->sizeHint ().height ());
+
+ stack.setCurrentWidget (tallPage);
+ QCOMPARE (stack.sizeHint ().height (), tallPage->sizeHint ().height ());
+ }
+
+ void nativeSlider ()
+ {
+#ifndef Q_OS_WIN
+ QSKIP ("Native Windows slider contract");
+#else
+ for (int width : {27, 44})
+ for (int value : {0, 225, 450})
+ {
+ TxDriveSlider actual;
+ QSlider reference;
+ reference.setTickPosition (QSlider::TicksRight);
+ reference.setTickInterval (50);
+ for (auto * slider : {static_cast<QSlider *> (&actual), &reference})
+ {
+ slider->setOrientation (Qt::Vertical);
+ slider->setRange (0, 450);
+ slider->setInvertedAppearance (true);
+ slider->setValue (value);
+ slider->resize (width, 200);
+ slider->ensurePolished ();
+ }
+ QCOMPARE (actual.tickPosition (), reference.tickPosition ());
+ QCOMPARE (actual.sizeHint (), reference.sizeHint ());
+ QCOMPARE (actual.minimumSizeHint (), reference.minimumSizeHint ());
+ QCOMPARE (actual.grab ().toImage (), reference.grab ().toImage ());
+ }
+#endif
+ }
+ void compactButtons ()
+ {
+#if defined (Q_OS_WIN)
+ auto const families = {QStringLiteral ("Arial"), QStringLiteral ("Segoe UI")};
+#elif defined (Q_OS_LINUX)
+ auto const families = {QStringLiteral ("DejaVu Sans"), QStringLiteral ("Liberation Sans")};
+#else
+ QSKIP ("Compact Windows and Linux button contract");
+#endif
+#if defined (Q_OS_WIN) || defined (Q_OS_LINUX)
+ for (auto const& family : families)
+ for (int points : {8, 10, 13, 16})
+ {
+ QPushButton button {QStringLiteral ("Tx &1")};
+ button.setFont (QFont {family, points});
+ button.ensurePolished ();
+ auto shortSize = compactButtonSize (&button);
+ QVERIFY (shortSize.width () < button.sizeHint ().width ());
+ button.resize (shortSize);
+ QStyleOptionButton option;
+ option.initFrom (&button);
+ auto contents = button.style ()->subElementRect (QStyle::SE_PushButtonContents, &option, &button);
+ auto text = button.fontMetrics ().size (Qt::TextShowMnemonic, button.text ());
+ QVERIFY (contents.width () >= text.width ());
+ QVERIFY (contents.height () >= text.height ());
+ for (auto const& label : {QStringLiteral ("&Lookup"),
+ QStringLiteral ("Add"),
+ QStringLiteral ("Ignore")})
+ {
+ button.setText (label);
+ button.resize (compactButtonSize (&button));
+ option.initFrom (&button);
+ contents = button.style ()->subElementRect (
+ QStyle::SE_PushButtonContents, &option, &button);
+ text = button.fontMetrics ().size (
+ Qt::TextShowMnemonic, button.text ());
+ QVERIFY (contents.width () >= text.width ());
+ QVERIFY (contents.height () >= text.height ());
+ }
+ button.setText (QStringLiteral ("Translated action label"));
+ QVERIFY (compactButtonSize (&button).width () > shortSize.width ());
+ }
+#endif
+ }
+};
+QTEST_MAIN (CompactControlsTest)
+#include "test_mainwindow_compact_controls.moc"
diff --git a/tests/unit/common/test_operating_frequency.cpp b/tests/unit/common/test_operating_frequency.cpp
new file mode 100644
index 00000000..6564027f
--- /dev/null
+++ b/tests/unit/common/test_operating_frequency.cpp
@@ -0,0 +1,211 @@
+#include <QtTest>
+#include "OperatingFrequency.hpp"
+
+namespace
+{
+ using Owner = OperatingFrequency;
+ constexpr Radio::Frequency rf = 10368200000ULL;
+ constexpr Radio::Frequency intermediate = 144200000;
+ Owner::Observation offline {false, false, false, 0, 0};
+ Owner::Observation initial {true, false, false, intermediate, 0};
+ Owner::Context automatic {false, true, true, true, false, 0, 0};
+ struct Recorder
+ {
+ QVector<Radio::Frequency> commands;
+ bool accepted = true;
+ bool operator() (Radio::Frequency value)
+ {
+ commands.append (value);
+ return accepted;
+ }
+ };
+}
+
+class TestOperatingFrequency : public QObject
+{
+ Q_OBJECT
+private slots:
+ void startupAndDoppler_data ()
+ {
+ QTest::addColumn<bool> ("responseFirst");
+ QTest::addColumn<qint64> ("initialCorrection");
+ QTest::newRow ("correction-before-response") << false << qint64 (0);
+ QTest::newRow ("response-before-correction") << true << qint64 (0);
+ QTest::newRow ("nonzero-correction-before-response") << false << qint64 (125);
+ QTest::newRow ("nonzero-response-before-correction") << true << qint64 (125);
+ }
+
+ void startupAndDoppler ()
+ {
+ QFETCH (bool, responseFirst);
+ QFETCH (qint64, initialCorrection);
+ Owner frequency {rf};
+ Recorder requests;
+ auto context = automatic;
+ context.rxCorrection = initialCorrection;
+ context.txCorrection = -50;
+ auto const transition = frequency.reconcile (offline, initial, context, std::ref (requests));
+ QVERIFY (transition.restorationAccepted);
+ QVERIFY (transition.monitor && *transition.monitor);
+ QCOMPARE (transition.before.rx, 0ULL);
+ QCOMPARE (transition.after.rx, rf);
+ QCOMPARE (transition.after.tx, rf);
+ QCOMPARE (transition.after.remembered, rf);
+ QCOMPARE (requests.commands, QVector<Radio::Frequency> {rf + initialCorrection});
+ context.monitoring = true;
+ Owner::Observation response {true, false, false, rf + initialCorrection, 0};
+ if (responseFirst)
+ frequency.reconcile (initial, response, context, std::ref (requests));
+ context.rxCorrection = 175;
+ requests (frequency.correctedRx (context.rxCorrection));
+ QCOMPARE (requests.commands.last (), rf + 175);
+ // Configuration forwards RF plus correction and filters superseded responses.
+ Owner::Observation corrected {true, false, false, rf + 175, 0};
+ frequency.reconcile (responseFirst ? response : initial, corrected, context, std::ref (requests));
+ QCOMPARE (frequency.rx (), rf);
+ QCOMPARE (frequency.tx (), rf);
+ QCOMPARE (frequency.remembered (), rf);
+ auto const count = requests.commands.size ();
+ frequency.reconcile (corrected, corrected, context, std::ref (requests));
+ QCOMPARE (requests.commands.size (), count);
+ corrected.rx += 1000;
+ frequency.reconcile (response, corrected, context, std::ref (requests));
+ QCOMPARE (frequency.rx (), rf + 1000);
+ QCOMPARE (frequency.remembered (), rf + 1000);
+ }
+
+ void manualMonitorPreservesSavedTarget ()
+ {
+ Owner frequency {rf};
+ Recorder requests;
+ auto context = automatic;
+ context.monitorAtStartup = false;
+ auto transition = frequency.reconcile (offline, initial, context, std::ref (requests));
+ QVERIFY (transition.monitor && !*transition.monitor);
+ QCOMPARE (frequency.rx (), intermediate);
+ QCOMPARE (frequency.tx (), intermediate);
+ QCOMPARE (frequency.remembered (), rf);
+ auto tuned = initial;
+ tuned.rx += 2000;
+ frequency.reconcile (initial, tuned, context, std::ref (requests));
+ QCOMPARE (frequency.rx (), tuned.rx);
+ QCOMPARE (frequency.remembered (), rf);
+ transition = frequency.enableMonitor (context, std::ref (requests));
+ QVERIFY (transition.restorationAccepted);
+ QCOMPARE (requests.commands, QVector<Radio::Frequency> {rf});
+ QCOMPARE (frequency.rx (), rf);
+ QCOMPARE (frequency.remembered (), rf);
+ }
+
+ void restorationEligibility_data ()
+ {
+ QTest::addColumn<bool> ("restore");
+ QTest::addColumn<bool> ("echo");
+ QTest::addColumn<bool> ("allowed");
+ QTest::newRow ("disabled") << false << false << true;
+ QTest::newRow ("echo") << true << true << true;
+ QTest::newRow ("monitor-blocked") << true << false << false;
+ }
+
+ void restorationEligibility ()
+ {
+ QFETCH (bool, restore);
+ QFETCH (bool, echo);
+ QFETCH (bool, allowed);
+ Owner frequency {rf};
+ Recorder requests;
+ auto context = automatic;
+ context.restore = restore;
+ context.echo = echo;
+ context.monitorAllowed = allowed;
+ auto transition = frequency.reconcile (offline, initial, context, std::ref (requests));
+ QVERIFY (!transition.restorationAccepted);
+ QVERIFY (requests.commands.isEmpty ());
+ QCOMPARE (frequency.rx (), intermediate);
+ QCOMPARE (frequency.remembered (), !restore && allowed && !echo ? intermediate : rf);
+ frequency.enableMonitor (context, std::ref (requests));
+ QVERIFY (requests.commands.isEmpty ());
+ }
+
+ void rejectionAndReconnect ()
+ {
+ Owner frequency {rf};
+ Recorder requests;
+ requests.accepted = false;
+ auto context = automatic;
+ auto transition = frequency.reconcile (offline, initial, context, std::ref (requests));
+ QVERIFY (!transition.restorationAccepted);
+ QCOMPARE (frequency.rx (), intermediate);
+ QCOMPARE (frequency.tx (), intermediate);
+ QCOMPARE (frequency.remembered (), rf);
+ context.monitoring = true;
+ frequency.reconcile (initial, initial, context, std::ref (requests));
+ frequency.reconcile (initial, offline, context, std::ref (requests));
+ QCOMPARE (frequency.rx (), intermediate);
+ QCOMPARE (frequency.remembered (), rf);
+ Owner::Observation zero {true, false, false, 0, 0};
+ frequency.reconcile (initial, zero, context, std::ref (requests));
+ QCOMPARE (frequency.remembered (), rf);
+ // A reconnect while already monitoring is not a new Monitor activation.
+ frequency.reconcile (offline, initial, context, std::ref (requests));
+ QCOMPARE (requests.commands.size (), 1);
+ QCOMPARE (frequency.remembered (), rf);
+ context.monitoring = false;
+ requests.accepted = true;
+ transition = frequency.reconcile (offline, initial, context, std::ref (requests));
+ QVERIFY (transition.restorationAccepted);
+ QCOMPARE (requests.commands.size (), 2);
+ QCOMPARE (frequency.rx (), rf);
+ QCOMPARE (frequency.remembered (), rf);
+ }
+
+ void acceptedRequestsAndTxReports ()
+ {
+ Owner frequency {rf};
+ Recorder requests;
+ auto const* stableRx = &frequency.rx ();
+ QVERIFY (frequency.requestNominal (intermediate, 125, std::ref (requests)));
+ QCOMPARE (requests.commands.last (), intermediate + 125);
+ QCOMPARE (*stableRx, intermediate);
+ QCOMPARE (frequency.tx (), intermediate);
+ requests.accepted = false;
+ QVERIFY (!frequency.requestNominal (432200000, 0, std::ref (requests)));
+ QCOMPARE (frequency.rx (), intermediate);
+ QCOMPARE (frequency.tx (), intermediate);
+ QCOMPARE (frequency.remembered (), rf);
+ QVERIFY (!frequency.requestNominal (0, 0, std::ref (requests)));
+ auto context = automatic;
+ context.monitoring = true;
+ context.rxCorrection = 125;
+ context.txCorrection = 50;
+ Owner::Observation rx {true, false, false, 432200125, 0};
+ frequency.reconcile (initial, rx, context, std::ref (requests));
+ QCOMPARE (frequency.rx (), 432200000ULL);
+ QCOMPARE (frequency.remembered (), 432200000ULL);
+ Owner::Observation split {true, true, true, 432200125, 432201050};
+ frequency.reconcile (rx, split, context, std::ref (requests));
+ QCOMPARE (frequency.tx (), 432201000ULL);
+ QCOMPARE (frequency.rx (), 432200000ULL);
+ auto changedTx = split;
+ changedTx.tx += 500;
+ frequency.reconcile (split, changedTx, context, std::ref (requests));
+ QCOMPARE (frequency.tx (), 432201500ULL);
+ Owner::Observation simplex {true, true, false, 432202000, 0};
+ frequency.reconcile (split, simplex, context, std::ref (requests));
+ QCOMPARE (frequency.tx (), 432202000ULL);
+ auto adjustTx = [&] (Radio::Frequency nominal) {
+ if (!requests (nominal + context.txCorrection)) return false;
+ frequency.commitAcceptedTx (nominal);
+ return true;
+ };
+ QVERIFY (!adjustTx (432203000));
+ QCOMPARE (frequency.tx (), 432202000ULL);
+ requests.accepted = true;
+ QVERIFY (adjustTx (432203000));
+ QCOMPARE (frequency.correctedTx (-25), 432202975ULL);
+ QCOMPARE (frequency.rx (), 432200000ULL);
+ }
+};
+
+QTEST_GUILESS_MAIN (TestOperatingFrequency)
+#include "test_operating_frequency.moc"
diff --git a/tests/unit/common/test_qso_reaction.cpp b/tests/unit/common/test_qso_reaction.cpp
new file mode 100644
index 00000000..310bb68a
--- /dev/null
+++ b/tests/unit/common/test_qso_reaction.cpp
@@ -0,0 +1,712 @@
+#include <QtTest>
+
+#include "QsoReactionTestSupport.hpp"
+
+namespace
+{
+ using namespace QsoReactionTestSupport;
+
+ Snapshot baseSnapshot()
+ {
+ auto snapshot = neutralStationSnapshot();
+ snapshot.mode = "FT8";
+ snapshot.tx1Enabled = true;
+ return snapshot;
+ }
+
+ struct FinalState
+ {
+ int txMessage;
+ QsoProgress progress;
+ };
+
+ FinalState finalState(Plan const& plan, Snapshot const& snapshot)
+ {
+ FinalState state {snapshot.selectedTxMessage, snapshot.qsoProgress};
+ for (auto const& effect : plan.effects) {
+ if (effect.kind == Effect::Kind::SetTxMessage
+ || effect.kind == Effect::Kind::SetTxMessageIndex
+ || effect.kind == Effect::Kind::CheckTxMessage
+ || effect.kind == Effect::Kind::ClickTxMessage) {
+ state.txMessage = effect.intValue;
+ } else if (effect.kind == Effect::Kind::SetQsoProgress) {
+ state.progress = effect.progress;
+ }
+ }
+ return state;
+ }
+}
+
+class TestQsoReaction final
+ : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void qsoProgressValuesMatchDecoderContract()
+ {
+ QCOMPARE(static_cast<int>(QsoProgress::Calling), 0);
+ QCOMPARE(static_cast<int>(QsoProgress::Replying), 1);
+ QCOMPARE(static_cast<int>(QsoProgress::Report), 2);
+ QCOMPARE(static_cast<int>(QsoProgress::RogerReport), 3);
+ QCOMPARE(static_cast<int>(QsoProgress::Rogers), 4);
+ QCOMPARE(static_cast<int>(QsoProgress::Signoff), 5);
+ }
+
+ void rrrAutoTxShutdownPolicy_data()
+ {
+ QTest::addColumn<QString>("mode");
+ QTest::addColumn<bool>("repeatTx");
+ QTest::addColumn<bool>("sendRr73");
+ QTest::addColumn<bool>("expectedDefer");
+
+ QTest::newRow("MSK144 RRR") << "MSK144" << false << false << true;
+ QTest::newRow("MSK144 RRR repeat") << "MSK144" << true << false << true;
+ QTest::newRow("MSK144 RR73 repeat") << "MSK144" << true << true << false;
+ QTest::newRow("Q65 RRR") << "Q65" << false << false << false;
+ QTest::newRow("Q65 RRR repeat") << "Q65" << true << false << true;
+ QTest::newRow("Q65 RR73 repeat") << "Q65" << true << true << false;
+ QTest::newRow("FT8 RRR") << "FT8" << true << false << false;
+ }
+
+ void rrrAutoTxShutdownPolicy()
+ {
+ QFETCH(QString, mode);
+ QFETCH(bool, repeatTx);
+ QFETCH(bool, sendRr73);
+ QFETCH(bool, expectedDefer);
+
+ QCOMPARE(DecodedMessageReaction::shouldDeferAutoTxStopAfterRrr(mode, repeatTx, sendRr73),
+ expectedDefer);
+
+ bool stopCalled {false};
+ DecodedMessageReaction::applyAutoTxStopAfterLogging(
+ mode, repeatTx, sendRr73, [&stopCalled] { stopCalled = true; });
+ QCOMPARE(stopCalled, !expectedDefer);
+ }
+
+ void q65Final73LoggingStopsAutoTxWhenRepeatIsDisabled()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "Q65";
+ snapshot.qsoProgress = QsoProgress::Rogers;
+ snapshot.loggingEnabled = true;
+ snapshot.repeatTx = false;
+ snapshot.sendRr73 = false;
+
+ auto const plan = DecodedMessageReaction::planProcessMessage(
+ decode("K1ABC W1AW 73", ":"), snapshot);
+
+ QVERIFY(hasEffect(plan, Effect::Kind::RequestLogQso));
+ QCOMPARE(intEffect(plan, Effect::Kind::SetTxMessageIndex), 6);
+ QVERIFY(!hasEffect(plan, Effect::Kind::ScheduleAutoFlagOff));
+ QVERIFY(!DecodedMessageReaction::shouldDeferAutoTxStopAfterRrr(
+ snapshot.mode, snapshot.repeatTx, snapshot.sendRr73));
+ }
+
+ void responseTransitions_data()
+ {
+ QTest::addColumn<int>("initialProgress");
+ QTest::addColumn<QString>("response");
+ QTest::addColumn<int>("expectedTxMessage");
+ QTest::addColumn<int>("expectedProgress");
+ QTest::addColumn<bool>("expectedReaction");
+
+ QStringList const responses {"FN31", "-10", "R", "R-10", "RRR", "RR73", "73"};
+ for (int initial = 0; initial <= 5; ++initial) {
+ for (auto const& response : responses) {
+ int tx = -1;
+ int progress = initial;
+ bool reacts = true;
+ if (response == "FN31") {
+ tx = 2;
+ progress = 2;
+ } else if (response == "-10") {
+ tx = 3;
+ progress = 3;
+ } else if (response == "R") {
+ tx = initial == 3 ? 5 : 4;
+ if (initial == 2) progress = 4;
+ else if (initial >= 3) progress = 5;
+ } else if (response == "R-10") {
+ tx = 4;
+ progress = 4;
+ } else if (response == "RRR" || response == "RR73") {
+ tx = 5;
+ if (initial >= 3) progress = 5;
+ } else if (initial == 4) {
+ tx = 6;
+ progress = 5;
+ } else {
+ tx = 0;
+ }
+ QByteArray const name = QByteArray::number(initial) + '-' + response.toLatin1();
+ QTest::newRow(name.constData()) << initial << response << tx << progress << reacts;
+ }
+ }
+ }
+
+ void responseTransitions()
+ {
+ QFETCH(int, initialProgress);
+ QFETCH(QString, response);
+ QFETCH(int, expectedTxMessage);
+ QFETCH(int, expectedProgress);
+ QFETCH(bool, expectedReaction);
+
+ auto snapshot = baseSnapshot();
+ snapshot.qsoProgress = static_cast<QsoProgress>(initialProgress);
+ QString const payload = response == "R"
+ ? "<K1ABC> W1AW R" : "K1ABC W1AW " + response;
+ auto const plan = DecodedMessageReaction::planProcessMessage(decode(payload), snapshot);
+
+ QCOMPARE(plan.disposition == DecodedMessageReaction::ReactionDisposition::Reacted,
+ expectedReaction);
+ if (expectedReaction) {
+ auto const state = finalState(plan, snapshot);
+ QCOMPARE(state.txMessage, expectedTxMessage);
+ QCOMPARE(static_cast<int>(state.progress), expectedProgress);
+ }
+ }
+
+ void tx1AvailabilityControlsFallback_data()
+ {
+ QTest::addColumn<bool>("tx1Enabled");
+ QTest::addColumn<int>("expectedTxMessage");
+ QTest::addColumn<int>("expectedProgress");
+ QTest::newRow("tx1") << true << 1 << 1;
+ QTest::newRow("tx2-fallback") << false << 2 << 2;
+ }
+
+ void tx1AvailabilityControlsFallback()
+ {
+ QFETCH(bool, tx1Enabled);
+ QFETCH(int, expectedTxMessage);
+ QFETCH(int, expectedProgress);
+ auto snapshot = baseSnapshot();
+ snapshot.tx1Enabled = tx1Enabled;
+ snapshot.dxCall.clear();
+ snapshot.hisCall.clear();
+
+ auto const plan = DecodedMessageReaction::planProcessMessage(decode("CQ W1AW FN31"), snapshot);
+ auto const state = finalState(plan, snapshot);
+ QCOMPARE(state.txMessage, expectedTxMessage);
+ QCOMPARE(static_cast<int>(state.progress), expectedProgress);
+ }
+
+ void signoffLogsOrCeasesAuto_data()
+ {
+ QTest::addColumn<bool>("loggingEnabled");
+ QTest::addColumn<int>("expectedEffect");
+ QTest::newRow("log") << true << static_cast<int>(Effect::Kind::RequestLogQso);
+ QTest::newRow("cease") << false << static_cast<int>(Effect::Kind::CeaseAutoTx);
+ }
+
+ void signoffLogsOrCeasesAuto()
+ {
+ QFETCH(bool, loggingEnabled);
+ QFETCH(int, expectedEffect);
+ auto snapshot = baseSnapshot();
+ snapshot.qsoProgress = QsoProgress::Rogers;
+ snapshot.loggingEnabled = loggingEnabled;
+
+ auto const plan = DecodedMessageReaction::planProcessMessage(decode("K1ABC W1AW 73"), snapshot);
+ QVERIFY(effectIndex(plan, static_cast<Effect::Kind>(expectedEffect)) >= 0);
+ }
+
+ void sharedTailRequestsRestartQuickCallAndRegeneration()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.doubleClicked = true;
+ snapshot.selectionOrigin = DecodedMessageReaction::SelectionOrigin::ManualLeftPane;
+ snapshot.quickCall = true;
+ snapshot.transmitting = true;
+
+ auto const plan = DecodedMessageReaction::planProcessMessage(decode("K1ABC W1AW -10"), snapshot);
+
+ QVERIFY(effectIndex(plan, Effect::Kind::SetReport) >= 0);
+ QVERIFY(effectIndex(plan, Effect::Kind::GenerateStandardMessages) >= 0);
+ QVERIFY(effectIndex(plan, Effect::Kind::SetRestart) >= 0);
+ QVERIFY(effectIndex(plan, Effect::Kind::SetAutoEnabled) >= 0);
+ }
+
+ void jt65OooSelectsRogerReport()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "JT65";
+ auto const plan = DecodedMessageReaction::planProcessMessage(
+ decode("K1ABC W1AW FN31 OOO", "#"), snapshot);
+ auto const state = finalState(plan, snapshot);
+ QCOMPARE(state.txMessage, 3);
+ QCOMPARE(state.progress, QsoProgress::RogerReport);
+ }
+
+ void dualFoxMessagePreservesCurrentDisposition()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.loggingEnabled = true;
+ auto const message = decode("K1ABC RR73; W2XX W1AW -10");
+ auto const plan = DecodedMessageReaction::planProcessMessage(message, snapshot);
+ QCOMPARE(message.messageWords().size(), 7);
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QVERIFY(effectIndex(plan, Effect::Kind::RequestLogQso) < 0);
+ }
+
+ void freeTextSignoffSelectsTx5()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.qsoProgress = QsoProgress::RogerReport;
+ auto const plan = DecodedMessageReaction::planProcessMessage(decode("TNX QSO 73"), snapshot);
+ auto const state = finalState(plan, snapshot);
+ QCOMPARE(state.txMessage, 5);
+ QCOMPARE(state.progress, QsoProgress::Signoff);
+ int const select = effectIndex(plan, Effect::Kind::SetTxMessageIndex);
+ int const check = effectIndex(plan, Effect::Kind::CheckTxMessage, select + 1);
+ int const progress = effectIndex(plan, Effect::Kind::SetQsoProgress, check + 1);
+ QVERIFY(select >= 0 && check > select && progress > check);
+ }
+
+ void repeatTxUsesClickableTx5AndLiveAutoTimer()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "Q65";
+ snapshot.qsoProgress = QsoProgress::Rogers;
+ snapshot.repeatTx = true;
+ auto const plan = DecodedMessageReaction::planProcessMessage(
+ decode("K1ABC W1AW 73", ":"), snapshot);
+ QCOMPARE(intEffect(plan, Effect::Kind::ClickTxMessage), 5);
+ QCOMPARE(intEffect(plan, Effect::Kind::ScheduleAutoFlagOff), 15000);
+ }
+
+ void contestGridPolicies_data()
+ {
+ QTest::addColumn<int>("specOp");
+ QTest::addColumn<QString>("mode");
+ QTest::addColumn<QString>("marker");
+ QTest::addColumn<int>("expectedTx");
+ QTest::addColumn<int>("expectedProgress");
+ QTest::newRow("normal") << int(SpecialOperatingActivity::NONE) << "FT8" << "~" << 2 << 2;
+ QTest::newRow("na-vhf") << int(SpecialOperatingActivity::NA_VHF) << "FT8" << "~" << 3 << 3;
+ QTest::newRow("ww-digi") << int(SpecialOperatingActivity::WW_DIGI) << "FT8" << "~" << 3 << 3;
+ QTest::newRow("arrl-digi") << int(SpecialOperatingActivity::ARRL_DIGI) << "FT8" << "~" << 3 << 3;
+ QTest::newRow("q65-pileup") << int(SpecialOperatingActivity::Q65_PILEUP) << "Q65" << ":" << 3 << 3;
+ }
+
+ void contestGridPolicies()
+ {
+ QFETCH(int, specOp);
+ QFETCH(QString, mode);
+ QFETCH(QString, marker);
+ QFETCH(int, expectedTx);
+ QFETCH(int, expectedProgress);
+ auto snapshot = baseSnapshot();
+ snapshot.specOp = static_cast<SpecialOperatingActivity>(specOp);
+ snapshot.mode = mode;
+ auto const state = finalState(
+ DecodedMessageReaction::planProcessMessage(decode("K1ABC W1AW FN31", marker), snapshot),
+ snapshot);
+ QCOMPARE(state.txMessage, expectedTx);
+ QCOMPARE(static_cast<int>(state.progress), expectedProgress);
+ }
+
+ void contestExchangePolicies()
+ {
+ auto eu = baseSnapshot();
+ eu.specOp = SpecialOperatingActivity::EU_VHF;
+ auto euPlan = DecodedMessageReaction::planProcessMessage(
+ decode("<K1ABC> W1AW 520001 FN31"), eu);
+ QCOMPARE(finalState(euPlan, eu).progress, QsoProgress::RogerReport);
+
+ auto rtty = baseSnapshot();
+ rtty.specOp = SpecialOperatingActivity::RTTY;
+ auto rttyPlan = DecodedMessageReaction::planProcessMessage(
+ decode("K1ABC W1AW 599 0001"), rtty);
+ QCOMPARE(finalState(rttyPlan, rtty).progress, QsoProgress::RogerReport);
+ QVERIFY(effectIndex(rttyPlan, Effect::Kind::SetReceivedExchange) >= 0);
+
+ auto fieldDay = baseSnapshot();
+ fieldDay.specOp = SpecialOperatingActivity::FIELD_DAY;
+ auto fieldDayPlan = DecodedMessageReaction::planProcessMessage(
+ decode("K1ABC W1AW R 1D EMA"), fieldDay);
+ QCOMPARE(finalState(fieldDayPlan, fieldDay).progress, QsoProgress::Rogers);
+ }
+
+ void euVhfReportBoundaries_data()
+ {
+ QTest::addColumn<int>("exchange");
+ QTest::addColumn<bool>("valid");
+ QTest::newRow("below-report") << 510001 << false;
+ QTest::newRow("lower") << 520001 << true;
+ QTest::newRow("upper") << 592047 << true;
+ QTest::newRow("above-serial") << 592048 << false;
+ }
+
+ void euVhfReportBoundaries()
+ {
+ QFETCH(int, exchange);
+ QFETCH(bool, valid);
+ auto snapshot = baseSnapshot();
+ snapshot.dxCall.clear();
+ snapshot.hisCall.clear();
+ auto const plan = DecodedMessageReaction::planProcessMessage(
+ decode(QString {"<K1ABC> W1AW %1 FN31"}.arg(exchange)), snapshot);
+ QCOMPARE(effectIndex(plan, Effect::Kind::QueueContestHint) >= 0, valid);
+ }
+
+ void contestHints_data()
+ {
+ QTest::addColumn<QString>("payload");
+ QTest::addColumn<int>("expectedHint");
+
+ QTest::newRow("eu-vhf")
+ << "<K1ABC> W1AW 520001 FN31" << int(DecodedMessageReaction::ContestHint::EuVhf);
+ QTest::newRow("field-day")
+ << "K1ABC W1AW R 1D EMA" << int(DecodedMessageReaction::ContestHint::FieldDay);
+ QTest::newRow("rtty")
+ << "K1ABC W1AW 599 0001" << int(DecodedMessageReaction::ContestHint::Rtty);
+ }
+
+ void contestHints()
+ {
+ QFETCH(QString, payload);
+ QFETCH(int, expectedHint);
+ auto snapshot = baseSnapshot();
+
+ auto const plan = DecodedMessageReaction::planProcessMessage(decode(payload), snapshot);
+
+ QCOMPARE(effectCount(plan, Effect::Kind::QueueContestHint), 1);
+ int const hint = effectIndex(plan, Effect::Kind::QueueContestHint);
+ QCOMPARE(int(plan.effects[hint].contestHint), expectedHint);
+ }
+
+ void shownContestHintSuppressesFurtherHints()
+ {
+ QStringList const payloads {
+ "<K1ABC> W1AW 520001 FN31",
+ "K1ABC W1AW R 1D EMA",
+ "K1ABC W1AW 599 0001"
+ };
+ auto snapshot = baseSnapshot();
+ snapshot.contestHintShown = true;
+
+ for (auto const& payload : payloads) {
+ auto const plan = DecodedMessageReaction::planProcessMessage(decode(payload), snapshot);
+ QCOMPARE(effectCount(plan, Effect::Kind::QueueContestHint), 0);
+ }
+ }
+
+ void fieldDayExchangePrecedesContestHint()
+ {
+ auto snapshot = baseSnapshot();
+
+ auto const plan = DecodedMessageReaction::planProcessMessage(
+ decode("K1ABC W1AW R 1D EMA"), snapshot);
+
+ int const exchange = effectIndex(plan, Effect::Kind::SetReceivedExchange);
+ int const hint = effectIndex(plan, Effect::Kind::QueueContestHint);
+ QVERIFY(exchange >= 0 && hint > exchange);
+ }
+
+ void msk144ReportNormalization_data()
+ {
+ QTest::addColumn<int>("input");
+ QTest::addColumn<int>("expected");
+ QTest::newRow("negative") << -2 << -3;
+ QTest::newRow("zero-low") << -1 << 0;
+ QTest::newRow("zero-high") << 1 << 0;
+ QTest::newRow("three-low") << 2 << 3;
+ QTest::newRow("three-high") << 4 << 3;
+ QTest::newRow("six-low") << 5 << 6;
+ QTest::newRow("six-high") << 7 << 6;
+ QTest::newRow("ten-low") << 8 << 10;
+ QTest::newRow("ten-high") << 11 << 10;
+ QTest::newRow("thirteen-low") << 12 << 13;
+ QTest::newRow("thirteen-high") << 14 << 13;
+ QTest::newRow("sixteen") << 15 << 16;
+ }
+
+ void msk144ReportNormalization()
+ {
+ QFETCH(int, input);
+ QFETCH(int, expected);
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "MSK144";
+ snapshot.shortMessages = true;
+ DecodedText const message {
+ QString {"060522 %1 0.3 1500 & K1ABC W1AW -10"}.arg(input, 3)};
+ auto const plan = DecodedMessageReaction::planProcessMessage(
+ message, snapshot);
+ QVERIFY2(plan.disposition == DecodedMessageReaction::ReactionDisposition::Reacted,
+ qPrintable(plan.reason));
+ QCOMPARE(intEffect(plan, Effect::Kind::SetReport), expected);
+ }
+
+ void selectionOrigins_data()
+ {
+ QTest::addColumn<int>("origin");
+ QTest::addColumn<bool>("transmittingSignoff");
+ QTest::addColumn<bool>("reacts");
+ QTest::newRow("manual") << int(DecodedMessageReaction::SelectionOrigin::ManualLeftPane) << true << true;
+ QTest::newRow("synthetic") << int(DecodedMessageReaction::SelectionOrigin::Synthetic) << true << true;
+ QTest::newRow("udp-guard") << int(DecodedMessageReaction::SelectionOrigin::Udp) << true << false;
+ }
+
+ void selectionOrigins()
+ {
+ QFETCH(int, origin);
+ QFETCH(bool, transmittingSignoff);
+ QFETCH(bool, reacts);
+ auto snapshot = baseSnapshot();
+ snapshot.doubleClicked = true;
+ snapshot.selectionOrigin = static_cast<DecodedMessageReaction::SelectionOrigin>(origin);
+ snapshot.transmittingSignoff = transmittingSignoff;
+ auto const plan = DecodedMessageReaction::planProcessMessage(
+ decode("K1ABC W1AW RR73"), snapshot);
+ QCOMPARE(plan.disposition == DecodedMessageReaction::ReactionDisposition::Reacted, reacts);
+ }
+
+ void slowWaitReplyOrderingAndTimeout()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.waitFeaturesEnabled = true;
+ auto const plan = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW -10"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::SlowDecoder);
+ int const watchdog = effectIndex(plan, Effect::Kind::ResetWatchdog);
+ int const selection = effectIndex(plan, Effect::Kind::SetDoubleClicked, watchdog + 1);
+ int const process = effectIndex(plan, Effect::Kind::ProcessSyntheticMessageNow, selection + 1);
+ int const enableAuto = effectIndex(plan, Effect::Kind::SetAutoEnabled, process + 1);
+ int const timer = effectIndex(plan, Effect::Kind::StartWaitReplyTimer, enableAuto + 1);
+ QVERIFY(watchdog >= 0 && selection > watchdog && process > selection
+ && enableAuto > process && timer > enableAuto);
+ QCOMPARE(plan.effects[timer].intValue, 120000);
+ }
+
+ void slowWaitReplyAndCallCanBothFire()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.waitFeaturesEnabled = true;
+ snapshot.waitAndCall = true;
+ snapshot.autoSequenceChecked = true;
+ auto const plan = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW CQ W1AW"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::SlowDecoder);
+ QCOMPARE(effectCount(plan, Effect::Kind::ProcessSyntheticMessageNow), 2);
+ int const replySelection = effectIndex(plan, Effect::Kind::SetDoubleClicked);
+ int const replyProcess = effectIndex(
+ plan, Effect::Kind::ProcessSyntheticMessageNow, replySelection + 1);
+ int const replyAuto = effectIndex(plan, Effect::Kind::SetAutoEnabled, replyProcess + 1);
+ int const callSelection = effectIndex(plan, Effect::Kind::SetDoubleClicked, replyAuto + 1);
+ int const callProcess = effectIndex(
+ plan, Effect::Kind::ProcessSyntheticMessageNow, callSelection + 1);
+ int const callAuto = effectIndex(plan, Effect::Kind::SetAutoEnabled, callProcess + 1);
+ QCOMPARE(replyProcess, replySelection + 1);
+ QCOMPARE(replyAuto, replyProcess + 1);
+ QCOMPARE(callProcess, callSelection + 1);
+ QCOMPARE(callAuto, callProcess + 1);
+ QCOMPARE(intEffect(plan, Effect::Kind::StartWaitCallTimer), 93000);
+ }
+
+ void slowHoundWrongSlotIgnoresDecode()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.specOp = SpecialOperatingActivity::HOUND;
+ snapshot.waitFeaturesEnabled = true;
+ auto const plan = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW -10", "~", "060515"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::SlowDecoder);
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::IgnoreDecode);
+ }
+
+ void msk144WaitPolicies()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "MSK144";
+ snapshot.waitFeaturesEnabled = true;
+ auto reply = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW -10", "&", "060522"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::Msk144FastDecoder);
+ QCOMPARE(intEffect(reply, Effect::Kind::StartWaitReplyTimer), 180000);
+
+ snapshot.specOp = SpecialOperatingActivity::HOUND;
+ auto houndReply = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW -10", "&", "060515"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::Msk144FastDecoder);
+ QCOMPARE(houndReply.disposition, DecodedMessageReaction::ReactionDisposition::Reacted);
+ snapshot.specOp = SpecialOperatingActivity::NONE;
+
+ snapshot.fullDuplexEnabled = true;
+ snapshot.txing = true;
+ auto blocked = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW -10", "&", "060522"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::Msk144FastDecoder);
+ QVERIFY(effectIndex(blocked, Effect::Kind::ProcessSyntheticMessageNow) < 0);
+
+ snapshot.fullDuplexEnabled = false;
+ snapshot.txing = false;
+ snapshot.waitAndCall = true;
+ snapshot.waitAndCallControlChecked = true;
+ snapshot.autoSequenceChecked = true;
+ auto cancelled = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW CQ W1AW", "&", "060522"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::Msk144FastDecoder);
+ QVERIFY(effectIndex(cancelled, Effect::Kind::StopWaitCallTimer) >= 0);
+ QVERIFY(effectIndex(cancelled, Effect::Kind::DisableWaitAndCallControl) >= 0);
+ QVERIFY(effectIndex(cancelled, Effect::Kind::StartWaitCallTimer) < 0);
+ }
+
+ void msk144WaitPolicyRequiresFastDecoderSource()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "MSK144";
+ snapshot.waitFeaturesEnabled = true;
+ snapshot.waitAndCall = true;
+ snapshot.waitAndCallControlChecked = true;
+ snapshot.autoSequenceChecked = true;
+ auto const message = decode("K1ABC W1AW CQ W1AW", "&", "060522");
+
+ auto const slowPlan = DecodedMessageReaction::planWaitReplyCall(
+ message, snapshot, DecodedMessageReaction::WaitDecodeSource::SlowDecoder);
+ QCOMPARE(slowPlan.disposition, DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QVERIFY(!hasEffect(slowPlan, Effect::Kind::StopWaitCallTimer));
+ QVERIFY(!hasEffect(slowPlan, Effect::Kind::DisableWaitAndCallControl));
+ QVERIFY(!hasEffect(slowPlan, Effect::Kind::ProcessSyntheticMessageNow));
+ QVERIFY(!hasEffect(slowPlan, Effect::Kind::SetAutoEnabled));
+ QVERIFY(!hasEffect(slowPlan, Effect::Kind::StartWaitReplyTimer));
+ QVERIFY(!hasEffect(slowPlan, Effect::Kind::StartWaitCallTimer));
+
+ auto const fastPlan = DecodedMessageReaction::planWaitReplyCall(
+ message, snapshot, DecodedMessageReaction::WaitDecodeSource::Msk144FastDecoder);
+ QVERIFY(hasEffect(fastPlan, Effect::Kind::StopWaitCallTimer));
+ QVERIFY(hasEffect(fastPlan, Effect::Kind::DisableWaitAndCallControl));
+ QVERIFY(hasEffect(fastPlan, Effect::Kind::ProcessSyntheticMessageNow));
+ QVERIFY(hasEffect(fastPlan, Effect::Kind::SetAutoEnabled));
+ QCOMPARE(intEffect(fastPlan, Effect::Kind::StartWaitReplyTimer), 180000);
+ QVERIFY(!hasEffect(fastPlan, Effect::Kind::StartWaitCallTimer));
+ }
+
+ void nonDirectWaitAndCallBlocksOnlySlowRightDisplay()
+ {
+ auto slowSnapshot = baseSnapshot();
+ slowSnapshot.waitFeaturesEnabled = true;
+ slowSnapshot.waitAndCall = true;
+ slowSnapshot.autoSequenceChecked = true;
+ auto const slowPlan = DecodedMessageReaction::planWaitReplyCall(
+ decode("CQ W1AW FN31"), slowSnapshot,
+ DecodedMessageReaction::WaitDecodeSource::SlowDecoder);
+ QVERIFY(hasEffect(slowPlan, Effect::Kind::SetBlockRightDisplay));
+
+ auto fastSnapshot = slowSnapshot;
+ fastSnapshot.mode = "MSK144";
+ auto const fastPlan = DecodedMessageReaction::planWaitReplyCall(
+ decode("CQ W1AW FN31", "&", "060522"), fastSnapshot,
+ DecodedMessageReaction::WaitDecodeSource::Msk144FastDecoder);
+ QVERIFY(hasEffect(fastPlan, Effect::Kind::ProcessSyntheticMessageNow));
+ QVERIFY(!hasEffect(fastPlan, Effect::Kind::SetBlockRightDisplay));
+ QCOMPARE(intEffect(fastPlan, Effect::Kind::StartWaitCallTimer), 93000);
+ }
+
+ void ncccSprintAvoidsDuplicateLogging()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "FT4";
+ snapshot.specOp = SpecialOperatingActivity::NA_VHF;
+ snapshot.ncccSprint = true;
+ snapshot.loggingEnabled = true;
+ auto const plan = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW R FN31", "+"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::SlowDecoder);
+ QCOMPARE(effectCount(plan, Effect::Kind::RequestLogQso), 1);
+ QCOMPARE(effectCount(plan, Effect::Kind::RequestLogQsoUnlessSuppressed), 1);
+ QCOMPARE(intEffect(plan, Effect::Kind::ScheduleStopTx), 500);
+ QVERIFY(effectIndex(plan, Effect::Kind::ProcessSyntheticMessageNow) >= 0);
+ }
+
+ void ncccReplyDefersLoggingSuppressionCheck()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.mode = "FT4";
+ snapshot.specOp = SpecialOperatingActivity::NA_VHF;
+ snapshot.ncccSprint = true;
+ snapshot.loggingEnabled = true;
+ auto const plan = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW -10", "+"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::SlowDecoder);
+
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::Reacted);
+ QCOMPARE(effectCount(plan, Effect::Kind::RequestLogQso), 0);
+ QCOMPARE(effectCount(plan, Effect::Kind::RequestLogQsoUnlessSuppressed), 1);
+ QVERIFY(effectIndex(plan, Effect::Kind::ProcessSyntheticMessageNow)
+ < effectIndex(plan, Effect::Kind::RequestLogQsoUnlessSuppressed));
+
+ snapshot.loggingEnabled = false;
+ auto const loggingDisabled = DecodedMessageReaction::planWaitReplyCall(
+ decode("K1ABC W1AW -10", "+"), snapshot,
+ DecodedMessageReaction::WaitDecodeSource::SlowDecoder);
+ QCOMPARE(effectCount(loggingDisabled, Effect::Kind::RequestLogQsoUnlessSuppressed), 1);
+ }
+
+ void representativeProcessEffectOrdering()
+ {
+ auto snapshot = baseSnapshot();
+ snapshot.qsoProgress = QsoProgress::Rogers;
+ snapshot.loggingEnabled = true;
+ auto const plan = DecodedMessageReaction::planProcessMessage(
+ decode("K1ABC W1AW 73"), snapshot);
+ int const log = effectIndex(plan, Effect::Kind::RequestLogQso);
+ int const select = effectIndex(plan, Effect::Kind::SetTxMessageIndex, log + 1);
+ int const check = effectIndex(plan, Effect::Kind::CheckTxMessage, select + 1);
+ int const progress = effectIndex(plan, Effect::Kind::SetQsoProgress, check + 1);
+ int const lookup = effectIndex(plan, Effect::Kind::Lookup, progress + 1);
+ int const generate = effectIndex(plan, Effect::Kind::GenerateStandardMessages, lookup + 1);
+ QVERIFY(log >= 0 && select > log && check > select && progress > check
+ && lookup > progress && generate > lookup);
+ }
+
+ void qsoPaneRefreshFollowsSelectionOrigin_data()
+ {
+ QTest::addColumn<int>("origin");
+ QTest::addColumn<bool>("expectedRefresh");
+
+ using Origin = DecodedMessageReaction::SelectionOrigin;
+ QTest::newRow("automatic") << int(Origin::None) << true;
+ QTest::newRow("manual-left-pane") << int(Origin::ManualLeftPane) << true;
+ QTest::newRow("manual-right-pane") << int(Origin::ManualRightPane) << false;
+ QTest::newRow("synthetic") << int(Origin::Synthetic) << true;
+ QTest::newRow("udp") << int(Origin::Udp) << true;
+ }
+
+ void qsoPaneRefreshFollowsSelectionOrigin()
+ {
+ QFETCH(int, origin);
+ QFETCH(bool, expectedRefresh);
+
+ auto snapshot = baseSnapshot();
+ snapshot.qsoProgress = QsoProgress::Rogers;
+ snapshot.loggingEnabled = true;
+ snapshot.selectionOrigin = static_cast<DecodedMessageReaction::SelectionOrigin>(origin);
+
+ auto const plan = DecodedMessageReaction::planProcessMessage(
+ decode("K1ABC W1AW 73"), snapshot);
+
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::Reacted);
+ QCOMPARE(finalState(plan, snapshot).progress, QsoProgress::Signoff);
+ QCOMPARE(effectCount(plan, Effect::Kind::RequestLogQso), 1);
+ QCOMPARE(effectCount(plan, Effect::Kind::GenerateStandardMessages), 1);
+ QCOMPARE(effectCount(plan, Effect::Kind::RefreshQsoPaneIfChanged),
+ expectedRefresh ? 1 : 0);
+ }
+
+ void earlyTxDecodeEffectsPrecedeRejection()
+ {
+ auto snapshot = baseSnapshot();
+ DecodedText message {"0605 Tx 1259 # CQ K1ABC FN42"};
+ auto const plan = DecodedMessageReaction::planProcessMessage(message, snapshot);
+ QCOMPARE(plan.disposition, DecodedMessageReaction::ReactionDisposition::NoReaction);
+ QCOMPARE(plan.effects.size(), 1);
+ QCOMPARE(plan.effects.first().kind, Effect::Kind::SetRxFrequency);
+ }
+};
+
+QTEST_MAIN(TestQsoReaction)
+#include "test_qso_reaction.moc"
diff --git a/tests/unit/common/test_qsy_message_parser.cpp b/tests/unit/common/test_qsy_message_parser.cpp
new file mode 100644
index 00000000..2fc2b12d
--- /dev/null
+++ b/tests/unit/common/test_qsy_message_parser.cpp
@@ -0,0 +1,316 @@
+#include <QTest>
+
+#include "widgets/QSYMessageParser.h"
+
+using QSYMessageParser::Type;
+using QSYMessageParser::Message;
+
+class TestQSYMessageParser final
+ : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void decode_frequency_data ()
+ {
+ QTest::addColumn<QString> ("payload");
+ QTest::addColumn<int> ("region");
+ QTest::addColumn<bool> ("valid");
+ QTest::addColumn<QString> ("frequency");
+ QTest::addColumn<QString> ("mode");
+
+ // every band prefix, exercised with a letter mode (-> FT8)
+ QTest::newRow ("band-A") << "AL123" << 2 << true << "50.123" << "FT8";
+ QTest::newRow ("band-B") << "BL123" << 2 << true << "144.123" << "FT8";
+ QTest::newRow ("band-C") << "CL123" << 2 << true << "222.123" << "FT8";
+ QTest::newRow ("band-D") << "DL123" << 2 << true << "432.123" << "FT8";
+ QTest::newRow ("band-E") << "EL123" << 2 << true << "1296.123" << "FT8";
+ QTest::newRow ("band-F") << "FL123" << 2 << true << "2304.123" << "FT8";
+ QTest::newRow ("band-G") << "GL123" << 2 << true << "3400.123" << "FT8";
+ QTest::newRow ("band-H") << "HL123" << 2 << true << "5760.123" << "FT8";
+ QTest::newRow ("band-I") << "IL123" << 2 << true << "10368.123" << "FT8";
+ QTest::newRow ("band-J-r2") << "JL123" << 2 << true << "24192.123" << "FT8";
+ QTest::newRow ("band-J-r1") << "JL123" << 1 << true << "24048.123" << "FT8";
+ QTest::newRow ("band-K") << "KL123" << 2 << true << "903.123" << "FT8";
+ QTest::newRow ("band-X") << "XL123" << 2 << true << "24048.123" << "FT8";
+ QTest::newRow ("band-9") << "9L123" << 2 << true << "902.123" << "FT8";
+ QTest::newRow ("band-4") << "4L123" << 2 << true << "40.123" << "FT8";
+ QTest::newRow ("band-7") << "7L123" << 2 << true << "70.123" << "FT8";
+ QTest::newRow ("band-L") << "LL123" << 2 << true << "0.123" << "FT8";
+ QTest::newRow ("band-M") << "ML123" << 2 << true << "1.123" << "FT8";
+ QTest::newRow ("band-N") << "NL123" << 2 << true << "3.123" << "FT8";
+ QTest::newRow ("band-O") << "OL123" << 2 << true << "5.123" << "FT8";
+ QTest::newRow ("band-P") << "PL123" << 2 << true << "7.123" << "FT8";
+ QTest::newRow ("band-Q") << "QL123" << 2 << true << "10.123" << "FT8";
+ QTest::newRow ("band-R") << "RL123" << 2 << true << "14.123" << "FT8";
+ QTest::newRow ("band-S") << "SL123" << 2 << true << "18.123" << "FT8";
+ QTest::newRow ("band-T") << "TL123" << 2 << true << "21.123" << "FT8";
+ QTest::newRow ("band-U") << "UL123" << 2 << true << "24.123" << "FT8";
+ QTest::newRow ("band-V") << "VL123" << 2 << true << "28.123" << "FT8";
+ QTest::newRow ("band-W") << "WL123" << 2 << true << "29.123" << "FT8";
+
+ // every digital mode name, on a fixed HF band (R -> 14.)
+ QTest::newRow ("mode-SSB") << "RV074" << 2 << true << "14.074" << "SSB";
+ QTest::newRow ("mode-CW") << "RW074" << 2 << true << "14.074" << "CW";
+ QTest::newRow ("mode-FT8") << "RL074" << 2 << true << "14.074" << "FT8";
+ QTest::newRow ("mode-FT4") << "RJ074" << 2 << true << "14.074" << "FT4";
+ QTest::newRow ("mode-MSK144") << "RK074" << 2 << true << "14.074" << "MSK144";
+ QTest::newRow ("mode-JT9") << "RA074" << 2 << true << "14.074" << "JT9";
+ QTest::newRow ("mode-JT65") << "RB074" << 2 << true << "14.074" << "JT65";
+ QTest::newRow ("mode-FST4") << "RC074" << 2 << true << "14.074" << "FST4";
+ QTest::newRow ("mode-Q65-30B") << "RD074" << 2 << true << "14.074" << "Q65-30B";
+ QTest::newRow ("mode-Q65-60C") << "RE074" << 2 << true << "14.074" << "Q65-60C";
+ QTest::newRow ("mode-Q65-60D") << "RF074" << 2 << true << "14.074" << "Q65-60D";
+ QTest::newRow ("mode-Q65-60E") << "RG074" << 2 << true << "14.074" << "Q65-60E";
+ QTest::newRow ("mode-Q65-120D") << "RH074" << 2 << true << "14.074" << "Q65-120D";
+
+ // FM digit sub-bands (numeric mode -> FM, per-digit MHz)
+ QTest::newRow ("fm-A0") << "A0123" << 2 << true << "50.123" << "FM";
+ QTest::newRow ("fm-A3") << "A3123" << 2 << true << "53.123" << "FM";
+ QTest::newRow ("fm-B4") << "B4123" << 2 << true << "144.123" << "FM";
+ QTest::newRow ("fm-B7") << "B7123" << 2 << true << "147.123" << "FM";
+ QTest::newRow ("fm-C2") << "C2123" << 2 << true << "222.123" << "FM";
+ QTest::newRow ("fm-C3") << "C3123" << 2 << true << "223.123" << "FM";
+ QTest::newRow ("fm-C0-r1") << "C0123" << 1 << true << "222.123" << "FM";
+ QTest::newRow ("fm-D-r2") << "D5446" << 2 << true << "445.446" << "FM";
+ QTest::newRow ("fm-D-r1") << "D5432" << 1 << true << "435.432" << "FM";
+ QTest::newRow ("fm-E5") << "E5123" << 2 << true << "1295.123" << "FM";
+ // user-guide example: QSY W3SZ to 145.550 FM -> "B5550"
+ QTest::newRow ("userguide-B5550") << "B5550" << 2 << true << "145.550" << "FM";
+
+ // ----- rejections (Type::Invalid) -----
+ QTest::newRow ("empty") << "" << 2 << false << "" << "";
+ QTest::newRow ("too-short") << "AL12" << 2 << false << "" << "";
+ QTest::newRow ("too-long") << "AL1234" << 2 << false << "" << "";
+ QTest::newRow ("bad-band-Y") << "YL123" << 2 << false << "" << "";
+ QTest::newRow ("bad-mode-Z") << "AZ123" << 2 << false << "" << "";
+ QTest::newRow ("bad-mode-I") << "RI123" << 2 << false << "" << "";
+ QTest::newRow ("bad-mode-R") << "RR123" << 2 << false << "" << "";
+ QTest::newRow ("bad-fm-digit") << "A5123" << 2 << false << "" << ""; // A only 0..3
+ QTest::newRow ("bad-C0-r2") << "C0123" << 2 << false << "" << "";
+ QTest::newRow ("bad-C2-r1") << "C2123" << 1 << false << "" << "";
+ QTest::newRow ("nondigit-freq")<< "AL12X" << 2 << false << "" << "";
+ QTest::newRow ("bare-call") << "KD0BTO" << 2 << false << "" << "";
+ }
+
+ void decode_frequency ()
+ {
+ QFETCH (QString, payload);
+ QFETCH (int, region);
+ QFETCH (bool, valid);
+ QFETCH (QString, frequency);
+ QFETCH (QString, mode);
+
+ Message const m = QSYMessageParser::decode (payload, region);
+ QCOMPARE (m.type == Type::Frequency, valid);
+ if (valid)
+ {
+ QCOMPARE (m.frequency_mhz, frequency);
+ QCOMPARE (m.mode, mode);
+ }
+ }
+
+ void decode_general_data ()
+ {
+ QTest::addColumn<QString> ("payload");
+ QTest::addColumn<bool> ("valid");
+ QTest::addColumn<QString> ("text");
+
+ QTest::newRow ("c01") << "ZA001" << true << "You are in the log";
+ QTest::newRow ("c02") << "ZA002" << true << "Please call me by phone";
+ QTest::newRow ("c03") << "ZA003" << true << "Check your email";
+ QTest::newRow ("c04") << "ZA004" << true << "You are not in Contest Mode";
+ QTest::newRow ("c05") << "ZA005" << true << "Please check your PC Clock";
+ QTest::newRow ("c06") << "ZA006" << true << "You are transmitting in the wrong time slot";
+ QTest::newRow ("c07") << "ZA007" << true << "Please transmit above 1000 Hz";
+ QTest::newRow ("c08") << "ZA008" << true << "Your transmitter is overmodulated";
+ QTest::newRow ("c09") << "ZA009" << true << "Your audio is distorted";
+ QTest::newRow ("c10") << "ZA010" << true << "You are transmitting on top of a rare DX station";
+ QTest::newRow ("c11") << "ZA011" << true << "Please check HB9Q Logger";
+ QTest::newRow ("c12") << "ZA012" << true << "Please check Ping Jockey";
+ QTest::newRow ("c13") << "ZA013" << true << "Please check ON4KST";
+ QTest::newRow ("c14") << "ZA014" << true << "Please QSL via LoTW";
+
+ QTest::newRow ("code-000") << "ZA000" << false << "";
+ QTest::newRow ("code-015") << "ZA015" << false << "";
+ QTest::newRow ("code-999") << "ZA999" << false << "";
+ QTest::newRow ("za-short") << "ZA" << false << "";
+ QTest::newRow ("za-nondig") << "ZA0X1" << false << "";
+ QTest::newRow ("non-za") << "AA007" << false << "";
+ }
+
+ void decode_general ()
+ {
+ QFETCH (QString, payload);
+ QFETCH (bool, valid);
+ QFETCH (QString, text);
+
+ Message const m = QSYMessageParser::decode (payload, 2);
+ QCOMPARE (m.type == Type::General, valid);
+ if (valid) QCOMPARE (m.text, text);
+ }
+
+ void decode_reply_data ()
+ {
+ QTest::addColumn<QString> ("payload");
+ QTest::addColumn<bool> ("valid");
+ QTest::addColumn<QString> ("call");
+ QTest::addColumn<QString> ("response");
+
+ QTest::newRow ("ok") << "$ K1ABC OKQSY" << true << "K1ABC" << "OK";
+ QTest::newRow ("no") << "$ N0CALL NOQSY" << true << "N0CALL" << "NO";
+ QTest::newRow ("too-few") << "$ K1ABC" << false << "" << "";
+ QTest::newRow ("bad-reply") << "$ K1ABC MAYBE" << false << "" << "";
+ QTest::newRow ("too-many") << "$ K1ABC OKQSY X" << false << "" << "";
+ QTest::newRow ("no-dollar") << "K1ABC OKQSY" << false << "" << "";
+ QTest::newRow ("dollar-prefix-token") << "$junk K1ABC OKQSY" << false << "" << "";
+ }
+
+ void decode_reply ()
+ {
+ QFETCH (QString, payload);
+ QFETCH (bool, valid);
+ QFETCH (QString, call);
+ QFETCH (QString, response);
+
+ Message const m = QSYMessageParser::decode (payload, 2);
+ QCOMPARE (m.type == Type::Reply, valid);
+ if (valid)
+ {
+ QCOMPARE (m.call, call);
+ QCOMPARE (m.response, response);
+ }
+ }
+
+ void roundtrip_frequency ()
+ {
+ static int const kHzSamples[] = {0, 1, 74, 125, 500, 999};
+ QString candidates;
+ for (char b = 'A'; b <= 'Z'; ++b) candidates += QChar (b);
+ for (char d = '0'; d <= '9'; ++d) candidates += QChar (d);
+
+ int accepted = 0, rejected = 0;
+ for (int r = 1; r <= 2; ++r)
+ for (QChar band : candidates)
+ for (QChar mode : candidates)
+ for (int kHz : kHzSamples)
+ {
+ QString const wire = QString {band} + mode + QString {"%1"}.arg (kHz, 3, 10, QLatin1Char ('0'));
+ QString const enc = QSYMessageParser::encodeFrequency (band, mode, kHz, r);
+ Message const m = QSYMessageParser::decode (wire, r);
+
+ if (enc.isEmpty ())
+ {
+ QVERIFY2 (m.type != Type::Frequency, qPrintable (QString ("decode accepted as frequency but encode rejected: %1 r%2").arg (wire).arg (r)));
+ ++rejected;
+ }
+ else
+ {
+ QCOMPARE (enc, wire);
+ QVERIFY2 (m.type == Type::Frequency, qPrintable (QString ("encode accepted but decode rejected: %1 r%2").arg (wire).arg (r)));
+ QCOMPARE (m.band, band);
+ QCOMPARE (m.mode_char, mode);
+ QCOMPARE (m.kHz, kHz);
+ QCOMPARE (QSYMessageParser::encode (m), wire);
+ ++accepted;
+ }
+ }
+ QVERIFY (accepted > 0 && rejected > 0);
+ }
+
+ void roundtrip_general ()
+ {
+ for (int code = 0; code <= 20; ++code)
+ {
+ QString const enc = QSYMessageParser::encodeGeneral (code);
+ QString const wire = QStringLiteral ("ZA") + QString {"%1"}.arg (code, 3, 10, QLatin1Char ('0'));
+ Message const m = QSYMessageParser::decode (wire, 2);
+ if (code >= 1 && code <= 14)
+ {
+ QCOMPARE (enc, wire);
+ QVERIFY (m.type == Type::General);
+ QCOMPARE (m.code, code);
+ QCOMPARE (QSYMessageParser::encode (m), wire);
+ }
+ else
+ {
+ QVERIFY (enc.isEmpty ());
+ QVERIFY (!m);
+ }
+ }
+ }
+
+ void encode_boundaries ()
+ {
+ QCOMPARE (QSYMessageParser::encodeFrequency ('A', 'L', 0, 2), QString ("AL000"));
+ QCOMPARE (QSYMessageParser::encodeFrequency ('A', 'L', 999, 2), QString ("AL999"));
+ QVERIFY (QSYMessageParser::encodeFrequency ('A', 'L', -1, 2).isEmpty ());
+ QVERIFY (QSYMessageParser::encodeFrequency ('A', 'L', 1000, 2).isEmpty ());
+ QVERIFY (QSYMessageParser::encodeFrequency ('Y', 'L', 123, 2).isEmpty ());
+ QVERIFY (QSYMessageParser::encodeFrequency ('A', 'Z', 123, 2).isEmpty ());
+ QVERIFY (QSYMessageParser::encodeFrequency ('A', '5', 123, 2).isEmpty ());
+ QVERIFY (QSYMessageParser::encodeFrequency ('C', '0', 123, 2).isEmpty ());
+ QVERIFY (QSYMessageParser::encodeFrequency ('C', '2', 123, 1).isEmpty ());
+
+ QCOMPARE (QSYMessageParser::encodeGeneral (1), QString ("ZA001"));
+ QCOMPARE (QSYMessageParser::encodeGeneral (14), QString ("ZA014"));
+ QVERIFY (QSYMessageParser::encodeGeneral (0).isEmpty ());
+ QVERIFY (QSYMessageParser::encodeGeneral (15).isEmpty ());
+ }
+
+ void reply_wire ()
+ {
+ QCOMPARE (QSYMessageParser::encodeReplyWire (true), QString ("OKQSY"));
+ QCOMPARE (QSYMessageParser::encodeReplyWire (false), QString ("NOQSY"));
+ }
+
+ void decode_line_data ()
+ {
+ QTest::addColumn<QString> ("line");
+ QTest::addColumn<bool> ("found");
+ QTest::addColumn<QString> ("call");
+ QTest::addColumn<QString> ("payload");
+ QTest::addColumn<int> ("type"); // Type as int
+
+ QTest::newRow ("freq")
+ << "120000 -10 0.2 1234 ~ W3SZ.B5550" << true << "W3SZ" << "B5550" << int (Type::Frequency);
+ QTest::newRow ("general")
+ << "120000 -10 0.2 1234 ~ KD0BTO.ZA007" << true << "KD0BTO" << "ZA007" << int (Type::General);
+ QTest::newRow ("dt-dot-then-msg")
+ << "120000 -10 0.2 1234 ~ K1ABC.AL125" << true << "K1ABC" << "AL125" << int (Type::Frequency);
+ QTest::newRow ("no-qsy")
+ << "120000 -10 0.2 1234 ~ CQ W3SZ FN20" << false << "" << "" << int (Type::Invalid);
+ QTest::newRow ("garbage-dot")
+ << "120000 -10 0.2 1234 ~ KD0BTO.NOTAMSG" << false << "" << "" << int (Type::Invalid);
+ }
+
+ void decode_line ()
+ {
+ QFETCH (QString, line);
+ QFETCH (bool, found);
+ QFETCH (QString, call);
+ QFETCH (QString, payload);
+ QFETCH (int, type);
+
+ QSYMessageParser::LineResult const r = QSYMessageParser::decodeLine (line, 2);
+ QCOMPARE (bool (r.message), found);
+ if (found)
+ {
+ QCOMPARE (r.call, call);
+ QCOMPARE (r.payload, payload);
+ QCOMPARE (int (r.message.type), type);
+ }
+ }
+
+ void prefilter_recall ()
+ {
+ QVERIFY (QSYMessageParser::mightContainMessage ("xx W3SZ.B5550"));
+ QVERIFY (QSYMessageParser::mightContainMessage ("xx KD0BTO.ZA007"));
+ QVERIFY (QSYMessageParser::mightContainMessage ("xx N0CALL.OKQSY"));
+ QVERIFY (!QSYMessageParser::mightContainMessage ("CQ W3SZ FN20"));
+ }
+};
+
+QTEST_APPLESS_MAIN (TestQSYMessageParser)
+
+#include "test_qsy_message_parser.moc"
diff --git a/tests/unit/common/test_qt_helpers.cpp b/tests/unit/common/test_qt_helpers.cpp
new file mode 100644
index 00000000..b56627c0
--- /dev/null
+++ b/tests/unit/common/test_qt_helpers.cpp
@@ -0,0 +1,586 @@
+#include <QtTest>
+#include <QDateTime>
+#include <QDebug>
+#include <QDir>
+#include <QFile>
+#include <QFont>
+#include <QTemporaryDir>
+
+#include <limits>
+
+#include "qt_helpers.hpp"
+
+class TestQtHelpers
+ : public QObject
+{
+ Q_OBJECT
+
+public:
+
+private:
+ Q_SLOT void round_15s_date_time_up ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 500}};
+ QCOMPARE (qt_round_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 30)));
+ }
+
+ Q_SLOT void truncate_15s_date_time_up ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 500}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 15)));
+ }
+
+ Q_SLOT void round_15s_date_time_down ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 499}};
+ QCOMPARE (qt_round_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 15)));
+ }
+
+ Q_SLOT void truncate_15s_date_time_down ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 499}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 15)));
+ }
+
+ Q_SLOT void round_15s_date_time_on ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 15}};
+ QCOMPARE (qt_round_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 15)));
+ }
+
+ Q_SLOT void truncate_15s_date_time_on ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 15}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 15)));
+ }
+
+ Q_SLOT void round_15s_date_time_under ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 14, 999}};
+ QCOMPARE (qt_round_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 15)));
+ }
+
+ Q_SLOT void truncate_15s_date_time_under ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 14, 999}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15)));
+ }
+
+ Q_SLOT void round_15s_date_time_over ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 15, 1}};
+ QCOMPARE (qt_round_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 15)));
+ }
+
+ Q_SLOT void truncate_15s_date_time_over ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 15, 1}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 15000), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 15)));
+ }
+
+ Q_SLOT void round_7p5s_date_time_up ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 26, 250}};
+ QCOMPARE (qt_round_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 30)));
+ }
+
+ Q_SLOT void truncate_7p5s_date_time_up ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 26, 250}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 22, 500)));
+ }
+
+ Q_SLOT void round_7p5s_date_time_down ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 26, 249}};
+ QCOMPARE (qt_round_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 22, 500)));
+ }
+
+ Q_SLOT void truncate_7p5s_date_time_down ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 26, 249}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 22, 500)));
+ }
+
+ Q_SLOT void round_7p5s_date_time_on ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 500}};
+ QCOMPARE (qt_round_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 22, 500)));
+ }
+
+ Q_SLOT void truncate_7p5s_date_time_on ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 500}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 22, 500)));
+ }
+
+ Q_SLOT void round_7p5s_date_time_under ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 499}};
+ QCOMPARE (qt_round_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 22, 500)));
+ }
+
+ Q_SLOT void truncate_7p5s_date_time_under ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 499}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 15)));
+ }
+
+ Q_SLOT void round_7p5s_date_time_over ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 501}};
+ QCOMPARE (qt_round_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 22, 500)));
+ }
+
+ Q_SLOT void truncate_7p5s_date_time_over ()
+ {
+ QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 501}};
+ QCOMPARE (qt_truncate_date_time_to (dt, 7500), QDateTime (QDate (2020, 8, 6), QTime (14, 15, 22, 500)));
+ }
+
+ Q_SLOT void date_time_alignment_rejects_non_positive_intervals_data ()
+ {
+ QTest::addColumn<int> ("milliseconds");
+
+ QTest::newRow ("zero") << 0;
+ QTest::newRow ("negative") << -1000;
+ }
+
+ Q_SLOT void date_time_alignment_rejects_non_positive_intervals ()
+ {
+ QFETCH (int, milliseconds);
+ auto const dt = QDateTime::fromMSecsSinceEpoch (1234, Qt::UTC);
+
+ QVERIFY (!qt_round_date_time_to (dt, milliseconds).isValid ());
+ QVERIFY (!qt_truncate_date_time_to (dt, milliseconds).isValid ());
+ }
+
+ Q_SLOT void date_time_alignment_rejects_invalid_date_times ()
+ {
+ QDateTime const invalid;
+
+ QVERIFY (!qt_round_date_time_to (invalid, 1000).isValid ());
+ QVERIFY (!qt_truncate_date_time_to (invalid, 1000).isValid ());
+ }
+
+ Q_SLOT void date_time_alignment_handles_positive_boundaries ()
+ {
+ auto const between_intervals = QDateTime::fromMSecsSinceEpoch (1600, Qt::UTC);
+ QCOMPARE (qt_round_date_time_to (between_intervals, 1000).toMSecsSinceEpoch (), qint64 {2000});
+ QCOMPARE (qt_truncate_date_time_to (between_intervals, 1000).toMSecsSinceEpoch (), qint64 {1000});
+
+ auto const exact_boundary = QDateTime::fromMSecsSinceEpoch (2000, Qt::UTC);
+ QCOMPARE (qt_round_date_time_to (exact_boundary, 1000), exact_boundary);
+ QCOMPARE (qt_truncate_date_time_to (exact_boundary, 1000), exact_boundary);
+ }
+
+ Q_SLOT void date_time_alignment_handles_pre_epoch_boundaries ()
+ {
+ auto const before_epoch = QDateTime::fromMSecsSinceEpoch (-1, Qt::UTC);
+ QCOMPARE (qt_round_date_time_to (before_epoch, 1000).toMSecsSinceEpoch (), qint64 {0});
+ QCOMPARE (qt_truncate_date_time_to (before_epoch, 1000).toMSecsSinceEpoch (), qint64 {-1000});
+
+ auto const midpoint = QDateTime::fromMSecsSinceEpoch (-1500, Qt::UTC);
+ QCOMPARE (qt_round_date_time_to (midpoint, 1000).toMSecsSinceEpoch (), qint64 {-1000});
+
+ auto const exact_boundary = QDateTime::fromMSecsSinceEpoch (-2000, Qt::UTC);
+ QCOMPARE (qt_round_date_time_to (exact_boundary, 1000), exact_boundary);
+ QCOMPARE (qt_truncate_date_time_to (exact_boundary, 1000), exact_boundary);
+ }
+
+ Q_SLOT void date_time_alignment_rejects_overflow ()
+ {
+ auto const maximum = QDateTime::fromMSecsSinceEpoch (std::numeric_limits<qint64>::max (), Qt::UTC);
+ QVERIFY (maximum.isValid ());
+ QVERIFY (!qt_round_date_time_to (maximum, 2).isValid ());
+ QCOMPARE (qt_truncate_date_time_to (maximum, 2).toMSecsSinceEpoch (),
+ std::numeric_limits<qint64>::max () - 1);
+
+ auto const minimum = QDateTime::fromMSecsSinceEpoch (std::numeric_limits<qint64>::min (), Qt::UTC);
+ QVERIFY (minimum.isValid ());
+ QVERIFY (!qt_round_date_time_to (minimum, 3).isValid ());
+ QVERIFY (!qt_truncate_date_time_to (minimum, 3).isValid ());
+ }
+
+ Q_SLOT void next_cyclic_index_advances_through_all_items ()
+ {
+ QCOMPARE (next_cyclic_index (0, 5), 1);
+ QCOMPARE (next_cyclic_index (1, 5), 2);
+ QCOMPARE (next_cyclic_index (2, 5), 3);
+ QCOMPARE (next_cyclic_index (3, 5), 4);
+ QCOMPARE (next_cyclic_index (4, 5), 0);
+ }
+
+ Q_SLOT void next_cyclic_index_starts_from_invalid_index ()
+ {
+ QCOMPARE (next_cyclic_index (-1, 5), 0);
+ }
+
+ Q_SLOT void next_cyclic_index_has_no_empty_index ()
+ {
+ QCOMPARE (next_cyclic_index (0, 0), -1);
+ }
+
+ Q_SLOT void next_cyclic_index_wraps_by_count ()
+ {
+ QCOMPARE (next_cyclic_index (2, 3), 0);
+ }
+
+ Q_SLOT void installed_data_directory_resolves_relative_destination ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ auto const application_directory = QDir {temporary.path ()}.absoluteFilePath ("bin");
+
+ auto const result = resolve_installed_data_directory (application_directory, "share/wsjtx", "..");
+
+ QCOMPARE (result.absolutePath (), QDir {temporary.path ()}.absoluteFilePath ("share/wsjtx"));
+ }
+
+ Q_SLOT void installed_data_directory_preserves_absolute_destination ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ auto const destination = QDir {temporary.path ()}.absoluteFilePath ("system-share/wsjtx");
+
+ auto const result = resolve_installed_data_directory ("/ignored/bin", destination, "..");
+
+ QCOMPARE (result.absolutePath (), destination);
+ }
+
+ Q_SLOT void installed_data_directory_resolves_macos_bundle_destination ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ auto const application_directory = QDir {temporary.path ()}.absoluteFilePath ("WSJT-X.app/Contents/MacOS");
+
+ auto const result = resolve_installed_data_directory (
+ application_directory, "WSJT-X.app/Contents/Resources/wsjtx", "../../..");
+
+ QCOMPARE (result.absolutePath (),
+ QDir {temporary.path ()}.absoluteFilePath ("WSJT-X.app/Contents/Resources/wsjtx"));
+ QVERIFY (!result.absolutePath ().endsWith ("/wsjtx/wsjtx"));
+ }
+
+ Q_SLOT void preferred_sounds_directory_uses_canonical_directory ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ QDir root {temporary.path ()};
+ QVERIFY (root.mkpath ("share/wsjtx/sounds"));
+ QVERIFY (root.mkpath ("bin/sounds"));
+ QDir canonical {root.absoluteFilePath ("share/wsjtx/sounds")};
+ QDir legacy {root.absoluteFilePath ("bin/sounds")};
+
+ QCOMPARE (preferred_sounds_directory (canonical, legacy).absolutePath (), canonical.absolutePath ());
+ }
+
+ Q_SLOT void preferred_sounds_directory_falls_back_to_legacy_directory ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ QDir root {temporary.path ()};
+ QVERIFY (root.mkpath ("bin/sounds"));
+ QDir canonical {root.absoluteFilePath ("share/wsjtx/sounds")};
+ QDir legacy {root.absoluteFilePath ("bin/sounds")};
+
+ QCOMPARE (preferred_sounds_directory (canonical, legacy).absolutePath (), legacy.absolutePath ());
+ }
+
+ Q_SLOT void preferred_sounds_directory_returns_canonical_when_neither_exists ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ QDir root {temporary.path ()};
+ QDir canonical {root.absoluteFilePath ("share/wsjtx/sounds")};
+ QDir legacy {root.absoluteFilePath ("bin/sounds")};
+
+ QCOMPARE (preferred_sounds_directory (canonical, legacy).absolutePath (), canonical.absolutePath ());
+ }
+
+ Q_SLOT void voice_manifest_path_prefers_readable_canonical_manifest ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ QDir root {temporary.path ()};
+ QVERIFY (root.mkpath ("canonical"));
+ QVERIFY (root.mkpath ("legacy"));
+ QDir canonical {root.absoluteFilePath ("canonical")};
+ QDir legacy {root.absoluteFilePath ("legacy")};
+ QFile canonical_manifest {canonical.absoluteFilePath ("voices.dat")};
+ QVERIFY (canonical_manifest.open (QIODevice::WriteOnly));
+ canonical_manifest.close ();
+ QFile legacy_manifest {legacy.absoluteFilePath ("voices.dat")};
+ QVERIFY (legacy_manifest.open (QIODevice::WriteOnly));
+ legacy_manifest.close ();
+
+ QCOMPARE (voice_manifest_path (canonical, legacy), canonical_manifest.fileName ());
+ }
+
+ Q_SLOT void voice_manifest_path_falls_back_when_canonical_base_has_no_manifest ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ QDir root {temporary.path ()};
+ QVERIFY (root.mkpath ("canonical"));
+ QVERIFY (root.mkpath ("legacy"));
+ QDir canonical {root.absoluteFilePath ("canonical")};
+ QDir legacy {root.absoluteFilePath ("legacy")};
+ QFile legacy_manifest {legacy.absoluteFilePath ("voices.dat")};
+ QVERIFY (legacy_manifest.open (QIODevice::WriteOnly));
+ legacy_manifest.close ();
+
+ QCOMPARE (voice_manifest_path (canonical, legacy), legacy_manifest.fileName ());
+ }
+
+ Q_SLOT void voice_manifest_path_is_empty_when_no_manifest_is_readable ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ QDir root {temporary.path ()};
+ QVERIFY (root.mkpath ("canonical"));
+ QVERIFY (root.mkpath ("legacy"));
+
+ QVERIFY (voice_manifest_path (QDir {root.absoluteFilePath ("canonical")},
+ QDir {root.absoluteFilePath ("legacy")}).isEmpty ());
+ }
+
+ Q_SLOT void app_sounds_subdirectory_accepts_relative_children ()
+ {
+ QVERIFY (app_sounds_subdirectory_is_safe (""));
+ QVERIFY (app_sounds_subdirectory_is_safe ("/English"));
+ QVERIFY (app_sounds_subdirectory_is_safe ("voices/English"));
+ }
+
+ Q_SLOT void app_sounds_subdirectory_rejects_traversal ()
+ {
+ QVERIFY (!app_sounds_subdirectory_is_safe (".."));
+ QVERIFY (!app_sounds_subdirectory_is_safe ("../outside"));
+ QVERIFY (!app_sounds_subdirectory_is_safe ("voices/../../outside"));
+ QVERIFY (!app_sounds_subdirectory_is_safe ("..\\outside"));
+ }
+
+ Q_SLOT void sounds_subdirectory_falls_back_for_traversal ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ QDir root {temporary.path ()};
+
+ QCOMPARE (sounds_subdirectory (root, "../outside").absolutePath (), root.absolutePath ());
+ }
+
+ Q_SLOT void sounds_subdirectory_resolves_valid_child ()
+ {
+ QTemporaryDir temporary;
+ QVERIFY (temporary.isValid ());
+ QDir root {temporary.path ()};
+
+ QCOMPARE (sounds_subdirectory (root, "voices/German").absolutePath (),
+ root.absoluteFilePath ("voices/German"));
+ }
+
+ Q_SLOT void app_voice_entry_parsing_data ()
+ {
+ QTest::addColumn<QString> ("record");
+ QTest::addColumn<bool> ("valid");
+ QTest::addColumn<QString> ("subdirectory");
+ QTest::addColumn<QString> ("display_name");
+
+ QTest::newRow ("legacy leading slash") << "/German|Deutsch" << true << "German" << "Deutsch";
+ QTest::newRow ("nested and trimmed") << " voices/German | Deutsch " << true << "voices/German" << "Deutsch";
+ QTest::newRow ("blank") << "" << false << "" << "";
+ QTest::newRow ("missing delimiter") << "German" << false << "" << "";
+ QTest::newRow ("empty directory") << "|Deutsch" << false << "" << "";
+ QTest::newRow ("root directory") << "/|Deutsch" << false << "" << "";
+ QTest::newRow ("empty name") << "German|" << false << "" << "";
+ QTest::newRow ("extra delimiter") << "German|Deutsch|extra" << false << "" << "";
+ QTest::newRow ("parent traversal") << "../outside|Bad" << false << "" << "";
+ QTest::newRow ("nested traversal") << "voices/../../outside|Bad" << false << "" << "";
+ QTest::newRow ("backslash traversal") << "..\\outside|Bad" << false << "" << "";
+ }
+
+ Q_SLOT void app_voice_entry_parsing ()
+ {
+ QFETCH (QString, record);
+ QFETCH (bool, valid);
+ QFETCH (QString, subdirectory);
+ QFETCH (QString, display_name);
+
+ QString parsed_subdirectory;
+ QString parsed_display_name;
+ QCOMPARE (::parse_app_voice_entry (record, parsed_subdirectory, parsed_display_name), valid);
+ if (valid)
+ {
+ QCOMPARE (parsed_subdirectory, subdirectory);
+ QCOMPARE (parsed_display_name, display_name);
+ }
+ }
+
+ Q_SLOT void writable_file_path_uses_writable_dir ()
+ {
+ QTemporaryDir writable;
+ QVERIFY (writable.isValid ());
+
+ QCOMPARE (writable_file_path (QDir {writable.path ()}, "wsjtx.log"),
+ QDir {writable.path ()}.absoluteFilePath ("wsjtx.log"));
+ }
+
+ Q_SLOT void writable_override_or_installed_file_path_uses_installed_default ()
+ {
+ QTemporaryDir writable;
+ QTemporaryDir installed;
+ QVERIFY (writable.isValid ());
+ QVERIFY (installed.isValid ());
+ QFile file {QDir {installed.path ()}.absoluteFilePath ("cty.dat")};
+ QVERIFY (file.open (QIODevice::WriteOnly));
+ file.close ();
+
+ QCOMPARE (writable_override_or_installed_file_path (QDir {writable.path ()}, QDir {installed.path ()}, "cty.dat"),
+ QDir {installed.path ()}.absoluteFilePath ("cty.dat"));
+ }
+
+ Q_SLOT void writable_override_or_installed_file_path_uses_installed_default_when_missing ()
+ {
+ QTemporaryDir writable;
+ QTemporaryDir installed;
+ QVERIFY (writable.isValid ());
+ QVERIFY (installed.isValid ());
+
+ QCOMPARE (writable_override_or_installed_file_path (QDir {writable.path ()}, QDir {installed.path ()}, "cty.dat"),
+ QDir {installed.path ()}.absoluteFilePath ("cty.dat"));
+ }
+
+ Q_SLOT void writable_override_or_installed_file_path_prefers_writable_override ()
+ {
+ QTemporaryDir writable;
+ QTemporaryDir installed;
+ QVERIFY (writable.isValid ());
+ QVERIFY (installed.isValid ());
+ QFile installed_file {QDir {installed.path ()}.absoluteFilePath ("cty.dat")};
+ QVERIFY (installed_file.open (QIODevice::WriteOnly));
+ installed_file.close ();
+ QFile writable_file {QDir {writable.path ()}.absoluteFilePath ("cty.dat")};
+ QVERIFY (writable_file.open (QIODevice::WriteOnly));
+ writable_file.close ();
+
+ QCOMPARE (writable_override_or_installed_file_path (QDir {writable.path ()}, QDir {installed.path ()}, "cty.dat"),
+ QDir {writable.path ()}.absoluteFilePath ("cty.dat"));
+ }
+
+ Q_SLOT void ensure_parent_directory_creates_append_parent ()
+ {
+ QTemporaryDir writable;
+ QVERIFY (writable.isValid ());
+ auto const& file_path = QDir {writable.path ()}.absoluteFilePath ("nested/wsjtx_log.adi");
+
+ QVERIFY (ensure_parent_directory (file_path));
+ QVERIFY (QDir {writable.path ()}.exists ("nested"));
+ }
+
+ Q_SLOT void is_multicast_address_data ()
+ {
+ QTest::addColumn<QString> ("addr");
+ QTest::addColumn<bool> ("result");
+
+ QTest::newRow ("loopback") << "127.0.0.1" << false;
+ QTest::newRow ("looback IPv6") << "::1" << false;
+ QTest::newRow ("lowest-") << "223.255.255.255" << false;
+ QTest::newRow ("lowest") << "224.0.0.0" << true;
+ QTest::newRow ("lowest- IPv6") << "feff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" << false;
+ QTest::newRow ("lowest IPv6") << "ff00::" << true;
+ QTest::newRow ("highest") << "239.255.255.255" << true;
+ QTest::newRow ("highest+") << "240.0.0.0" << false;
+ QTest::newRow ("highest IPv6") << "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" << true;
+ }
+
+ Q_SLOT void is_multicast_address ()
+ {
+ QFETCH (QString, addr);
+ QFETCH (bool, result);
+
+ QCOMPARE (::is_multicast_address (QHostAddress {addr}), result);
+ }
+
+ Q_SLOT void is_MAC_ambiguous_multicast_address_data ()
+ {
+ QTest::addColumn<QString> ("addr");
+ QTest::addColumn<bool> ("result");
+
+ QTest::newRow ("loopback") << "127.0.0.1" << false;
+ QTest::newRow ("looback IPv6") << "::1" << false;
+
+ QTest::newRow ("lowest- R1") << "223.255.255.255" << false;
+ QTest::newRow ("lowest R1") << "224.0.0.0" << false;
+ QTest::newRow ("highest R1") << "224.0.0.255" << false;
+ QTest::newRow ("highest+ R1") << "224.0.1.0" << false;
+ QTest::newRow ("lowest- R1A") << "224.127.255.255" << false;
+ QTest::newRow ("lowest R1A") << "224.128.0.0" << true;
+ QTest::newRow ("highest R1A") << "224.128.0.255" << true;
+ QTest::newRow ("highest+ R1A") << "224.128.1.0" << false;
+
+ QTest::newRow ("lowest- R2") << "224.255.255.255" << false;
+ QTest::newRow ("lowest R2") << "225.0.0.0" << true;
+ QTest::newRow ("highest R2") << "225.0.0.255" << true;
+ QTest::newRow ("highest+ R2") << "225.0.1.0" << false;
+ QTest::newRow ("lowest- R2A") << "225.127.255.255" << false;
+ QTest::newRow ("lowest R2A") << "225.128.0.0" << true;
+ QTest::newRow ("highest R2A") << "225.128.0.255" << true;
+ QTest::newRow ("highest+ R2A") << "225.128.1.0" << false;
+
+ QTest::newRow ("lowest- R3") << "238.255.255.255" << false;
+ QTest::newRow ("lowest R3") << "239.0.0.0" << true;
+ QTest::newRow ("highest R3") << "239.0.0.255" << true;
+ QTest::newRow ("highest+ R3") << "239.0.1.0" << false;
+ QTest::newRow ("lowest- R3A") << "239.127.255.255" << false;
+ QTest::newRow ("lowest R3A") << "239.128.0.0" << true;
+ QTest::newRow ("highest R3A") << "239.128.0.255" << true;
+ QTest::newRow ("highest+ R3A") << "239.128.1.0" << false;
+
+ QTest::newRow ("lowest- IPv6") << "feff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" << false;
+ QTest::newRow ("lowest IPv6") << "ff00::" << false;
+ QTest::newRow ("highest") << "239.255.255.255" << false;
+ QTest::newRow ("highest+") << "240.0.0.0" << false;
+ QTest::newRow ("highest IPv6") << "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" << false;
+ }
+
+ Q_SLOT void is_MAC_ambiguous_multicast_address ()
+ {
+ QFETCH (QString, addr);
+ QFETCH (bool, result);
+
+ QCOMPARE (::is_MAC_ambiguous_multicast_address (QHostAddress {addr}), result);
+ }
+
+ Q_SLOT void application_style_sheet_uses_light_base ()
+ {
+ QFont font {"Test Font", 10};
+ auto const base = QString {"QPushButton { color: red; }"};
+ auto const style_sheet = application_style_sheet (base, "dark", false, font);
+
+ QVERIFY (style_sheet.startsWith (base + '\n'));
+ QCOMPARE (style_sheet.count ("* {"), 1);
+ }
+
+ Q_SLOT void application_style_sheet_uses_dark_base ()
+ {
+ QFont font {"Test Font", 10};
+ auto const style_sheet = application_style_sheet ("light", "dark", true, font);
+
+ QVERIFY (style_sheet.startsWith ("dark\n"));
+ QVERIFY (!style_sheet.contains ("light"));
+ QCOMPARE (style_sheet.count ("* {"), 1);
+ }
+
+ Q_SLOT void application_style_sheet_adds_font_without_base ()
+ {
+ QFont font {"Test Font", 10};
+ auto const style_sheet = application_style_sheet ({}, {}, false, font);
+
+ QVERIFY (style_sheet.startsWith ("* {"));
+ QVERIFY (style_sheet.contains ("font-family: Test Font"));
+ }
+};
+
+QTEST_MAIN (TestQtHelpers);
+
+#include "test_qt_helpers.moc"
diff --git a/tests/unit/common/test_rig_frequency_change_policy.cpp b/tests/unit/common/test_rig_frequency_change_policy.cpp
new file mode 100644
index 00000000..baa674ee
--- /dev/null
+++ b/tests/unit/common/test_rig_frequency_change_policy.cpp
@@ -0,0 +1,246 @@
+#include <type_traits>
+
+#include <QtTest/QtTest>
+
+#include "RigFrequencyChangePolicy.hpp"
+
+Q_DECLARE_METATYPE (RigFrequencyChangePolicy::Activity)
+
+namespace
+{
+ using RigFrequencyChangePolicy::Activity;
+ using RigFrequencyChangePolicy::BlockReason;
+ using RigFrequencyChangePolicy::ChangeKind;
+ using RigFrequencyChangePolicy::Decision;
+
+ using EvaluateFunction = Decision (*) (ChangeKind, Activity const&, bool);
+ static_assert (std::is_same<decltype (&RigFrequencyChangePolicy::evaluate),
+ EvaluateFunction>::value,
+ "frequency-change policy must not depend on a frequency magnitude");
+
+ void addActivityRows ()
+ {
+ QTest::newRow ("transmit-requested")
+ << Activity{true, false, false, false, false, false, false, false, false};
+ QTest::newRow ("transmit-command-pending")
+ << Activity{false, true, false, false, false, false, false, false, false};
+ QTest::newRow ("transmitting")
+ << Activity{false, false, true, false, false, false, false, false, false};
+ QTest::newRow ("tuning")
+ << Activity{false, false, false, true, false, false, false, false, false};
+ QTest::newRow ("jtty-transmitting")
+ << Activity{false, false, false, false, true, false, false, false, false};
+ QTest::newRow ("start-delay-active")
+ << Activity{false, false, false, false, false, true, false, false, false};
+ QTest::newRow ("stop-delay-active")
+ << Activity{false, false, false, false, false, false, true, false, false};
+ QTest::newRow ("rig-ptt")
+ << Activity{false, false, false, false, false, false, false, true, false};
+ QTest::newRow ("rig-tune")
+ << Activity{false, false, false, false, false, false, false, false, true};
+ }
+
+ void compareDecision (Decision const& actual, bool allowed, BlockReason reason)
+ {
+ QCOMPARE (actual.allowed, allowed);
+ QCOMPARE (static_cast<int> (actual.reason), static_cast<int> (reason));
+ }
+}
+
+class TestRigFrequencyChangePolicy final
+ : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void idleAllowsEveryChangeKind ();
+ void everyActivityBlocksNominalQsy_data ();
+ void everyActivityBlocksNominalQsy ();
+ void transmitRequestedAloneAllowsPreKeyCorrection ();
+ void activeRfCorrectionRequiresPermission_data ();
+ void activeRfCorrectionRequiresPermission ();
+ void combinedActivityUsesStableBlockReasons ();
+ void evaluationSignatureExcludesFrequencyMagnitude ();
+ void guardedApplyProtectsMutationBoundary ();
+ void txPathFrequencyRequiresSplit ();
+ void acceptedRequestControlsDependentCommit ();
+ void rejectedRequestStopsMonitoringItStarted ();
+};
+
+void TestRigFrequencyChangePolicy::idleAllowsEveryChangeKind ()
+{
+ Activity const idle{};
+
+ for (auto const correctionsAllowed : {false, true})
+ {
+ compareDecision (RigFrequencyChangePolicy::evaluate (
+ ChangeKind::NominalQsy, idle, correctionsAllowed),
+ true, BlockReason::None);
+ compareDecision (RigFrequencyChangePolicy::evaluate (
+ ChangeKind::TxPathCorrection, idle, correctionsAllowed),
+ true, BlockReason::None);
+ }
+}
+
+void TestRigFrequencyChangePolicy::everyActivityBlocksNominalQsy_data ()
+{
+ QTest::addColumn<Activity> ("activity");
+ addActivityRows ();
+}
+
+void TestRigFrequencyChangePolicy::everyActivityBlocksNominalQsy ()
+{
+ QFETCH (Activity, activity);
+
+ for (auto const correctionsAllowed : {false, true})
+ {
+ compareDecision (RigFrequencyChangePolicy::evaluate (
+ ChangeKind::NominalQsy, activity, correctionsAllowed),
+ false, BlockReason::NominalQsyWhileRfActive);
+ }
+}
+
+void TestRigFrequencyChangePolicy::transmitRequestedAloneAllowsPreKeyCorrection ()
+{
+ Activity const requested{true, false, false, false, false, false, false, false, false};
+
+ for (auto const correctionsAllowed : {false, true})
+ {
+ compareDecision (RigFrequencyChangePolicy::evaluate (
+ ChangeKind::TxPathCorrection, requested, correctionsAllowed),
+ true, BlockReason::None);
+ }
+}
+
+void TestRigFrequencyChangePolicy::activeRfCorrectionRequiresPermission_data ()
+{
+ QTest::addColumn<Activity> ("activity");
+
+ QTest::newRow ("transmit-command-pending")
+ << Activity{false, true, false, false, false, false, false, false, false};
+ QTest::newRow ("transmitting")
+ << Activity{false, false, true, false, false, false, false, false, false};
+ QTest::newRow ("tuning")
+ << Activity{false, false, false, true, false, false, false, false, false};
+ QTest::newRow ("jtty-transmitting")
+ << Activity{false, false, false, false, true, false, false, false, false};
+ QTest::newRow ("start-delay-active")
+ << Activity{false, false, false, false, false, true, false, false, false};
+ QTest::newRow ("stop-delay-active")
+ << Activity{false, false, false, false, false, false, true, false, false};
+ QTest::newRow ("rig-ptt")
+ << Activity{false, false, false, false, false, false, false, true, false};
+ QTest::newRow ("rig-tune")
+ << Activity{false, false, false, false, false, false, false, false, true};
+}
+
+void TestRigFrequencyChangePolicy::activeRfCorrectionRequiresPermission ()
+{
+ QFETCH (Activity, activity);
+
+ compareDecision (RigFrequencyChangePolicy::evaluate (
+ ChangeKind::TxPathCorrection, activity, false),
+ false, BlockReason::TxCorrectionDisabled);
+ compareDecision (RigFrequencyChangePolicy::evaluate (
+ ChangeKind::TxPathCorrection, activity, true),
+ true, BlockReason::None);
+}
+
+void TestRigFrequencyChangePolicy::combinedActivityUsesStableBlockReasons ()
+{
+ Activity const allActive{true, true, true, true, true, true, true, true, true};
+
+ compareDecision (RigFrequencyChangePolicy::evaluate (
+ ChangeKind::NominalQsy, allActive, true),
+ false, BlockReason::NominalQsyWhileRfActive);
+ compareDecision (RigFrequencyChangePolicy::evaluate (
+ ChangeKind::TxPathCorrection, allActive, false),
+ false, BlockReason::TxCorrectionDisabled);
+}
+
+void TestRigFrequencyChangePolicy::evaluationSignatureExcludesFrequencyMagnitude ()
+{
+ EvaluateFunction const evaluator = &RigFrequencyChangePolicy::evaluate;
+ QVERIFY (evaluator);
+}
+
+void TestRigFrequencyChangePolicy::guardedApplyProtectsMutationBoundary ()
+{
+ Activity active;
+ active.rigPtt = true;
+ bool mutated = false;
+
+ QVERIFY (!RigFrequencyChangePolicy::applyIfAllowed (
+ ChangeKind::NominalQsy, active, true, [&] {mutated = true;}));
+ QVERIFY (!mutated);
+
+ QVERIFY (RigFrequencyChangePolicy::applyIfAllowed (
+ ChangeKind::TxPathCorrection, active, true, [&] {mutated = true;}));
+ QVERIFY (mutated);
+}
+
+void TestRigFrequencyChangePolicy::txPathFrequencyRequiresSplit ()
+{
+ QVERIFY (RigFrequencyChangePolicy::tx_path_frequency_supported (false, false));
+ QVERIFY (RigFrequencyChangePolicy::tx_path_frequency_supported (false, true));
+ QVERIFY (!RigFrequencyChangePolicy::tx_path_frequency_supported (true, false));
+ QVERIFY (RigFrequencyChangePolicy::tx_path_frequency_supported (true, true));
+}
+
+void TestRigFrequencyChangePolicy::acceptedRequestControlsDependentCommit ()
+{
+ bool committed = false;
+ QVERIFY (!RigFrequencyChangePolicy::commitIfAccepted (
+ [] {return false;}, [&] {committed = true;}));
+ QVERIFY (!committed);
+
+ QVERIFY (RigFrequencyChangePolicy::commitIfAccepted (
+ [] {return true;}, [&] {committed = true;}));
+ QVERIFY (committed);
+}
+
+void TestRigFrequencyChangePolicy::rejectedRequestStopsMonitoringItStarted ()
+{
+ bool monitoring = false;
+ QVector<bool> transitions;
+ auto const setMonitoring = [&] (bool state) {
+ monitoring = state;
+ transitions.append (state);
+ };
+ bool request_observed_monitoring = false;
+
+ QVERIFY (!RigFrequencyChangePolicy::requestWhileMonitoring (
+ monitoring, setMonitoring, [&] {
+ request_observed_monitoring = monitoring;
+ return false;
+ }));
+ QVERIFY (request_observed_monitoring);
+ QCOMPARE (transitions, QVector<bool> ({true, false}));
+ QVERIFY (!monitoring);
+
+ transitions.clear ();
+ request_observed_monitoring = false;
+ QVERIFY (RigFrequencyChangePolicy::requestWhileMonitoring (
+ monitoring, setMonitoring, [&] {
+ request_observed_monitoring = monitoring;
+ return true;
+ }));
+ QVERIFY (request_observed_monitoring);
+ QCOMPARE (transitions, QVector<bool> ({true}));
+ QVERIFY (monitoring);
+
+ transitions.clear ();
+ request_observed_monitoring = false;
+ QVERIFY (!RigFrequencyChangePolicy::requestWhileMonitoring (
+ monitoring, setMonitoring, [&] {
+ request_observed_monitoring = monitoring;
+ return false;
+ }));
+ QVERIFY (request_observed_monitoring);
+ QVERIFY (transitions.isEmpty ());
+ QVERIFY (monitoring);
+}
+
+QTEST_GUILESS_MAIN (TestRigFrequencyChangePolicy)
+
+#include "test_rig_frequency_change_policy.moc"
diff --git a/tests/unit/common/test_round_robin_selection.cpp b/tests/unit/common/test_round_robin_selection.cpp
new file mode 100644
index 00000000..5bf32351
--- /dev/null
+++ b/tests/unit/common/test_round_robin_selection.cpp
@@ -0,0 +1,103 @@
+#include <QtTest>
+#include <QComboBox>
+#include <QLineEdit>
+
+#include "widgets/RoundRobinSelection.hpp"
+
+namespace
+{
+ QString selectedValue (QComboBox const& combo)
+ {
+ return QString::fromStdString (
+ BeaconTx::formatRoundRobinPolicy (RoundRobinSelection::policy (combo)));
+ }
+}
+
+class TestRoundRobinSelection final : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void presetsHaveCanonicalIdentity ()
+ {
+ QComboBox combo;
+ combo.setEditable (true);
+ RoundRobinSelection::initialize (combo, "Localized random");
+ QCOMPARE (combo.count (), 21);
+ QCOMPARE (combo.currentText (), QString {"Localized random"});
+ QCOMPARE (selectedValue (combo), QString {"random"});
+ for (int index = 1; index < combo.count (); ++index)
+ {
+ combo.setCurrentIndex (index);
+ QCOMPARE (selectedValue (combo), combo.currentData ().toString ());
+ QVERIFY (RoundRobinSelection::policy (combo).kind == BeaconTx::RoundRobinPolicy::Kind::Fixed);
+ }
+ combo.setItemText (1, "Localized fixed preset");
+ combo.setCurrentIndex (1);
+ QCOMPARE (selectedValue (combo), QString {"1/2"});
+ }
+
+ void editorOverridesSelectedPreset ()
+ {
+ QComboBox combo;
+ combo.setEditable (true);
+ RoundRobinSelection::initialize (combo, "Random");
+ QString observed;
+ connect (&combo, &QComboBox::currentTextChanged, this,
+ [&] {observed = selectedValue (combo);});
+ combo.setEditText ("7/12");
+ QCOMPARE (combo.currentIndex (), 0);
+ QCOMPARE (observed, QString {"7/12"});
+ combo.setCurrentIndex (1);
+ combo.setEditText ("2/4");
+ QCOMPARE (observed, QString {"2/4"});
+ RoundRobinSelection::setPolicy (combo, BeaconTx::RoundRobinPolicy::fixed (0, 2));
+ QCOMPARE (combo.currentText (), QString {"1/2"});
+ QCOMPARE (observed, QString {"1/2"});
+ combo.setEditText ("invalid");
+ QCOMPARE (observed, QString {"random"});
+ combo.setCurrentIndex (0);
+ QCOMPARE (observed, QString {"random"});
+ }
+
+ void committedCustomEntryDoesNotNeedPresetData ()
+ {
+ QComboBox combo;
+ combo.setEditable (true);
+ RoundRobinSelection::initialize (combo, "Random");
+ combo.setEditText ("7/12");
+ QTest::keyClick (combo.lineEdit (), Qt::Key_Return);
+ QVERIFY (combo.currentIndex () > 0);
+ QVERIFY (!combo.currentData ().isValid ());
+ QCOMPARE (selectedValue (combo), QString {"7/12"});
+ }
+
+ void selectionRestoration_data ()
+ {
+ QTest::addColumn<QString> ("stored");
+ QTest::addColumn<QString> ("expected");
+ QTest::newRow ("custom") << "7/12" << "7/12";
+ QTest::newRow ("preset") << "2/4" << "2/4";
+ QTest::newRow ("whitespace") << " 2 / 4 " << "2/4";
+ QTest::newRow ("canonical-random") << "random" << "random";
+ QTest::newRow ("legacy-random-label") << "Localized random" << "random";
+ QTest::newRow ("invalid") << "13/12" << "random";
+ }
+
+ void selectionRestoration ()
+ {
+ QFETCH (QString, stored);
+ QFETCH (QString, expected);
+ QComboBox combo;
+ combo.setEditable (true);
+ RoundRobinSelection::initialize (combo, "Localized random");
+ RoundRobinSelection::setPolicy (combo, BeaconTx::parseRoundRobinPolicy (
+ stored.toStdString ()));
+ QCOMPARE (selectedValue (combo), expected);
+ QCOMPARE (combo.currentText (), expected == "random" ? QString {"Localized random"} : expected);
+ }
+};
+
+QTEST_MAIN (TestRoundRobinSelection)
+
+#include "test_round_robin_selection.moc"
diff --git a/tests/unit/common/test_rr73_policy.cpp b/tests/unit/common/test_rr73_policy.cpp
new file mode 100644
index 00000000..9f126f3b
--- /dev/null
+++ b/tests/unit/common/test_rr73_policy.cpp
@@ -0,0 +1,43 @@
+#include <QtTest>
+
+#include "Rr73Policy.hpp"
+
+class TestRr73Policy final : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void tx4AllowsRr73_data ();
+ void tx4AllowsRr73 ();
+};
+
+void TestRr73Policy::tx4AllowsRr73_data ()
+{
+ QTest::addColumn<QString> ("mode");
+ QTest::addColumn<bool> ("shortMessages");
+ QTest::addColumn<bool> ("allowed");
+
+ QTest::newRow ("FT8") << QString {"FT8"} << false << true;
+ QTest::newRow ("FT4") << QString {"FT4"} << false << true;
+ QTest::newRow ("FST4") << QString {"FST4"} << false << true;
+ QTest::newRow ("MSK144") << QString {"MSK144"} << false << true;
+ QTest::newRow ("MSK144 shorthand") << QString {"MSK144"} << true << false;
+ QTest::newRow ("Q65") << QString {"Q65"} << false << true;
+ QTest::newRow ("Q65 shorthand") << QString {"Q65"} << true << false;
+ QTest::newRow ("JT65") << QString {"JT65"} << false << false;
+ QTest::newRow ("JT4") << QString {"JT4"} << false << false;
+ QTest::newRow ("FST4W") << QString {"FST4W"} << false << false;
+}
+
+void TestRr73Policy::tx4AllowsRr73 ()
+{
+ QFETCH (QString, mode);
+ QFETCH (bool, shortMessages);
+ QFETCH (bool, allowed);
+
+ QCOMPARE (Rr73Policy::tx4AllowsRr73 (mode, shortMessages), allowed);
+}
+
+QTEST_GUILESS_MAIN (TestRr73Policy)
+
+#include "test_rr73_policy.moc"
diff --git a/tests/unit/common/test_spec_op_label.cpp b/tests/unit/common/test_spec_op_label.cpp
new file mode 100644
index 00000000..f5d45535
--- /dev/null
+++ b/tests/unit/common/test_spec_op_label.cpp
@@ -0,0 +1,55 @@
+#include <QtTest>
+
+#include "widgets/SpecOpLabel.h"
+
+Q_DECLARE_METATYPE (SpecialOperatingActivity)
+
+class TestSpecOpLabel : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void formatsLabel_data ();
+ void formatsLabel ();
+ void superFoxPreference ();
+};
+
+void TestSpecOpLabel::formatsLabel_data ()
+{
+ QTest::addColumn<SpecialOperatingActivity> ("specialOperation");
+ QTest::addColumn<bool> ("ncccSprint");
+ QTest::addColumn<QString> ("expected");
+
+ QTest::newRow ("na-vhf") << SpecialOperatingActivity::NA_VHF << false << QString {"NA VHF"};
+ QTest::newRow ("nccc-sprint") << SpecialOperatingActivity::NA_VHF << true << QString {"NCCC Sprint"};
+ QTest::newRow ("eu-vhf") << SpecialOperatingActivity::EU_VHF << false << QString {"EU VHF"};
+ QTest::newRow ("field-day") << SpecialOperatingActivity::FIELD_DAY << false << QString {"Field Day"};
+ QTest::newRow ("rtty") << SpecialOperatingActivity::RTTY << false << QString {"FT RU"};
+ QTest::newRow ("ww-digi") << SpecialOperatingActivity::WW_DIGI << false << QString {"WW Digi"};
+ QTest::newRow ("arrl-digi") << SpecialOperatingActivity::ARRL_DIGI << false << QString {"ARRL Digi"};
+ QTest::newRow ("q65-pileup") << SpecialOperatingActivity::Q65_PILEUP << false << QString {"Q65 Pileup"};
+ QTest::newRow ("nccc-ignored-outside-na-vhf") << SpecialOperatingActivity::EU_VHF << true << QString {"EU VHF"};
+ QTest::newRow ("none") << SpecialOperatingActivity::NONE << false << QString {};
+ QTest::newRow ("fox") << SpecialOperatingActivity::FOX << false << QString {"Fox"};
+ QTest::newRow ("hound") << SpecialOperatingActivity::HOUND << false << QString {"Hound"};
+}
+
+void TestSpecOpLabel::formatsLabel ()
+{
+ QFETCH (SpecialOperatingActivity, specialOperation);
+ QFETCH (bool, ncccSprint);
+ QFETCH (QString, expected);
+
+ QCOMPARE (SpecOpLabel::label (specialOperation, ncccSprint), expected);
+}
+
+void TestSpecOpLabel::superFoxPreference ()
+{
+ QCOMPARE(SpecOpLabel::label(SpecialOperatingActivity::FOX, false, true), QString("Super Fox"));
+ QCOMPARE(SpecOpLabel::label(SpecialOperatingActivity::HOUND, false, true), QString("Super Hound"));
+ QCOMPARE(SpecOpLabel::label(SpecialOperatingActivity::NONE, false, true), QString{});
+ QCOMPARE(SpecOpLabel::label(SpecialOperatingActivity::NA_VHF, true, true), QString("NCCC Sprint"));
+}
+
+QTEST_MAIN (TestSpecOpLabel)
+#include "test_spec_op_label.moc"
diff --git a/tests/unit/common/test_superfox_tx_planner.cpp b/tests/unit/common/test_superfox_tx_planner.cpp
new file mode 100644
index 00000000..f1c6dc84
--- /dev/null
+++ b/tests/unit/common/test_superfox_tx_planner.cpp
@@ -0,0 +1,125 @@
+#include "SuperFoxTxPlanner.h"
+
+#include <QTest>
+
+class TestSuperFoxTxPlanner : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void freeTextCapsQueuedReportsAtFour();
+ void noFreeTextAllowsNineRecords();
+ void freeTextRR73UsesSharedRecordCapacity();
+ void parseQueuedHoundLine();
+
+private:
+ static SuperFoxTxPlanner::QsoState qso(QString const& call,
+ QString const& report = "-10",
+ int ncall = 0,
+ int tFoxRrpt = -1,
+ int tFoxTxRR73 = -1);
+ static QString queueLine(QString const& call, QString const& report,
+ QString const& grid);
+};
+
+SuperFoxTxPlanner::QsoState TestSuperFoxTxPlanner::qso(QString const& call,
+ QString const& report,
+ int ncall,
+ int tFoxRrpt,
+ int tFoxTxRR73)
+{
+ SuperFoxTxPlanner::QsoState result;
+ result.call = call;
+ result.grid = "FN20";
+ result.sent = report;
+ result.rcvd = "-05";
+ result.ncall = ncall;
+ result.tFoxRrpt = tFoxRrpt;
+ result.tFoxTxRR73 = tFoxTxRR73;
+ return result;
+}
+
+QString TestSuperFoxTxPlanner::queueLine(QString const& call, QString const& report,
+ QString const& grid)
+{
+ return (call + " ").left(12) + report + " " + grid;
+}
+
+void TestSuperFoxTxPlanner::freeTextCapsQueuedReportsAtFour()
+{
+ QVector<SuperFoxTxPlanner::QsoState> qsos;
+ QQueue<QString> inProgress;
+ QVector<SuperFoxTxPlanner::QueuedHound> queue;
+ for (auto const& call : {"K1AAA", "K1AAB", "K1AAC", "K1AAD", "K1AAE"})
+ {
+ queue.push_back(SuperFoxTxPlanner::parseQueuedHound(queueLine(call, "-12", "FN31")));
+ }
+
+ auto const plan = SuperFoxTxPlanner::plan(qsos, inProgress, queue, 3, true);
+
+ QCOMPARE(plan.records.size(), 4);
+ QCOMPARE(plan.reportCount(), 4);
+ QCOMPARE(plan.queuedReportCount(), 4);
+ QCOMPARE(plan.records.at(0).call, QString {"K1AAA"});
+ QCOMPARE(plan.records.at(3).call, QString {"K1AAD"});
+}
+
+void TestSuperFoxTxPlanner::noFreeTextAllowsNineRecords()
+{
+ QVector<SuperFoxTxPlanner::QsoState> qsos;
+ for (auto const& call : {"K1RR1", "K1RR2", "K1RR3", "K1RR4", "K1RR5"})
+ {
+ qsos.push_back(qso(call, "-10", 0, 10, -1));
+ }
+
+ QQueue<QString> inProgress;
+ QVector<SuperFoxTxPlanner::QueuedHound> queue;
+ for (auto const& call : {"K1RP1", "K1RP2", "K1RP3", "K1RP4", "K1RP5"})
+ {
+ queue.push_back(SuperFoxTxPlanner::parseQueuedHound(queueLine(call, "-07", "FN32")));
+ }
+
+ auto const plan = SuperFoxTxPlanner::plan(qsos, inProgress, queue, 3, false);
+
+ QCOMPARE(plan.records.size(), 9);
+ QCOMPARE(plan.rr73Count(), 5);
+ QCOMPARE(plan.reportCount(), 4);
+ QCOMPARE(plan.queuedReportCount(), 4);
+}
+
+void TestSuperFoxTxPlanner::freeTextRR73UsesSharedRecordCapacity()
+{
+ QVector<SuperFoxTxPlanner::QsoState> qsos;
+ for (auto const& call : {"K1RR1", "K1RR2", "K1RR3"})
+ {
+ qsos.push_back(qso(call, "-10", 0, 10, -1));
+ }
+
+ QQueue<QString> inProgress;
+ QVector<SuperFoxTxPlanner::QueuedHound> queue;
+ for (auto const& call : {"K1RP1", "K1RP2"})
+ {
+ queue.push_back(SuperFoxTxPlanner::parseQueuedHound(queueLine(call, "-07", "FN32")));
+ }
+
+ auto const plan = SuperFoxTxPlanner::plan(qsos, inProgress, queue, 3, true);
+
+ QCOMPARE(plan.records.size(), 4);
+ QCOMPARE(plan.rr73Count(), 3);
+ QCOMPARE(plan.reportCount(), 1);
+ QCOMPARE(plan.queuedReportCount(), 1);
+ QCOMPARE(plan.records.last().call, QString {"K1RP1"});
+}
+
+void TestSuperFoxTxPlanner::parseQueuedHoundLine()
+{
+ auto const hound = SuperFoxTxPlanner::parseQueuedHound(queueLine("K1ABC", "+03", "FN42"));
+
+ QCOMPARE(hound.call, QString {"K1ABC"});
+ QCOMPARE(hound.report, QString {"+03"});
+ QCOMPARE(hound.grid, QString {"FN42"});
+}
+
+QTEST_MAIN(TestSuperFoxTxPlanner)
+
+#include "test_superfox_tx_planner.moc"
diff --git a/tests/unit/common/test_tx_inhibit_transceiver.cpp b/tests/unit/common/test_tx_inhibit_transceiver.cpp
new file mode 100644
index 00000000..8b67f2f1
--- /dev/null
+++ b/tests/unit/common/test_tx_inhibit_transceiver.cpp
@@ -0,0 +1,485 @@
+#include <memory>
+
+#include <QtTest>
+#include <QThread>
+
+#include "Transceiver/TransceiverBase.hpp"
+#include "Transceiver/TransceiverFactory.hpp"
+#include "Transceiver/TxInhibitTransceiver.hpp"
+
+class FakeInhibitTransceiver final
+ : public Transceiver
+{
+ Q_OBJECT
+
+public:
+ FakeInhibitTransceiver ()
+ : Transceiver {nullptr, nullptr}
+ {
+ }
+
+ void set (TransceiverState const& state, unsigned sequence_number) noexcept override
+ {
+ ++set_calls;
+ last_set_thread = QThread::currentThread ();
+ last_state = state;
+ last_sequence_number = sequence_number;
+ }
+
+ void start (unsigned sequence_number) noexcept override
+ {
+ started = true;
+ last_sequence_number = sequence_number;
+ }
+
+ void stop () noexcept override
+ {
+ stopped = true;
+ }
+
+ void send_update (TransceiverState const& state, unsigned sequence_number)
+ {
+ Q_EMIT update (state, sequence_number);
+ }
+
+ void send_receive_audio (ReceiveAudio audio) { Q_EMIT receiveAudio (audio); }
+
+ TransceiverState last_state;
+ unsigned last_sequence_number {0};
+ bool stopped {false};
+ bool started {false};
+ int set_calls {0};
+ QThread * last_set_thread {nullptr};
+};
+
+class RecordingTransceiverBase final
+ : public TransceiverBase
+{
+public:
+ explicit RecordingTransceiverBase (logger_type * logger)
+ : TransceiverBase {logger, nullptr}
+ {
+ }
+
+ QStringList operations;
+
+private:
+ int do_start () override {return 0;}
+ void do_stop () override {}
+ void do_frequency (Frequency, MODE, bool) override {}
+ void do_tx_frequency (Frequency, MODE, bool) override {}
+ void do_mode (MODE) override {}
+
+ void do_ptt (bool on) override
+ {
+ operations.append (QStringLiteral ("ptt:%1").arg (on));
+ update_PTT (on);
+ }
+
+ void do_tune (bool on) override
+ {
+ operations.append (QStringLiteral ("tune:%1").arg (on));
+ }
+};
+
+class TestTxInhibitTransceiver : public QObject
+{
+ Q_OBJECT
+
+private:
+ Q_SIGNAL void command (QString controller, quint32 ttl, QString station);
+
+ Q_SLOT void forwardsReceiveAudio ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ ReceiveAudio observed;
+ connect (&transceiver, &Transceiver::receiveAudio,
+ this, [&observed] (ReceiveAudio audio) { observed = std::move (audio); });
+ auto block = std::make_shared<ReceiveAudioBlock> ();
+
+ fake->send_receive_audio (block);
+
+ QCOMPARE (observed, ReceiveAudio {block});
+ }
+
+ Q_SLOT void holdFiltersPttAndTuneWithoutChangingReportedRigState ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ QSignalSpy updates {&transceiver, &Transceiver::update};
+ transceiver.start (10);
+ QVERIFY (!status.isEmpty ());
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ requested.tune (true);
+ transceiver.set (requested, 11);
+ QVERIFY (fake->last_state.ptt ());
+ QVERIFY (fake->last_state.tune ());
+
+ transceiver.tx_inhibit_command (QStringLiteral ("W1AW"), 600, QStringLiteral ("W1AW"));
+ QTRY_VERIFY (!fake->last_state.ptt ());
+ QVERIFY (!fake->last_state.tune ());
+
+ Transceiver::TransceiverState physical;
+ physical.online (true);
+ physical.ptt (false);
+ physical.tune (false);
+ fake->send_update (physical, 11);
+ QCOMPARE (updates.size (), 1);
+ auto const reported = qvariant_cast<Transceiver::TransceiverState> (updates.takeFirst ().at (0));
+ QVERIFY (!reported.ptt ());
+ QVERIFY (!reported.tune ());
+ }
+
+ Q_SLOT void pttAndTuneTransitionsReachTransceiverBaseInSafeOrder ()
+ {
+ Transceiver::logger_type logger;
+ auto * recorder = new RecordingTransceiverBase {&logger};
+ TxInhibitTransceiver transceiver {
+ &logger, std::unique_ptr<Transceiver> {recorder}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (12);
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ requested.tune (true);
+ transceiver.set (requested, 13);
+ QCOMPARE (recorder->operations.mid (recorder->operations.size () - 2),
+ QStringList ({QStringLiteral ("tune:1"), QStringLiteral ("ptt:1")}));
+
+ transceiver.tx_inhibit_command (QStringLiteral ("W1AW"), 600, QStringLiteral ("W1AW"));
+ QTRY_COMPARE (recorder->operations.mid (recorder->operations.size () - 2),
+ QStringList ({QStringLiteral ("ptt:0"), QStringLiteral ("tune:0")}));
+
+ transceiver.tx_inhibit_command (QStringLiteral ("W1AW"), 0, QStringLiteral ("W1AW"));
+ QTRY_COMPARE (recorder->operations.mid (recorder->operations.size () - 2),
+ QStringList ({QStringLiteral ("tune:1"), QStringLiteral ("ptt:1")}));
+ }
+
+ Q_SLOT void holdBeforeFirstRequestDoesNotForwardAnOfflineState ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (15);
+
+ transceiver.tx_inhibit_command (QStringLiteral ("W1AW"), 600, QStringLiteral ("W1AW"));
+ QTRY_VERIFY (status.last ().at (1).toBool ());
+ QCOMPARE (fake->set_calls, 0);
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ transceiver.set (requested, 16);
+ QVERIFY (fake->last_state.online ());
+ QVERIFY (!fake->last_state.ptt ());
+ }
+
+ Q_SLOT void releasesAreScopedToControllerIdentity ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (20);
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ transceiver.set (requested, 21);
+
+ transceiver.tx_inhibit_command (QStringLiteral ("OWNER"), 600, QStringLiteral ("OWNER"));
+ QTRY_VERIFY (!fake->last_state.ptt ());
+
+ transceiver.tx_inhibit_command (QStringLiteral ("OTHER"), 0, QStringLiteral ("OTHER"));
+ QTest::qWait (30);
+ QVERIFY (!fake->last_state.ptt ());
+
+ transceiver.tx_inhibit_command (QStringLiteral ("OTHER"), 600, QStringLiteral ("OWNER"));
+ QTRY_COMPARE (status.last ().at (3).toUInt (), 2u);
+ transceiver.tx_inhibit_command (QStringLiteral ("OWNER"), 0, QStringLiteral ("OWNER"));
+ QTest::qWait (30);
+ QVERIFY (!fake->last_state.ptt ());
+
+ transceiver.tx_inhibit_command (QStringLiteral ("OTHER"), 0, QStringLiteral ("OTHER"));
+ QTRY_VERIFY (fake->last_state.ptt ());
+ }
+
+ Q_SLOT void excessHoldersRemainBoundedAndFailClosed ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (22);
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ transceiver.set (requested, 23);
+
+ for (auto i = 0; i < TxInhibitTransceiver::maximum_tracked_holds; ++i)
+ {
+ transceiver.tx_inhibit_command (QStringLiteral ("HOLDER_%1").arg (i), 1200, QStringLiteral ("HOLDER_%1").arg (i));
+ }
+ QTRY_COMPARE (status.last ().at (2).toString ().split (QStringLiteral (", ")).size (),
+ TxInhibitTransceiver::maximum_tracked_holds);
+
+ transceiver.tx_inhibit_command (QStringLiteral ("HOLDER_0"), 2400, QStringLiteral ("HOLDER_0"));
+
+ transceiver.tx_inhibit_command (QStringLiteral ("OVERFLOW"), 1800, QStringLiteral ("OVERFLOW"));
+
+ transceiver.tx_inhibit_command (QStringLiteral ("OVERFLOW"), 0, QStringLiteral ("OVERFLOW"));
+
+ QTRY_COMPARE_WITH_TIMEOUT (status.last ().at (2).toString (),
+ QStringLiteral ("HOLDER_0"), 1800);
+
+ transceiver.tx_inhibit_command (QStringLiteral ("HOLDER_0"), 0, QStringLiteral ("HOLDER_0"));
+ QTRY_VERIFY (status.last ().at (2).toString ().isEmpty ());
+ QVERIFY (status.last ().at (1).toBool ());
+ QVERIFY (!fake->last_state.ptt ());
+ QTRY_VERIFY_WITH_TIMEOUT (fake->last_state.ptt (), 1200);
+ }
+
+ Q_SLOT void leaseExpiresAndClearedIntentDoesNotRekey ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (30);
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ transceiver.set (requested, 31);
+
+ transceiver.tx_inhibit_command (QStringLiteral ("W2SZ"), 100, QStringLiteral ("W2SZ"));
+ QTRY_VERIFY (!fake->last_state.ptt ());
+ QTRY_VERIFY_WITH_TIMEOUT (fake->last_state.ptt (), 300);
+ QCOMPARE (status.last ().at (5).toUInt (), 1u);
+
+ transceiver.tx_inhibit_command (QStringLiteral ("W2SZ"), 600, QStringLiteral ("W2SZ"));
+ QTRY_VERIFY (!fake->last_state.ptt ());
+ requested.ptt (false);
+ transceiver.set (requested, 32);
+ transceiver.tx_inhibit_command (QStringLiteral ("W2SZ"), 0, QStringLiteral ("W2SZ"));
+ QTest::qWait (30);
+ QVERIFY (!fake->last_state.ptt ());
+ }
+
+ Q_SLOT void refreshedHoldExtendsItsDeadline ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (35);
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ transceiver.set (requested, 36);
+
+ transceiver.tx_inhibit_command (QStringLiteral ("W2SZ"), 800, QStringLiteral ("W2SZ"));
+ QTRY_VERIFY (!fake->last_state.ptt ());
+ QTest::qWait (450);
+ transceiver.tx_inhibit_command (QStringLiteral ("W2SZ"), 800, QStringLiteral ("W2SZ"));
+ QTest::qWait (450);
+ QVERIFY (!fake->last_state.ptt ());
+ QTRY_VERIFY_WITH_TIMEOUT (fake->last_state.ptt (), 600);
+ QCOMPARE (status.last ().at (3).toUInt (), 2u);
+ QCOMPARE (status.last ().at (5).toUInt (), 1u);
+ }
+
+ Q_SLOT void stopDoesNotRestorePttFromAnActiveHold ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (37);
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ transceiver.set (requested, 38);
+
+ transceiver.tx_inhibit_command (QStringLiteral ("W2SZ"), 100, QStringLiteral ("W2SZ"));
+ QTRY_VERIFY (!fake->last_state.ptt ());
+ auto const set_calls = fake->set_calls;
+
+ transceiver.stop ();
+ QVERIFY (fake->stopped);
+ QVERIFY (!status.last ().at (0).toBool ());
+ QVERIFY (!status.last ().at (1).toBool ());
+ QTest::qWait (200);
+ QCOMPARE (fake->set_calls, set_calls);
+ QVERIFY (!fake->last_state.ptt ());
+ }
+
+ Q_SLOT void counterOnlyChangesEmitStatus ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (39);
+
+ auto status_count = status.size ();
+
+ transceiver.tx_inhibit_invalid (3);
+ QCOMPARE (status.size (), ++status_count);
+ QCOMPARE (status.last ().at (6).toUInt (), 3u);
+
+ transceiver.tx_inhibit_command (QStringLiteral ("COUNTER"), 0, {});
+ QCOMPARE (status.size (), ++status_count);
+ QCOMPARE (status.last ().at (4).toUInt (), 1u);
+ transceiver.tx_inhibit_command (QStringLiteral ("COUNTER"), 600, {});
+ QCOMPARE (status.size (), ++status_count);
+ transceiver.tx_inhibit_command (QStringLiteral ("COUNTER"), 600, {});
+ QCOMPARE (status.size (), ++status_count);
+ QCOMPARE (status.last ().at (3).toUInt (), 2u);
+ }
+
+ Q_SLOT void pttOffWithChangedTxRequestForwardsFinalState ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (41);
+
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ transceiver.set (requested, 42);
+
+ auto next_request = requested.tx_request ();
+ next_request.mode = QStringLiteral ("JT9");
+ next_request.fast_mode = true;
+ requested.ptt (false);
+ requested.tx_request (next_request);
+ transceiver.set (requested, 43);
+
+ QVERIFY (!fake->last_state.ptt ());
+ QCOMPARE (fake->last_state.tx_request ().mode, QStringLiteral ("JT9"));
+ QVERIFY (fake->last_state.tx_request ().fast_mode);
+ }
+
+ Q_SLOT void txRequestEqualityIncludesAllFields ()
+ {
+ TxEvidence::TxRequest lhs;
+ auto rhs = lhs;
+ QVERIFY (lhs == rhs);
+
+ rhs.mode = QStringLiteral ("JT9");
+ QVERIFY (lhs != rhs);
+ rhs = lhs;
+ rhs.fast_mode = true;
+ QVERIFY (lhs != rhs);
+ rhs = lhs;
+ rhs.channel = AudioDevice::Right;
+ QVERIFY (lhs != rhs);
+ rhs = lhs;
+ rhs.queue_epoch = TxAudioQueueEpoch {1};
+ QVERIFY (lhs != rhs);
+ rhs = lhs;
+ rhs.start_window_open_ms = 1;
+ QVERIFY (lhs != rhs);
+ }
+
+ Q_SLOT void txInhibitCapabilityMatchesPttMethod ()
+ {
+ QVERIFY (TransceiverFactory::supports_tx_inhibit (TransceiverFactory::PTT_method_DTR));
+ QVERIFY (TransceiverFactory::supports_tx_inhibit (TransceiverFactory::PTT_method_RTS));
+ QVERIFY (!TransceiverFactory::supports_tx_inhibit (TransceiverFactory::PTT_method_CAT));
+ QVERIFY (!TransceiverFactory::supports_tx_inhibit (TransceiverFactory::PTT_method_VOX));
+ }
+
+ Q_SLOT void queuedCommandsApplyOnTransceiverThread ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QThread worker;
+ auto * gui_thread = QThread::currentThread ();
+ fake->moveToThread (&worker);
+ transceiver.moveToThread (&worker);
+ connect (this, &TestTxInhibitTransceiver::command,
+ &transceiver, &TxInhibitTransceiver::tx_inhibit_command, Qt::QueuedConnection);
+ worker.start ();
+ QMetaObject::invokeMethod (&transceiver, [&] {
+ transceiver.start (70);
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ transceiver.set (requested, 71);
+ }, Qt::BlockingQueuedConnection);
+ Q_EMIT command (QStringLiteral ("KEY"), 600, {});
+ bool held_on_worker {false};
+ QMetaObject::invokeMethod (&transceiver, [&] {
+ held_on_worker = !fake->last_state.ptt () && fake->last_set_thread == &worker;
+ }, Qt::BlockingQueuedConnection);
+ Q_EMIT command (QStringLiteral ("KEY"), 0, {});
+ bool released_on_worker {false};
+ QMetaObject::invokeMethod (&transceiver, [&] {
+ released_on_worker = fake->last_state.ptt () && fake->last_set_thread == &worker;
+ transceiver.stop ();
+ fake->moveToThread (gui_thread);
+ transceiver.moveToThread (gui_thread);
+ }, Qt::BlockingQueuedConnection);
+ worker.quit ();
+ worker.wait ();
+ QVERIFY (held_on_worker);
+ QVERIFY (released_on_worker);
+ }
+
+ Q_SLOT void noHoldAllowsPttAndTune ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ QSignalSpy status {&transceiver, &TxInhibitTransceiver::statusChanged};
+ transceiver.start (50);
+ QVERIFY (fake->started);
+ QVERIFY (status.last ().at (0).toBool ());
+ QVERIFY (!status.last ().at (1).toBool ());
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ requested.tune (true);
+ transceiver.set (requested, 51);
+ QVERIFY (fake->last_state.ptt ());
+ QVERIFY (fake->last_state.tune ());
+ requested.ptt (false);
+ requested.tune (false);
+ transceiver.set (requested, 52);
+ QVERIFY (!fake->last_state.ptt ());
+ QVERIFY (!fake->last_state.tune ());
+ }
+
+ Q_SLOT void endedTuneAndUpdatedMetadataDoNotRestartAfterRelease ()
+ {
+ auto * fake = new FakeInhibitTransceiver;
+ TxInhibitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {fake}};
+ transceiver.start (60);
+ Transceiver::TransceiverState requested;
+ requested.online (true);
+ requested.ptt (true);
+ requested.tune (true);
+ transceiver.set (requested, 61);
+ transceiver.tx_inhibit_command (QStringLiteral ("KEY"), 600, {});
+ requested.ptt (false);
+ requested.tune (false);
+ auto request = requested.tx_request ();
+ request.mode = QStringLiteral ("JT9");
+ request.fast_mode = true;
+ requested.tx_request (request);
+ transceiver.set (requested, 62);
+ transceiver.tx_inhibit_command (QStringLiteral ("KEY"), 0, {});
+ QVERIFY (!fake->last_state.ptt ());
+ QVERIFY (!fake->last_state.tune ());
+ QVERIFY (fake->last_state.tx_request () == request);
+ }
+
+};
+
+QTEST_MAIN (TestTxInhibitTransceiver)
+#include "test_tx_inhibit_transceiver.moc"
diff --git a/tests/unit/common/test_tx_start_policy.cpp b/tests/unit/common/test_tx_start_policy.cpp
new file mode 100644
index 00000000..255476bb
--- /dev/null
+++ b/tests/unit/common/test_tx_start_policy.cpp
@@ -0,0 +1,108 @@
+#include <QtTest/QtTest>
+
+#include "TxStartPolicy.hpp"
+
+class TestTxStartPolicy final
+ : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void standardMessageModesRequireText ();
+ void generatedPayloadModesDoNotRequireText ();
+ void unknownModesDefaultToStandardMessages ();
+ void missingPayloadStopsOnlyStandardMessageModes ();
+ void canStartTransmitRequiresPayloadAndOpenWindow ();
+ void generatedPayloadModesRespectStartWindow ();
+ void tuningCanStartWithoutPayload ();
+ void rejectedGeneratedMessageBlocksTransmit ();
+};
+
+void TestTxStartPolicy::standardMessageModesRequireText ()
+{
+ for (auto const& mode : {"FT8", "FT4", "MSK144", "Q65", "JT65", "JT4", "FST4"})
+ {
+ QVERIFY (requires_standard_tx_message (mode));
+ QVERIFY (!tx_payload_ready (mode, 0));
+ QVERIFY (tx_payload_ready (mode, 1));
+ }
+}
+
+void TestTxStartPolicy::generatedPayloadModesDoNotRequireText ()
+{
+ for (auto const& mode : {"Echo", "WSPR", "FST4W", "JTTY"})
+ {
+ QVERIFY (!requires_standard_tx_message (mode));
+ QVERIFY (tx_payload_ready (mode, 0));
+ }
+}
+
+void TestTxStartPolicy::unknownModesDefaultToStandardMessages ()
+{
+ for (auto const& mode : {"", "Unknown"})
+ {
+ QVERIFY (requires_standard_tx_message (mode));
+ QVERIFY (!tx_payload_ready (mode, 0));
+ QVERIFY (tx_payload_ready (mode, 1));
+ }
+}
+
+void TestTxStartPolicy::missingPayloadStopsOnlyStandardMessageModes ()
+{
+ QVERIFY (should_stop_for_missing_tx_payload ("FT8", 0, false));
+ QVERIFY (!should_stop_for_missing_tx_payload ("FT8", 1, false));
+ QVERIFY (!should_stop_for_missing_tx_payload ("Echo", 0, false));
+ QVERIFY (!should_stop_for_missing_tx_payload ("WSPR", 0, false));
+ QVERIFY (!should_stop_for_missing_tx_payload ("FST4W", 0, false));
+ QVERIFY (!should_stop_for_missing_tx_payload ("JTTY", 0, false));
+ QVERIFY (!should_stop_for_missing_tx_payload ("FT8", 0, true));
+}
+
+void TestTxStartPolicy::canStartTransmitRequiresPayloadAndOpenWindow ()
+{
+ QVERIFY (!can_start_transmit ("FT8", true, 0.5, 0, false));
+ QVERIFY (can_start_transmit ("FT8", true, 0.5, 1, false));
+ QVERIFY (!can_start_transmit ("FT8", true, 0.75, 1, false));
+ QVERIFY (!can_start_transmit ("FT8", false, 0.5, 1, false));
+
+ QVERIFY (can_start_transmit ("Echo", true, 0.5, 0, false));
+ QVERIFY (!can_start_transmit ("Echo", false, 0.5, 0, false));
+ QVERIFY (can_start_transmit ("WSPR", true, 0.5, 0, false));
+ QVERIFY (can_start_transmit ("FST4W", true, 0.5, 0, false));
+
+ QVERIFY (can_start_transmit ("JTTY", false, 0.95, 0, false));
+}
+
+void TestTxStartPolicy::generatedPayloadModesRespectStartWindow ()
+{
+ QVERIFY (can_start_transmit ("Echo", true, 0.5, 0, false));
+ QVERIFY (!can_start_transmit ("Echo", true, TxStartLatestPeriodFraction, 0, false));
+ QVERIFY (!can_start_transmit ("Echo", true, 0.8, 0, false));
+ QVERIFY (!can_start_transmit ("WSPR", true, TxStartLatestPeriodFraction, 0, false));
+ QVERIFY (!can_start_transmit ("FST4W", true, 0.8, 0, false));
+ QVERIFY (can_start_transmit ("JTTY", false, 0.95, 0, false));
+}
+
+void TestTxStartPolicy::tuningCanStartWithoutPayload ()
+{
+ QVERIFY (can_start_transmit ("FT8", false, 0.95, 0, true));
+}
+
+void TestTxStartPolicy::rejectedGeneratedMessageBlocksTransmit ()
+{
+ QVERIFY (should_block_generated_transmit ("*** bad message ***", false));
+ QVERIFY (should_block_generated_transmit (
+ QStringLiteral ("*** bad message ***").leftJustified (37, ' '), false));
+
+ QVERIFY (!should_block_generated_transmit ("*** bad message ***", true));
+ QVERIFY (!should_block_generated_transmit ("TUNE", false));
+ QVERIFY (!should_block_generated_transmit ("ECHO", false));
+ QVERIFY (!should_block_generated_transmit (
+ QStringLiteral ("K1ABC W9XYZ R-10").leftJustified (22, ' '), false));
+ QVERIFY (!should_block_generated_transmit (
+ QStringLiteral ("CQ K1ABC FN42").leftJustified (37, ' '), false));
+}
+
+QTEST_MAIN (TestTxStartPolicy)
+
+#include "test_tx_start_policy.moc"
diff --git a/tests/unit/common/test_wait_feature_policy.cpp b/tests/unit/common/test_wait_feature_policy.cpp
new file mode 100644
index 00000000..c50523b6
--- /dev/null
+++ b/tests/unit/common/test_wait_feature_policy.cpp
@@ -0,0 +1,162 @@
+#include <QtTest/QtTest>
+
+#include "WaitFeaturePolicy.hpp"
+
+class TestWaitFeaturePolicy final
+ : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void enableTxWarning_data ();
+ void enableTxWarning ();
+ void waitAndCallEligibility_data ();
+ void waitAndCallEligibility ();
+};
+
+void TestWaitFeaturePolicy::enableTxWarning_data ()
+{
+ QTest::addColumn<QString> ("mode");
+ QTest::addColumn<int> ("specialOperation");
+ QTest::addColumn<bool> ("waitFeaturesEnabled");
+ QTest::addColumn<bool> ("autoSequenceEnabled");
+ QTest::addColumn<bool> ("hasDxCall");
+ QTest::addColumn<bool> ("ncccSprint");
+ QTest::addColumn<int> ("expected");
+
+ using Op = SpecialOperatingActivity;
+ auto addRow = [] (char const * name, QString const& mode, Op operation,
+ bool waitEnabled, bool autoSeq, bool hasCall, bool nccc,
+ EnableTxWarning expected) {
+ QTest::newRow (name) << mode << static_cast<int> (operation) << waitEnabled
+ << autoSeq << hasCall << nccc << static_cast<int> (expected);
+ };
+
+ using Warning = EnableTxWarning;
+ addRow ("arrl-digi-auto-seq", "FT8", Op::ARRL_DIGI, true, true, true, false,
+ Warning::WAIT_AND_REPLY);
+ addRow ("arrl-digi-no-auto-seq", "FT8", Op::ARRL_DIGI, true, false, true, false,
+ Warning::WAIT_AND_REPLY);
+ addRow ("field-day", "FT4", Op::FIELD_DAY, true, true, true, false,
+ Warning::WAIT_AND_REPLY);
+ addRow ("ww-digi-no-auto-seq", "FT4", Op::WW_DIGI, true, false, true, false,
+ Warning::WAIT_AND_REPLY);
+ addRow ("ordinary-no-auto-seq", "Q65", Op::NONE, true, false, true, false,
+ Warning::WAIT_AND_REPLY);
+
+ for (auto const& mode : {"FT8", "FT4", "Q65", "FST4", "MSK144", "JT65", "JT9", "JT4"})
+ {
+ addRow (qPrintable (QString {"supported-%1"}.arg (mode)), mode, Op::NONE,
+ true, true, true, false, Warning::WAIT_AND_REPLY);
+ }
+ for (auto const& mode : {"WSPR", "FST4W", "Echo", "JTTY", "Unknown"})
+ {
+ addRow (qPrintable (QString {"unsupported-%1"}.arg (mode)), mode, Op::NONE,
+ true, true, true, false, Warning::NONE);
+ }
+
+ addRow ("missing-call", "FT8", Op::NONE, true, true, false, false, Warning::NONE);
+ addRow ("wait-features-disabled", "FT8", Op::NONE, false, true, true, false,
+ Warning::NONE);
+ addRow ("fox", "FT8", Op::FOX, true, true, true, false, Warning::NONE);
+ addRow ("nccc-sprint-override", "FT4", Op::NA_VHF, false, false, true, true,
+ Warning::NCCC_SPRINT);
+ addRow ("nccc-wrong-mode", "FT8", Op::NA_VHF, false, false, true, true, Warning::NONE);
+ addRow ("hound-wait-enabled", "FT8", Op::HOUND, true, false, true, false,
+ Warning::HOUND_AUTO_REPLY);
+ addRow ("hound-wait-disabled", "FT8", Op::HOUND, false, false, true, false,
+ Warning::HOUND_AUTO_REPLY);
+ addRow ("hound-without-call", "FT8", Op::HOUND, true, false, false, false,
+ Warning::NONE);
+ addRow ("non-ft8-hound", "FT4", Op::HOUND, true, true, true, false,
+ Warning::NONE);
+}
+
+void TestWaitFeaturePolicy::enableTxWarning ()
+{
+ QFETCH (QString, mode);
+ QFETCH (int, specialOperation);
+ QFETCH (bool, waitFeaturesEnabled);
+ QFETCH (bool, autoSequenceEnabled);
+ QFETCH (bool, hasDxCall);
+ QFETCH (bool, ncccSprint);
+ QFETCH (int, expected);
+
+ WaitFeatureContext const context {
+ mode,
+ static_cast<SpecialOperatingActivity> (specialOperation),
+ waitFeaturesEnabled,
+ autoSequenceEnabled,
+ hasDxCall,
+ ncccSprint
+ };
+ QCOMPARE (static_cast<int> (enable_tx_warning (context)), expected);
+}
+
+void TestWaitFeaturePolicy::waitAndCallEligibility_data ()
+{
+ QTest::addColumn<QString> ("mode");
+ QTest::addColumn<int> ("specialOperation");
+ QTest::addColumn<bool> ("waitFeaturesEnabled");
+ QTest::addColumn<bool> ("autoSequenceEnabled");
+ QTest::addColumn<bool> ("hasDxCall");
+ QTest::addColumn<bool> ("expectedArming");
+ QTest::addColumn<bool> ("expectedWarning");
+
+ using Op = SpecialOperatingActivity;
+ auto addRow = [] (char const * name, QString const& mode, Op operation,
+ bool waitEnabled, bool autoSeq, bool hasCall,
+ bool expectedArming, bool expectedWarning) {
+ QTest::newRow (name) << mode << static_cast<int> (operation) << waitEnabled
+ << autoSeq << hasCall << expectedArming << expectedWarning;
+ };
+
+ for (auto const& mode : {"FT8", "FT4", "Q65", "FST4", "MSK144"})
+ {
+ addRow (qPrintable (QString {"ordinary-%1"}.arg (mode)), mode, Op::NONE,
+ true, true, true, true, true);
+ }
+ for (auto const& mode : {"JT65", "JT9", "JT4", "WSPR"})
+ {
+ addRow (qPrintable (QString {"unsupported-%1"}.arg (mode)), mode, Op::NONE,
+ true, true, true, false, false);
+ }
+
+ addRow ("missing-call", "FT8", Op::NONE, true, true, false, false, false);
+ addRow ("ft8-hound-with-call", "FT8", Op::HOUND, true, true, true, true, true);
+ addRow ("ft8-hound-no-call", "FT8", Op::HOUND, true, true, false, true, false);
+ addRow ("non-ft8-hound-with-call", "FT4", Op::HOUND, true, true, true, false, false);
+ addRow ("ft4-hound-no-call", "FT4", Op::HOUND, true, true, false, false, false);
+ addRow ("auto-seq-disabled", "FT8", Op::NONE, true, false, true, false, false);
+ addRow ("wait-features-disabled", "FT8", Op::NONE, false, true, true, false, false);
+ addRow ("arrl-digi", "FT8", Op::ARRL_DIGI, true, true, true, false, false);
+ addRow ("field-day", "FT4", Op::FIELD_DAY, true, true, true, false, false);
+ addRow ("nccc-sprint", "FT4", Op::NA_VHF, true, true, true, false, false);
+ addRow ("fox", "FT8", Op::FOX, true, true, true, false, false);
+}
+
+void TestWaitFeaturePolicy::waitAndCallEligibility ()
+{
+ QFETCH (QString, mode);
+ QFETCH (int, specialOperation);
+ QFETCH (bool, waitFeaturesEnabled);
+ QFETCH (bool, autoSequenceEnabled);
+ QFETCH (bool, hasDxCall);
+ QFETCH (bool, expectedArming);
+ QFETCH (bool, expectedWarning);
+
+ WaitFeatureContext const context {
+ mode,
+ static_cast<SpecialOperatingActivity> (specialOperation),
+ waitFeaturesEnabled,
+ autoSequenceEnabled,
+ hasDxCall,
+ false
+ };
+ QCOMPARE (wait_and_call_arming_eligible (context), expectedArming);
+ QCOMPARE (wait_and_call_warning_eligible (context), expectedWarning);
+}
+
+QTEST_MAIN (TestWaitFeaturePolicy)
+
+#include "test_wait_feature_policy.moc"
diff --git a/tests/unit/common/test_waterfall_scale.cpp b/tests/unit/common/test_waterfall_scale.cpp
new file mode 100644
index 00000000..c4b9a038
--- /dev/null
+++ b/tests/unit/common/test_waterfall_scale.cpp
@@ -0,0 +1,267 @@
+#include <cmath>
+#include <limits>
+
+#include <QtTest/QtTest>
+
+#include "widgets/WaterfallScale.hpp"
+
+class TestWaterfallScale final
+ : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void frequencyToPixelClampsAtVisibleEndpoints ();
+ void pixelToFrequencyRemainsUnclamped ();
+ void conversionsRoundTripAtPixelResolution ();
+ void supportedConfigurationsPreserveScaleArithmetic ();
+ void emptyScaleQueriesAreSafe ();
+ void derivedValuesUpdateAfterEveryMutation ();
+ void maximumFrequencyPreservesFiveKilohertzRounding ();
+ void majorDivisionThresholdsPreserveStrictBoundaries ();
+ void gridLayoutPreservesAlignedLabelsAndCounts ();
+ void gridLayoutPreservesNonAlignedLabelOrigin ();
+ void divisionCountsIgnoreTinyFloatingPointOvershoot ();
+ void majorTickPositionsUseFullPrecision ();
+ void twoHundredHertzDivisionsUseFourMinorTicks ();
+};
+
+namespace
+{
+ WaterfallScale scaleWith(double hzPerPixel, int width = 1000,
+ int startHz = 0)
+ {
+ WaterfallScale scale;
+ scale.setWidth(width);
+ scale.setStartHz(startHz);
+ scale.setFftBinWidthHz(hzPerPixel);
+ return scale;
+ }
+}
+
+void TestWaterfallScale::frequencyToPixelClampsAtVisibleEndpoints ()
+{
+ auto scale = scaleWith(0.5, 1000, 200);
+ scale.setBinsPerPixel(4);
+
+ QCOMPARE(scale.spanHz(), 2000.0f);
+ QCOMPARE(scale.xFromFreqHz(200.0f), 0);
+ QCOMPARE(scale.xFromFreqHz(2200.0f), 1000);
+ QCOMPARE(scale.xFromFreqHz(-1000.0f), 0);
+ QCOMPARE(scale.xFromFreqHz(4000.0f), 1000);
+ QCOMPARE(scale.xFromFreqHz(201.0f), 1);
+}
+
+void TestWaterfallScale::pixelToFrequencyRemainsUnclamped ()
+{
+ auto scale = scaleWith(2.0, 1000, 200);
+
+ QCOMPARE(scale.freqHzFromX(-10), 180.0f);
+ QCOMPARE(scale.freqHzFromX(0), 200.0f);
+ QCOMPARE(scale.freqHzFromX(1000), 2200.0f);
+ QCOMPARE(scale.freqHzFromX(1010), 2220.0f);
+}
+
+void TestWaterfallScale::conversionsRoundTripAtPixelResolution ()
+{
+ auto scale = scaleWith(1500.0 / 2048.0, 1537, 125);
+ scale.setBinsPerPixel(7);
+
+ for(int x : {0, 1, 127, 768, 1536, 1537}) {
+ QCOMPARE(scale.xFromFreqHz(scale.freqHzFromX(x)), x);
+ }
+
+ double const halfPixel = scale.hzPerPixel() / 2.0;
+ for(float frequency : {125.0f, 126.0f, 999.25f, 4000.0f, 7999.0f}) {
+ int const x = scale.xFromFreqHz(frequency);
+ if(x > 0 && x < scale.width()) {
+ QVERIFY(std::abs(scale.freqHzFromX(x) - frequency) <= halfPixel);
+ }
+ }
+}
+
+void TestWaterfallScale::supportedConfigurationsPreserveScaleArithmetic ()
+{
+ double const fftBinWidths[] = {
+ 1500.0 / 2048.0,
+ 1500.0 / 6144.0,
+ 1500.0 / 12288.0,
+ 1500.0 / 32768.0
+ };
+
+ for(double fftBinWidth : fftBinWidths) {
+ for(int startHz : {0, 100, 2500}) {
+ for(int width : {50, 1000, 2048}) {
+ for(int binsPerPixel : {1, 4, 1000}) {
+ WaterfallScale scale;
+ scale.setWidth(width);
+ scale.setStartHz(startHz);
+ scale.setBinsPerPixel(binsPerPixel);
+ scale.setFftBinWidthHz(fftBinWidth);
+
+ QCOMPARE(scale.width(), width);
+ QCOMPARE(scale.startHz(), startHz);
+ QCOMPARE(scale.binsPerPixel(), binsPerPixel);
+ QCOMPARE(scale.fftBinWidthHz(), fftBinWidth);
+ QCOMPARE(scale.hzPerPixel(), binsPerPixel * fftBinWidth);
+ QCOMPARE(scale.spanHz(), float(width * binsPerPixel * fftBinWidth));
+ QCOMPARE(scale.freqHzFromX(width),
+ float(startHz + width * binsPerPixel * fftBinWidth));
+ }
+ }
+ }
+ }
+
+ WaterfallScale scale;
+ scale.setBinsPerPixel(0);
+ QCOMPARE(scale.binsPerPixel(), 1);
+ scale.setBinsPerPixel(-100);
+ QCOMPARE(scale.binsPerPixel(), 1);
+
+ scale.setWidth(-100);
+ QCOMPARE(scale.width(), 0);
+}
+
+void TestWaterfallScale::emptyScaleQueriesAreSafe ()
+{
+ WaterfallScale scale;
+
+ QCOMPARE(scale.spanHz(), 0.0f);
+ QCOMPARE(scale.xFromFreqHz(5000.0f), 0);
+ QCOMPARE(scale.maxFreqHz(), 0);
+
+ scale.setStartHz(200);
+ QCOMPARE(scale.xFromFreqHz(5000.0f), 0);
+ QCOMPARE(scale.maxFreqHz(), 200);
+}
+
+void TestWaterfallScale::derivedValuesUpdateAfterEveryMutation ()
+{
+ auto scale = scaleWith(1.0, 1000, 0);
+
+ QCOMPARE(scale.spanHz(), 1000.0f);
+ QCOMPARE(scale.maxFreqHz(), 1000);
+
+ scale.setWidth(2000);
+ QCOMPARE(scale.spanHz(), 2000.0f);
+ QCOMPARE(scale.maxFreqHz(), 2000);
+
+ scale.setStartHz(1000);
+ QCOMPARE(scale.freqHzFromX(0), 1000.0f);
+ QCOMPARE(scale.maxFreqHz(), 3000);
+
+ scale.setBinsPerPixel(2);
+ QCOMPARE(scale.spanHz(), 4000.0f);
+ QCOMPARE(scale.maxFreqHz(), 5000);
+
+ scale.setFftBinWidthHz(0.25);
+ QCOMPARE(scale.spanHz(), 1000.0f);
+ QCOMPARE(scale.maxFreqHz(), 2000);
+}
+
+void TestWaterfallScale::maximumFrequencyPreservesFiveKilohertzRounding ()
+{
+ QCOMPARE(scaleWith(1.0, 4999).maxFreqHz(), 4999);
+ QCOMPARE(scaleWith(1.0, 5000).maxFreqHz(), 5000);
+ QCOMPARE(scaleWith(1.0, 6000).maxFreqHz(), 5000);
+ QCOMPARE(scaleWith(2.0, 1000, 4000).maxFreqHz(), 5000);
+ QCOMPARE(scaleWith(2.0, 1000, 4999).maxFreqHz(), 5001);
+ QCOMPARE(scaleWith(3.0, 1666).maxFreqHz(), 4998);
+}
+
+void TestWaterfallScale::majorDivisionThresholdsPreserveStrictBoundaries ()
+{
+ struct Threshold
+ {
+ float spanHz;
+ int atBoundary;
+ int aboveBoundary;
+ };
+
+ Threshold const thresholds[] = {
+ {100.0f, 10, 20},
+ {250.0f, 20, 50},
+ {500.0f, 50, 100},
+ {1000.0f, 100, 200},
+ {2500.0f, 200, 500}
+ };
+
+ for(auto const& threshold : thresholds) {
+ auto scale = scaleWith(threshold.spanHz, 1);
+ QCOMPARE(scale.gridLayout().majorSpacingHz, threshold.atBoundary);
+
+ scale.setFftBinWidthHz(std::nextafter(
+ threshold.spanHz, std::numeric_limits<float>::infinity()));
+ QCOMPARE(scale.gridLayout().majorSpacingHz, threshold.aboveBoundary);
+ }
+}
+
+void TestWaterfallScale::gridLayoutPreservesAlignedLabelsAndCounts ()
+{
+ auto const grid = scaleWith(1.0, 1000, 200).gridLayout();
+
+ QCOMPARE(grid.majorSpacingHz, 100);
+ QCOMPARE(grid.pixelsPerDivision, 100.0);
+ QCOMPARE(grid.overlayDivisionCount, 11);
+ QCOMPARE(grid.scaleDivisionCount, 10);
+ QCOMPARE(grid.firstMajorDivisionOffset, 0.0);
+ QCOMPARE(grid.verticalGridOffsetPixels, 0);
+ QCOMPARE(grid.minorDivisionCount, 5);
+ QCOMPARE(grid.labels.size(), 11);
+ QCOMPARE(grid.labels[0], QStringLiteral("200"));
+ QCOMPARE(grid.labels[1], QStringLiteral("300"));
+ QCOMPARE(grid.labels[10], QStringLiteral("1200"));
+}
+
+void TestWaterfallScale::gridLayoutPreservesNonAlignedLabelOrigin ()
+{
+ auto const grid = scaleWith(1.0, 1000, 225).gridLayout();
+
+ QCOMPARE(grid.majorSpacingHz, 100);
+ QCOMPARE(grid.firstMajorDivisionOffset, 0.75);
+ QCOMPARE(grid.verticalGridOffsetPixels, 25);
+ QCOMPARE(grid.labels[0], QStringLiteral("300"));
+ QCOMPARE(grid.labels[1], QStringLiteral("400"));
+ QCOMPARE(grid.labels.last(), QStringLiteral("1300"));
+}
+
+void TestWaterfallScale::divisionCountsIgnoreTinyFloatingPointOvershoot ()
+{
+ auto scale = scaleWith(3000.025, 1);
+ QCOMPARE(scale.gridLayout().majorSpacingHz, 500);
+ QCOMPARE(scale.gridLayout().scaleDivisionCount, 6);
+ QCOMPARE(scale.gridLayout().overlayDivisionCount, 7);
+
+ scale.setFftBinWidthHz(3000.1);
+ QCOMPARE(scale.gridLayout().scaleDivisionCount, 7);
+ QCOMPARE(scale.gridLayout().overlayDivisionCount, 8);
+}
+
+void TestWaterfallScale::majorTickPositionsUseFullPrecision ()
+{
+ WaterfallScale scale;
+ scale.setWidth(1181);
+ scale.setStartHz(4349);
+ scale.setBinsPerPixel(213);
+ scale.setFftBinWidthHz(1500.0 / 12288.0);
+ auto const grid = scale.gridLayout();
+
+ QCOMPARE(grid.majorSpacingHz, 500);
+ QCOMPARE(grid.firstMajorDivisionOffset, 151.0 / 500.0);
+ QCOMPARE(int((grid.firstMajorDivisionOffset + 53)
+ * grid.pixelsPerDivision), 1024);
+}
+
+void TestWaterfallScale::twoHundredHertzDivisionsUseFourMinorTicks ()
+{
+ auto const grid = scaleWith(1.5, 1000).gridLayout();
+
+ QCOMPARE(grid.majorSpacingHz, 200);
+ QCOMPARE(grid.minorDivisionCount, 4);
+ QCOMPARE(grid.overlayDivisionCount, 9);
+ QCOMPARE(grid.scaleDivisionCount, 8);
+}
+
+QTEST_APPLESS_MAIN (TestWaterfallScale)
+
+#include "test_waterfall_scale.moc"
diff --git a/tests/unit/common/test_wf_palette.cpp b/tests/unit/common/test_wf_palette.cpp
new file mode 100644
index 00000000..2e652a30
--- /dev/null
+++ b/tests/unit/common/test_wf_palette.cpp
@@ -0,0 +1,113 @@
+#include <QtTest>
+
+#include <stdexcept>
+
+#include <QColor>
+#include <QDir>
+#include <QFile>
+#include <QString>
+#include <QTemporaryFile>
+#include <QTextStream>
+#include <QUuid>
+
+#include "WFPalette.hpp"
+
+class TestWFPalette
+ : public QObject
+{
+ Q_OBJECT
+
+private:
+ QString write_palette (QString const& body)
+ {
+ QTemporaryFile file;
+ file.setAutoRemove (false);
+ if (!file.open ())
+ {
+ throw std::runtime_error {"failed to open temporary palette file"};
+ }
+
+ QTextStream out {&file};
+ out << body;
+ out.flush ();
+ if (out.status () != QTextStream::Ok)
+ {
+ throw std::runtime_error {"failed to write temporary palette file"};
+ }
+
+ auto const name = file.fileName ();
+ file.close ();
+ return name;
+ }
+
+ QString palette_body (int lines)
+ {
+ QString body;
+ QTextStream out {&body};
+ for (int i {0}; i < lines; ++i)
+ {
+ out << i % 256 << ';' << (i + 1) % 256 << ';' << (i + 2) % 256 << '\n';
+ }
+ return body;
+ }
+
+ void remove_file (QString const& file_name)
+ {
+ QVERIFY (QFile::remove (file_name));
+ }
+
+private Q_SLOTS:
+ void constructor_accepts_256_colour_palette ()
+ {
+ auto const file_name = write_palette (palette_body (256));
+
+ WFPalette palette {file_name};
+
+ QCOMPARE (palette.colours ().size (), 256);
+ QCOMPARE (palette.colours ().front (), QColor (0, 1, 2));
+ QCOMPARE (palette.colours ().back (), QColor (255, 0, 1));
+ QCOMPARE (palette.interpolate ().size (), 256);
+
+ remove_file (file_name);
+ }
+
+ void constructor_rejects_257_colour_palette ()
+ {
+ auto const file_name = write_palette (palette_body (257));
+
+ QVERIFY_EXCEPTION_THROWN (WFPalette {file_name}, std::runtime_error);
+
+ remove_file (file_name);
+ }
+
+ void constructor_rejects_invalid_triplet ()
+ {
+ auto const file_name = write_palette ("0;1\n");
+
+ QVERIFY_EXCEPTION_THROWN (WFPalette {file_name}, std::runtime_error);
+
+ remove_file (file_name);
+ }
+
+ void constructor_rejects_invalid_colour_component ()
+ {
+ auto const file_name = write_palette ("0;1;256\n");
+
+ QVERIFY_EXCEPTION_THROWN (WFPalette {file_name}, std::runtime_error);
+
+ remove_file (file_name);
+ }
+
+ void constructor_rejects_missing_file ()
+ {
+ auto const file_name = QDir::temp ().absoluteFilePath (
+ QUuid::createUuid ().toString (QUuid::WithoutBraces) + ".pal");
+ QVERIFY (!QFile::exists (file_name));
+
+ QVERIFY_EXCEPTION_THROWN (WFPalette {file_name}, std::runtime_error);
+ }
+};
+
+QTEST_MAIN (TestWFPalette);
+
+#include "test_wf_palette.moc"