diff options
Diffstat (limited to 'tests/unit/common')
| -rw-r--r-- | tests/unit/common/CMakeLists.txt | 49 | ||||
| -rw-r--r-- | tests/unit/common/test_active_stations.cpp | 31 | ||||
| -rw-r--r-- | tests/unit/common/test_configuration_dialog_layout.cpp | 41 | ||||
| -rw-r--r-- | tests/unit/common/test_configuration_radio.cpp | 237 | ||||
| -rw-r--r-- | tests/unit/common/test_decode_highlighting_model.cpp | 526 | ||||
| -rw-r--r-- | tests/unit/common/test_frequency_list.cpp | 294 | ||||
| -rw-r--r-- | tests/unit/common/test_frequency_suggestions.cpp | 200 | ||||
| -rw-r--r-- | tests/unit/common/test_log_window_deletion.cpp | 202 | ||||
| -rw-r--r-- | tests/unit/common/test_qt_helpers.cpp | 33 | ||||
| -rw-r--r-- | tests/unit/common/test_radio_callsign.cpp | 128 |
10 files changed, 1741 insertions, 0 deletions
diff --git a/tests/unit/common/CMakeLists.txt b/tests/unit/common/CMakeLists.txt index 770aa0ec..9c6f0a2d 100644 --- a/tests/unit/common/CMakeLists.txt +++ b/tests/unit/common/CMakeLists.txt @@ -1,3 +1,14 @@ +add_executable (test_radio_callsign test_radio_callsign.cpp) +target_link_libraries (test_radio_callsign wsjt_qt Qt5::Test) +add_test (NAME test_radio_callsign COMMAND test_radio_callsign) + +add_executable (test_frequency_list + test_frequency_list.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp +) +target_link_libraries (test_frequency_list wsjt_qt Boost::log_setup Qt5::Test) +add_test (NAME test_frequency_list COMMAND test_frequency_list) + add_executable (test_qt_helpers test_qt_helpers.cpp ${CMAKE_SOURCE_DIR}/qt_helpers.cpp @@ -6,6 +17,19 @@ 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_configuration_radio test_configuration_radio.cpp) +add_dependencies (test_configuration_radio wsjt_qt_autogen) +target_include_directories (test_configuration_radio PRIVATE + ${CMAKE_BINARY_DIR} + ${CMAKE_BINARY_DIR}/wsjt_qt_autogen/include + ${CMAKE_BINARY_DIR}/wsjt_qt_autogen/include_$<CONFIG>) +target_link_libraries (test_configuration_radio wsjt_qt wsjt_cxx wsjt_fort_common + Boost::log_setup Qt5::Test) +add_test (NAME test_configuration_radio COMMAND test_configuration_radio) +set_tests_properties (test_configuration_radio PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + TIMEOUT 60) + add_executable (test_callsign_validator test_callsign_validator.cpp ${CMAKE_SOURCE_DIR}/validators/CallsignValidator.cpp @@ -49,6 +73,12 @@ add_executable (test_wf_palette target_link_libraries (test_wf_palette wsjt_qt Qt5::Test) add_test (NAME test_wf_palette COMMAND test_wf_palette) +add_executable (test_decode_highlighting_model + test_decode_highlighting_model.cpp +) +target_link_libraries (test_decode_highlighting_model wsjt_qt Qt5::Test) +add_test (NAME test_decode_highlighting_model COMMAND test_decode_highlighting_model) + add_executable (test_waterfall_scale test_waterfall_scale.cpp ) @@ -97,6 +127,17 @@ 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_log_window_deletion + test_log_window_deletion.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp +) +target_link_libraries (test_log_window_deletion wsjt_qt wsjt_cxx wsjt_fort_common + Boost::log_setup Qt5::Test Qt5::Widgets Qt5::Sql) +add_test (NAME test_log_window_deletion COMMAND test_log_window_deletion) +set_tests_properties (test_log_window_deletion PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + TIMEOUT 60) + add_executable (test_rig_frequency_change_policy test_rig_frequency_change_policy.cpp ) @@ -183,6 +224,14 @@ add_executable (test_frequency_editors 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_frequency_suggestions + test_frequency_suggestions.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp +) +target_link_libraries (test_frequency_suggestions wsjt_qt Boost::log_setup Qt5::Test Qt5::Widgets) +add_test (NAME test_frequency_suggestions COMMAND test_frequency_suggestions) +set_tests_properties (test_frequency_suggestions PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + add_executable (test_decoded_message_reaction test_decoded_message_reaction.cpp ) diff --git a/tests/unit/common/test_active_stations.cpp b/tests/unit/common/test_active_stations.cpp index d53f58e0..10b262d2 100644 --- a/tests/unit/common/test_active_stations.cpp +++ b/tests/unit/common/test_active_stations.cpp @@ -6,6 +6,7 @@ #include <QTemporaryDir> #include "widgets/activeStations.h" +#include "lib/qra/q65/q65_limits.h" class TestActiveStations : public QObject { @@ -14,6 +15,7 @@ class TestActiveStations : public QObject private slots: void transitions(); void clickRouting(); + void fullPileupSelection(); }; void TestActiveStations::transitions() @@ -82,5 +84,34 @@ void TestActiveStations::clickRouting() } } +void TestActiveStations::fullPileupSelection() +{ + QTemporaryDir directory; + QVERIFY(directory.isValid()); + QSettings settings(directory.filePath("settings.ini"), QSettings::IniFormat); + ActiveStations widget(&settings, QFont{}); + QSignalSpy station(&widget, SIGNAL(callSandP(int))); + QVERIFY(station.isValid()); + auto editor = widget.findChild<QPlainTextEdit *>("RecentStationsPlainTextEdit"); + QVERIFY(editor); + QString rows; + for (int row = 1; row <= Q65_CALLER_CAPACITY; ++row) { + rows += QString("%1. 1500 K1ABC FN42 10 0.0\n").arg(row, 2); + } + widget.setClickOK(false); + widget.displayRecentStations(ActiveStations::DisplayMode::Q65Pileup, rows); + auto cursor = editor->textCursor(); + cursor.movePosition(QTextCursor::Start); + for (int row = 1; row < Q65_CALLER_CAPACITY; ++row) { + QVERIFY(cursor.movePosition(QTextCursor::NextBlock)); + } + editor->setTextCursor(cursor); + station.clear(); + widget.setClickOK(true); + QVERIFY(QMetaObject::invokeMethod(&widget, "on_textEdit_clicked", Qt::DirectConnection)); + QCOMPARE(station.count(), 1); + QCOMPARE(station.at(0).at(0).toInt(), Q65_CALLER_CAPACITY); +} + QTEST_MAIN(TestActiveStations) #include "test_active_stations.moc" diff --git a/tests/unit/common/test_configuration_dialog_layout.cpp b/tests/unit/common/test_configuration_dialog_layout.cpp index 019147af..b66d5724 100644 --- a/tests/unit/common/test_configuration_dialog_layout.cpp +++ b/tests/unit/common/test_configuration_dialog_layout.cpp @@ -241,9 +241,12 @@ void TestConfigurationDialogLayout::compactControlsKeepNaturalGeometry () { 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, {640, 480}); ui.configuration_tabs->setCurrentWidget (ui.general_tab); @@ -268,6 +271,30 @@ void TestConfigurationDialogLayout::compactControlsKeepNaturalGeometry () QVERIFY (isFullyInside (control, group)); } } + + ui.configuration_tabs->setCurrentWidget (ui.colors_tab); + for (int width : {420, 640, 1100}) + { + dialog.resize (width, 480); + settleLayouts (); + QCOMPARE (dialog.width (), width); + auto * up = ui.move_highlighting_up_push_button; + auto * down = ui.move_highlighting_down_push_button; + for (auto * button : {up, down}) + { + QVERIFY (button->width () >= button->minimumSizeHint ().width ()); + QVERIFY2 (button->width () <= button->sizeHint ().width () + 2, + qPrintable (QString {"%1 dialogWidth=%2 actual=%3 hint=%4"} + .arg (button->objectName ()).arg (width) + .arg (sizeText (button->size ()), sizeText (button->sizeHint ())))); + QVERIFY (isFullyInside (button, ui.groupBox_12)); + } + QVERIFY (qAbs (up->geometry ().center ().y () + - down->geometry ().center ().y ()) <= 2); + QVERIFY (ui.highlighting_actions_tool_button->geometry ().right () + < up->geometry ().left ()); + QVERIFY (up->geometry ().right () < down->geometry ().left ()); + } } void TestConfigurationDialogLayout::constrainedDialogKeepsNavigationAndActionsReachable_data () @@ -473,6 +500,20 @@ void TestConfigurationDialogLayout::keyboardFocusRevealsOffscreenControls () QTRY_VERIFY (isFullyVisible (left_side_control, filters_scroll_area)); QCOMPARE (geometryIn (ui.configuration_dialog_button_box, &dialog), filters_button_box_geometry); + + ui.configuration_tabs->setCurrentWidget (ui.colors_tab); + settleLayouts (); + auto * colors_scroll_area = SettingsDialogLayout::pageScrollArea (ui.colors_tab); + ui.move_highlighting_up_push_button->setFocus (Qt::TabFocusReason); + QTRY_COMPARE (QApplication::focusWidget (), ui.move_highlighting_up_push_button); + QTRY_VERIFY (isFullyVisible (ui.move_highlighting_up_push_button, colors_scroll_area)); + QCOMPARE (ui.move_highlighting_up_push_button->nextInFocusChain (), + ui.move_highlighting_down_push_button); + QCOMPARE (ui.move_highlighting_down_push_button->previousInFocusChain (), + ui.move_highlighting_up_push_button); + ui.move_highlighting_down_push_button->setFocus (Qt::TabFocusReason); + QTRY_COMPARE (QApplication::focusWidget (), ui.move_highlighting_down_push_button); + QTRY_VERIFY (isFullyVisible (ui.move_highlighting_down_push_button, colors_scroll_area)); } void TestConfigurationDialogLayout::wheelEventsScrollThePage () diff --git a/tests/unit/common/test_configuration_radio.cpp b/tests/unit/common/test_configuration_radio.cpp new file mode 100644 index 00000000..9df6b2bd --- /dev/null +++ b/tests/unit/common/test_configuration_radio.cpp @@ -0,0 +1,237 @@ +#include "wsjtx_config.h" +#include <QtTest> +#include <QTemporaryDir> + +// Exercise the private dialog and its auto-connected slots without exposing a test API. +#include "Configuration.cpp" +#include "widgets/itoneAndicw.h" + +int volatile itone[MAX_NUM_SYMBOLS] {}; +float gran () { return 0; } + +class TestConfigurationRadio final : public QObject +{ + Q_OBJECT + + using RadioValidationError = Configuration::impl::RadioValidationError; + + QTemporaryDir directory_; + QNetworkAccessManager network_; + std::unique_ptr<QSettings> settings_; + std::unique_ptr<Configuration> configuration_; + QString serial_rig_; + QString network_rig_; + + Configuration::impl& dialog () { return *configuration_->m_; } + Ui::configuration_dialog& ui () { return *dialog ().ui_; } + +private slots: + void initTestCase () + { + register_types (); + QStandardPaths::setTestModeEnabled (true); + QCoreApplication::setApplicationName ("test_configuration_radio"); + QVERIFY (directory_.isValid ()); + } + + void init () + { + settings_.reset (new QSettings {directory_.filePath ("settings.ini"), QSettings::IniFormat}); + settings_->clear (); + configuration_.reset (new Configuration {&network_, QDir {directory_.path ()}, settings_.get (), nullptr}); + auto& d = dialog (); + auto& rigs = const_cast<TransceiverFactory::Transceivers&> (d.transceiver_factory_.supported_transceivers ()); + using Caps = TransceiverFactory::Capabilities; + for (auto it = rigs.cbegin (); it != rigs.cend (); ++it) + { + if (it->port_type_ == Caps::serial) serial_rig_ = it.key (); + if (it->port_type_ == Caps::network) network_rig_ = it.key (); + } + QVERIFY (!serial_rig_.isEmpty ()); + QVERIFY (!network_rig_.isEmpty ()); + // OmniRig's Windows COM transport is unavailable here; use its registered capabilities. + if (!rigs.contains ("OmniRig Rig 1")) + rigs.insert ("OmniRig Rig 1", Caps {99904, Caps::none, true, false, true, true}); + d.enumerate_rigs (); + d.rig_params_.rig_name = serial_rig_; + d.rig_params_.serial_port = "/dev/test-cat"; + d.rig_params_.network_port = "localhost:4532"; + d.rig_params_.ptt_port = "/dev/test-cat"; + d.rig_params_.ptt_type = TransceiverFactory::PTT_method_DTR; + d.rig_params_.handshake = TransceiverFactory::handshake_none; + d.initialize_models (); + // Audio availability is independent of these radio validation cases. + if (ui ().sound_input_combo_box->currentIndex () < 0) + ui ().sound_input_combo_box->addItem ("Test input"); + if (ui ().sound_input_channel_combo_box->currentIndex () < 0) + ui ().sound_input_channel_combo_box->addItem ("Mono"); + if (ui ().sound_output_combo_box->currentIndex () < 0) + ui ().sound_output_combo_box->addItem ("Test output"); + if (d.dns_lookup_id_ > -1) QHostInfo::abortHostLookup (d.dns_lookup_id_); + d.dns_lookup_id_ = -1; + } + + void cleanup () + { + configuration_.reset (); + settings_.reset (); + } + + void proxyCatBecomesExplicitSerialSelection_data () + { + QTest::addColumn<bool> ("rts"); + QTest::newRow ("DTR") << false; + QTest::newRow ("RTS") << true; + } + + void proxyCatBecomesExplicitSerialSelection () + { + QFETCH (bool, rts); + auto& u = ui (); + u.rig_combo_box->setCurrentText ("OmniRig Rig 1"); + (rts ? u.PTT_RTS_radio_button : u.PTT_DTR_radio_button)->setChecked (true); + u.PTT_port_combo_box->setCurrentIndex (u.PTT_port_combo_box->findText ("CAT")); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {"CAT"}); + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::none); + QSignalSpy changes {u.PTT_port_combo_box, &QComboBox::currentTextChanged}; + u.rig_combo_box->setCurrentText (serial_rig_); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {}); + QCOMPARE (u.PTT_port_combo_box->currentIndex (), -1); + QCOMPARE (changes.count (), 0); + QCOMPARE (u.PTT_port_combo_box->findText ("USB"), -1); + QVERIFY (u.CAT_port_combo_box->findText ("USB") >= 0); + for (int i = 0; i != 3; ++i) dialog ().set_rig_invariants (); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {}); + u.rig_combo_box->setCurrentText ("OmniRig Rig 1"); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {}); + u.rig_combo_box->setCurrentText (serial_rig_); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {}); + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::invalid_ptt_port); + u.PTT_port_combo_box->setEditText ("/dev/manually-entered-ptt"); + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::none); + QCOMPARE (dialog ().gather_rig_data ().ptt_port, QString {"/dev/manually-entered-ptt"}); + } + + void networkToSerialUsesFinalPorts_data () + { + QTest::addColumn<bool> ("same_port"); + QTest::addColumn<bool> ("hardware"); + QTest::addColumn<bool> ("rts"); + for (bool same : {false, true}) + for (bool hw : {false, true}) + for (bool rts : {false, true}) + QTest::newRow (qPrintable (QString {"same=%1,hardware=%2,rts=%3"}.arg (same).arg (hw).arg (rts))) + << same << hw << rts; + } + + void networkToSerialUsesFinalPorts () + { + QFETCH (bool, same_port); + QFETCH (bool, hardware); + QFETCH (bool, rts); + auto& u = ui (); + (hardware ? u.CAT_handshake_hardware_radio_button : u.CAT_handshake_none_radio_button)->setChecked (true); + (rts ? u.PTT_RTS_radio_button : u.PTT_DTR_radio_button)->setChecked (true); + u.PTT_port_combo_box->setEditText (same_port ? "/dev/test-cat" : "/dev/test-ptt"); + for (int i = 0; i != 3; ++i) + { + u.rig_combo_box->setCurrentText (network_rig_); + QVERIFY (u.PTT_RTS_radio_button->isEnabled ()); + u.rig_combo_box->setCurrentText (serial_rig_); + QCOMPARE (u.CAT_port_combo_box->currentText (), QString {"/dev/test-cat"}); + QCOMPARE (u.PTT_RTS_radio_button->isEnabled (), !(same_port && hardware)); + QCOMPARE (u.force_DTR_combo_box->isEnabled (), !(same_port && !rts)); + QCOMPARE (u.force_RTS_combo_box->isEnabled (), !hardware && !(same_port && rts)); + dialog ().set_rig_invariants (); + QCOMPARE (u.PTT_RTS_radio_button->isEnabled (), !(same_port && hardware)); + QCOMPARE (u.force_DTR_combo_box->isEnabled (), !(same_port && !rts)); + QCOMPARE (u.force_RTS_combo_box->isEnabled (), !hardware && !(same_port && rts)); + } + } + + void editablePortsUpdateWithoutActivation () + { + auto& u = ui (); + QSignalSpy activated {u.PTT_port_combo_box, QOverload<int>::of (&QComboBox::activated)}; + QVERIFY (!u.force_DTR_combo_box->isEnabled ()); + u.PTT_port_combo_box->lineEdit ()->selectAll (); + QTest::keyClicks (u.PTT_port_combo_box->lineEdit (), "/dev/typed-port"); + QCOMPARE (activated.count (), 0); + QVERIFY (u.force_DTR_combo_box->isEnabled ()); + u.CAT_port_combo_box->setEditText ("/dev/typed-port"); + QVERIFY (!u.force_DTR_combo_box->isEnabled ()); + u.CAT_handshake_hardware_radio_button->setChecked (true); + QVERIFY (!u.PTT_RTS_radio_button->isEnabled ()); + u.PTT_port_combo_box->setCurrentText ("/dev/separate-port"); + QVERIFY (u.PTT_RTS_radio_button->isEnabled ()); + QVERIFY (!u.force_RTS_combo_box->isEnabled ()); + } + + void validationRefreshesBlockedProgrammaticChanges_data () + { + QTest::addColumn<QString> ("port"); + QTest::newRow ("unsupported proxy") << QString {"CAT"}; + QTest::newRow ("USB is not serial PTT") << QString {"USB"}; + QTest::newRow ("empty") << QString {}; + QTest::newRow ("whitespace") << QString {" "}; + } + + void validationRefreshesBlockedProgrammaticChanges () + { + QFETCH (QString, port); + auto& u = ui (); + { + QSignalBlocker blocked {u.PTT_port_combo_box}; + u.PTT_port_combo_box->setEditText (port); + } + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::invalid_ptt_port); + QVERIFY (!dialog ().rig_active_); + QCOMPARE (dialog ().rig_params_.ptt_port, QString {"/dev/test-cat"}); + } + + void cancelRestoresSavedPorts () + { + auto& u = ui (); + u.CAT_port_combo_box->setEditText ("/dev/edited-cat"); + u.PTT_port_combo_box->setEditText ("/dev/edited-ptt"); + u.configuration_dialog_button_box->button (QDialogButtonBox::Cancel)->click (); + QCOMPARE (u.CAT_port_combo_box->currentText (), QString {"/dev/test-cat"}); + QCOMPARE (u.PTT_port_combo_box->currentText (), QString {"/dev/test-cat"}); + QVERIFY (!u.force_DTR_combo_box->isEnabled ()); + } + + void validationRefreshesHandshakeAfterBlockedRigChange () + { + auto& u = ui (); + u.rig_combo_box->setCurrentText (network_rig_); + u.CAT_handshake_hardware_radio_button->setChecked (true); + u.PTT_RTS_radio_button->setChecked (true); + QVERIFY (u.PTT_RTS_radio_button->isEnabled ()); + { + QSignalBlocker blocked {u.rig_combo_box}; + u.rig_combo_box->setCurrentText (serial_rig_); + } + QCOMPARE (dialog ().validate_radio_settings (), RadioValidationError::invalid_ptt_method); + QCOMPARE (u.CAT_port_combo_box->currentText (), u.PTT_port_combo_box->currentText ()); + QVERIFY (!u.PTT_RTS_radio_button->isEnabled ()); + QVERIFY (!u.force_RTS_combo_box->isEnabled ()); + } + + void noneRetainsSerialPortSelection () + { + auto& u = ui (); + u.CAT_port_combo_box->setEditText ("/dev/edited-cat"); + u.rig_combo_box->setCurrentText ("None"); + u.rig_combo_box->setCurrentText (serial_rig_); + QCOMPARE (u.CAT_port_combo_box->currentText (), QString {"/dev/edited-cat"}); + } + + void destructionCancelsDeferredFileInformation () + { + configuration_.reset (); + QTest::qWait (3000); + } +}; + +QTEST_MAIN (TestConfigurationRadio) +#include "test_configuration_radio.moc" diff --git a/tests/unit/common/test_decode_highlighting_model.cpp b/tests/unit/common/test_decode_highlighting_model.cpp new file mode 100644 index 00000000..c34223c2 --- /dev/null +++ b/tests/unit/common/test_decode_highlighting_model.cpp @@ -0,0 +1,526 @@ +#include <QtTest> + +#include <algorithm> +#include <cmath> + +#include <QMetaEnum> +#include <QSettings> +#include <QSet> +#include <QSignalSpy> +#include <QTemporaryDir> + +#include "models/DecodeHighlightingModel.hpp" + +class TestDecodeHighlightingModel + : public QObject +{ + Q_OBJECT + + using Highlight = DecodeHighlightingModel::Highlight; + using HighlightItems = DecodeHighlightingModel::HighlightItems; + using HighlightColors = DecodeHighlightingModel::HighlightColors; + using ColorPreset = DecodeHighlightingModel::ColorPreset; + + static HighlightColors const * colors_for (ColorPreset const& preset, Highlight type) + { + for (auto const& colors : preset) + { + if (colors.type_ == type) + { + return &colors; + } + } + return nullptr; + } + + static qreal relative_luminance (QColor const& color) + { + auto linear = [] (int component) { + auto const value = component / 255.; + return value <= .04045 ? value / 12.92 : std::pow ((value + .055) / 1.055, 2.4); + }; + return .2126 * linear (color.red ()) + + .7152 * linear (color.green ()) + + .0722 * linear (color.blue ()); + } + + static qreal contrast_ratio (QColor const& first, QColor const& second) + { + auto const first_luminance = relative_luminance (first); + auto const second_luminance = relative_luminance (second); + auto const lighter = std::max (first_luminance, second_luminance); + auto const darker = std::min (first_luminance, second_luminance); + return (lighter + .05) / (darker + .05); + } + + template<typename Items> + static void verify_complete_type_coverage (Items const& items, char const * name) + { + auto const meta = QMetaEnum::fromType<Highlight> (); + QSet<int> types; + for (auto const& item : items) + { + auto const type = static_cast<int> (item.type_); + auto const message = QString {"%1 contains unknown or duplicate type %2"}.arg (name).arg (type); + QVERIFY2 (meta.valueToKey (type), qPrintable (message)); + QVERIFY2 (!types.contains (type), qPrintable (message)); + types.insert (type); + } + QCOMPARE (types.size (), meta.keyCount ()); + for (int key {0}; key < meta.keyCount (); ++key) + { + auto const message = QString {"%1 omits %2"}.arg (name).arg (meta.key (key)); + QVERIFY2 (types.contains (meta.value (key)), qPrintable (message)); + } + } + +private Q_SLOTS: + void refactored_defaults_preserve_existing_values () + { + HighlightItems const expected_default = { + {Highlight::MyCall, true, {}, {{0xff, 0x66, 0x66}}} + , {Highlight::Continent, true, {}, {{0xff, 0x00, 0x63}}} + , {Highlight::ContinentBand, true, {}, {{0xff, 0x99, 0xc2}}} + , {Highlight::CQZone, true, {}, {{0xff, 0xbf, 0x00}}} + , {Highlight::CQZoneBand, true, {}, {{0xff, 0xe4, 0x99}}} + , {Highlight::ITUZone, false, {}, {{0xa6, 0xff, 0x00}}} + , {Highlight::ITUZoneBand, false, {}, {{0xdd, 0xff, 0x99}}} + , {Highlight::DXCC, true, {}, {{0xff, 0x00, 0xff}}} + , {Highlight::DXCCBand, true, {}, {{0xff, 0xaa, 0xff}}} + , {Highlight::Grid, false, {}, {{0xff, 0x80, 0x00}}} + , {Highlight::GridBand, false, {}, {{0xff, 0xcc, 0x99}}} + , {Highlight::Call, false, {}, {{0x00, 0xff, 0xff}}} + , {Highlight::CallBand, false, {}, {{0x99, 0xff, 0xff}}} + , {Highlight::LotW, false, {{0x99, 0x00, 0x00}}, {}} + , {Highlight::CQ, true, {}, {{0x66, 0xff, 0x66}}} + , {Highlight::Tx, true, {}, {Qt::yellow}} + }; + HighlightItems const expected_default2 = { + {Highlight::LotW, true, {Qt::black}, {}} + , {Highlight::MyCall, true, {{0xaa, 0x00, 0x00}}, {{0x00, 0xff, 0xff}}} + , {Highlight::Continent, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0x50, 0xff}}} + , {Highlight::ContinentBand, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0x82, 0xff}}} + , {Highlight::DXCC, true, {{0xaa, 0x00, 0x00}}, {Qt::yellow}} + , {Highlight::DXCCBand, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0xff, 0x9b}}} + , {Highlight::CQZone, true, {{0xaa, 0x00, 0x00}}, {{0xaa, 0xaa, 0x00}}} + , {Highlight::CQZoneBand, true, {{0xaa, 0x00, 0x00}}, {{0xaa, 0xaa, 0x7f}}} + , {Highlight::ITUZone, true, {{0xaa, 0x00, 0x00}}, {{0x37, 0xbd, 0xff}}} + , {Highlight::ITUZoneBand, true, {{0xaa, 0x00, 0x00}}, {{0x91, 0xde, 0xff}}} + , {Highlight::Grid, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0xa8, 0x80}}} + , {Highlight::GridBand, true, {{0xaa, 0x00, 0x00}}, {{0xff, 0xcd, 0x9b}}} + , {Highlight::Call, true, {{0xaa, 0x00, 0x00}}, {{0x64, 0xff, 0x64}}} + , {Highlight::CallBand, true, {{0xaa, 0x00, 0x00}}, {{0xb4, 0xff, 0xb4}}} + , {Highlight::CQ, true, {{0xaa, 0x00, 0x00}}, {{0xc3, 0xc3, 0xc3}}} + , {Highlight::Tx, true, {Qt::black}, {{0xff, 0xa5, 0xc6}}} + }; + + QVERIFY (DecodeHighlightingModel::default_items () == expected_default); + QVERIFY (DecodeHighlightingModel::default_items2 () == expected_default2); + } + + void built_in_presets_are_complete () + { + DecodeHighlightingModel model; + + verify_complete_type_coverage (DecodeHighlightingModel::default_items (), "Default 1 items"); + verify_complete_type_coverage (DecodeHighlightingModel::default_items2 (), "Default 2 items"); + verify_complete_type_coverage (DecodeHighlightingModel::default_color_preset (), "Default 1 preset"); + verify_complete_type_coverage (DecodeHighlightingModel::default2_color_preset (), "Default 2 preset"); + verify_complete_type_coverage (DecodeHighlightingModel::red_green_color_vision_preset (), "Red/green preset"); + verify_complete_type_coverage (DecodeHighlightingModel::blue_yellow_color_vision_preset (), "Blue/yellow preset"); + verify_complete_type_coverage (DecodeHighlightingModel::high_contrast_color_preset (), "High contrast preset"); + verify_complete_type_coverage (DecodeHighlightingModel::dark_shack_color_preset (), "Dark shack preset"); + verify_complete_type_coverage (DecodeHighlightingModel::solarized_color_preset (), "Solarized preset"); + verify_complete_type_coverage (DecodeHighlightingModel::monochrome_color_preset (), "Monochrome preset"); + + QCOMPARE (DecodeHighlightingModel::default_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::default2_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::red_green_color_vision_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::blue_yellow_color_vision_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::high_contrast_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::dark_shack_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::solarized_color_preset ().size (), model.items ().size ()); + QCOMPARE (DecodeHighlightingModel::monochrome_color_preset ().size (), model.items ().size ()); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::default_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::default2_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::red_green_color_vision_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::blue_yellow_color_vision_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::high_contrast_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::dark_shack_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::solarized_color_preset ())); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::monochrome_color_preset ())); + } + + void default_presets_match_reset_colors () + { + struct DefaultPair final + { + HighlightItems const& items_; + ColorPreset const& preset_; + }; + DefaultPair const defaults[] = { + {DecodeHighlightingModel::default_items (), DecodeHighlightingModel::default_color_preset ()} + , {DecodeHighlightingModel::default_items2 (), DecodeHighlightingModel::default2_color_preset ()} + }; + + for (auto const& default_pair : defaults) + { + for (auto const& item : default_pair.items_) + { + auto const colors = colors_for (default_pair.preset_, item.type_); + QVERIFY (colors); + QCOMPARE (colors->foreground_, item.foreground_); + QCOMPARE (colors->background_, item.background_); + } + } + } + + void color_resolution_honors_priority_and_reordering () + { + HighlightItems items { + {Highlight::MyCall, true, QBrush {Qt::white}, QBrush {Qt::red}} + , {Highlight::CQ, true, QBrush {Qt::black}, QBrush {Qt::yellow}} + }; + DecodeHighlightingModel::HighlightTypes matches {Highlight::CQ, Highlight::MyCall}; + + auto resolved = DecodeHighlightingModel::resolve_colors (items, matches, Qt::magenta, Qt::cyan); + QCOMPARE (resolved.type_, Highlight::MyCall); + QCOMPARE (resolved.background_, QColor {Qt::red}); + QCOMPARE (resolved.foreground_, QColor {Qt::white}); + + items.prepend (items.takeLast ()); + resolved = DecodeHighlightingModel::resolve_colors (items, matches, Qt::magenta, Qt::cyan); + QCOMPARE (resolved.type_, Highlight::CQ); + QCOMPARE (resolved.background_, QColor {Qt::yellow}); + QCOMPARE (resolved.foreground_, QColor {Qt::black}); + } + + void color_resolution_composes_independent_channels () + { + HighlightItems const items { + {Highlight::MyCall, true, {}, QBrush {Qt::red}} + , {Highlight::DXCC, true, QBrush {Qt::white}, {}} + , {Highlight::CQ, true, QBrush {Qt::black}, QBrush {Qt::yellow}} + }; + DecodeHighlightingModel::HighlightTypes const matches { + Highlight::CQ, Highlight::DXCC, Highlight::MyCall + }; + + auto const resolved = DecodeHighlightingModel::resolve_colors (items, matches, Qt::magenta, Qt::cyan); + QCOMPARE (resolved.type_, Highlight::MyCall); + QCOMPARE (resolved.background_, QColor {Qt::red}); + QCOMPARE (resolved.foreground_, QColor {Qt::white}); + } + + void color_resolution_ignores_disabled_rules () + { + HighlightItems const items { + {Highlight::MyCall, false, QBrush {Qt::white}, QBrush {Qt::red}} + , {Highlight::CQ, true, QBrush {Qt::black}, QBrush {Qt::yellow}} + }; + DecodeHighlightingModel::HighlightTypes const matches {Highlight::CQ, Highlight::MyCall}; + + auto const resolved = DecodeHighlightingModel::resolve_colors (items, matches, Qt::magenta, Qt::cyan); + QCOMPARE (resolved.type_, Highlight::CQ); + QCOMPARE (resolved.background_, QColor {Qt::yellow}); + QCOMPARE (resolved.foreground_, QColor {Qt::black}); + } + + void complete_pair_presets_meet_text_contrast () + { + struct NamedPreset final + { + char const * name_; + ColorPreset const& preset_; + }; + NamedPreset const presets[] = { + {"red/green", DecodeHighlightingModel::red_green_color_vision_preset ()} + , {"blue/yellow", DecodeHighlightingModel::blue_yellow_color_vision_preset ()} + , {"high contrast", DecodeHighlightingModel::high_contrast_color_preset ()} + , {"dark shack", DecodeHighlightingModel::dark_shack_color_preset ()} + , {"solarized", DecodeHighlightingModel::solarized_color_preset ()} + , {"monochrome", DecodeHighlightingModel::monochrome_color_preset ()} + }; + + for (auto const& named_preset : presets) + { + for (auto const& colors : named_preset.preset_) + { + auto const rule_name = DecodeHighlightingModel::highlight_name (colors.type_); + auto const unset_message = QString {"%1: %2 must set both foreground and background colors"} + .arg (named_preset.name_) + .arg (rule_name); + QVERIFY2 (Qt::NoBrush != colors.foreground_.style (), qPrintable (unset_message)); + QVERIFY2 (Qt::NoBrush != colors.background_.style (), qPrintable (unset_message)); + auto const ratio = contrast_ratio (colors.foreground_.color (), colors.background_.color ()); + auto const message = QString {"%1: %2 has contrast ratio %3"} + .arg (named_preset.name_) + .arg (rule_name) + .arg (ratio, 0, 'f', 2); + QVERIFY2 (ratio >= 4.5, qPrintable (message)); + } + } + } + + void monochrome_preset_is_achromatic () + { + for (auto const& colors : DecodeHighlightingModel::monochrome_color_preset ()) + { + QColor const pair[] = {colors.foreground_.color (), colors.background_.color ()}; + for (auto const& color : pair) + { + QCOMPARE (color.red (), color.green ()); + QCOMPARE (color.green (), color.blue ()); + } + } + } + + void dark_shack_preset_uses_dark_backgrounds () + { + qreal constexpr maximum_background_luminance {.15}; + for (auto const& colors : DecodeHighlightingModel::dark_shack_color_preset ()) + { + auto const luminance = relative_luminance (colors.background_.color ()); + auto const message = QString {"%1 background luminance %2 exceeds %3"} + .arg (DecodeHighlightingModel::highlight_name (colors.type_)) + .arg (luminance, 0, 'f', 3) + .arg (maximum_background_luminance, 0, 'f', 3); + QVERIFY2 (luminance <= maximum_background_luminance, qPrintable (message)); + } + } + + void operating_presets_separate_all_band_backgrounds_from_cq () + { + struct AlertPair final + { + Highlight all_band_; + Highlight on_band_; + }; + AlertPair const alert_pairs[] = { + {Highlight::Continent, Highlight::ContinentBand} + , {Highlight::CQZone, Highlight::CQZoneBand} + , {Highlight::ITUZone, Highlight::ITUZoneBand} + , {Highlight::DXCC, Highlight::DXCCBand} + , {Highlight::Grid, Highlight::GridBand} + , {Highlight::Call, Highlight::CallBand} + }; + ColorPreset const * presets[] = { + &DecodeHighlightingModel::dark_shack_color_preset () + , &DecodeHighlightingModel::solarized_color_preset () + , &DecodeHighlightingModel::monochrome_color_preset () + }; + + for (auto const preset : presets) + { + auto const cq = colors_for (*preset, Highlight::CQ); + QVERIFY (cq); + for (auto const& pair : alert_pairs) + { + auto const all_band = colors_for (*preset, pair.all_band_); + auto const on_band = colors_for (*preset, pair.on_band_); + QVERIFY (all_band); + QVERIFY (on_band); + auto const all_band_contrast = contrast_ratio ( + all_band->background_.color (), cq->background_.color ()); + auto const on_band_contrast = contrast_ratio ( + on_band->background_.color (), cq->background_.color ()); + auto const minimum_contrast = on_band_contrast * 1.1; + auto const message = QString {"%1 background contrast %2 must be at least 10% greater " + "than %3's %4"} + .arg (DecodeHighlightingModel::highlight_name (pair.all_band_)) + .arg (all_band_contrast, 0, 'f', 2) + .arg (DecodeHighlightingModel::highlight_name (pair.on_band_)) + .arg (on_band_contrast, 0, 'f', 2); + QVERIFY2 (all_band_contrast >= minimum_contrast, qPrintable (message)); + } + } + } + + void preset_changes_only_colors () + { + DecodeHighlightingModel model; + auto custom = DecodeHighlightingModel::default_items (); + custom.append (custom.takeFirst ()); + for (int row {0}; row < custom.size (); ++row) + { + custom[row].enabled_ = 0 == row % 2; + custom[row].foreground_ = QBrush {QColor {row, row + 1, row + 2}}; + custom[row].background_ = QBrush {QColor {row + 3, row + 4, row + 5}}; + } + model.items (custom); + auto const before = model.items (); + QSignalSpy changes {&model, &QAbstractItemModel::dataChanged}; + QSignalSpy resets {&model, &QAbstractItemModel::modelReset}; + + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::default2_color_preset ())); + + auto const after = model.items (); + QCOMPARE (after.size (), before.size ()); + for (int row {0}; row < after.size (); ++row) + { + QCOMPARE (after[row].type_, before[row].type_); + QCOMPARE (after[row].enabled_, before[row].enabled_); + auto const colors = colors_for (DecodeHighlightingModel::default2_color_preset (), after[row].type_); + QVERIFY (colors); + QCOMPARE (after[row].foreground_, colors->foreground_); + QCOMPARE (after[row].background_, colors->background_); + } + QCOMPARE (changes.size (), 1); + auto const change = changes.takeFirst (); + QCOMPARE (change.at (0).value<QModelIndex> (), model.index (0, 0)); + QCOMPARE (change.at (1).value<QModelIndex> (), model.index (after.size () - 1, 0)); + auto const roles = change.at (2).value<QVector<int>> (); + QCOMPARE (roles, QVector<int> ({Qt::DisplayRole, Qt::ForegroundRole, Qt::BackgroundRole})); + QCOMPARE (resets.size (), 0); + auto const lotw = std::find_if (after.cbegin (), after.cend (), [] (auto const& item) { + return item.type_ == Highlight::LotW; + }); + QVERIFY (lotw != after.cend ()); + auto const lotw_row = static_cast<int> (std::distance (after.cbegin (), lotw)); + auto const& abstract_model = static_cast<QAbstractItemModel const&> (model); + QVERIFY (abstract_model.data (model.index (lotw_row, 0), Qt::DisplayRole).toString ().contains ("b/g unset")); + + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::default2_color_preset ())); + QCOMPARE (changes.size (), 0); + } + + void color_changes_notify_display_role () + { + DecodeHighlightingModel model; + auto items = model.items (); + items[0].foreground_ = QBrush {Qt::black}; + items[0].background_ = QBrush {Qt::white}; + model.items (items); + auto const index = model.index (0, 0); + auto& abstract_model = static_cast<QAbstractItemModel&> (model); + QSignalSpy changes {&model, &QAbstractItemModel::dataChanged}; + + QVERIFY (abstract_model.setData (index, QBrush {}, Qt::ForegroundRole)); + QCOMPARE (changes.size (), 1); + QCOMPARE (changes.takeFirst ().at (2).value<QVector<int>> (), + QVector<int> ({Qt::ForegroundRole, Qt::DisplayRole})); + QVERIFY (abstract_model.data (index, Qt::DisplayRole).toString ().contains ("f/g unset")); + + QVERIFY (abstract_model.setData (index, QBrush {}, Qt::BackgroundRole)); + QCOMPARE (changes.size (), 1); + QCOMPARE (changes.takeFirst ().at (2).value<QVector<int>> (), + QVector<int> ({Qt::BackgroundRole, Qt::DisplayRole})); + QVERIFY (abstract_model.data (index, Qt::DisplayRole).toString ().contains ("b/g unset")); + } + + void complete_presets_apply_to_legacy_models () + { + DecodeHighlightingModel model; + auto legacy = DecodeHighlightingModel::default_items (); + legacy.erase (std::remove_if (legacy.begin (), legacy.end (), [] (auto const& item) { + return item.type_ == Highlight::Continent + || item.type_ == Highlight::ContinentBand + || item.type_ == Highlight::CQZone + || item.type_ == Highlight::CQZoneBand + || item.type_ == Highlight::ITUZone + || item.type_ == Highlight::ITUZoneBand; + }), legacy.end ()); + model.items (legacy); + + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::high_contrast_color_preset ())); + QCOMPARE (model.items ().size (), legacy.size ()); + for (auto const& item : model.items ()) + { + auto const colors = colors_for (DecodeHighlightingModel::high_contrast_color_preset (), item.type_); + QVERIFY (colors); + QCOMPARE (item.foreground_, colors->foreground_); + QCOMPARE (item.background_, colors->background_); + } + } + + void presets_apply_to_duplicate_model_rules () + { + DecodeHighlightingModel model; + auto malformed = DecodeHighlightingModel::default_items (); + malformed.last ().type_ = malformed.first ().type_; + malformed.first ().foreground_ = QBrush {Qt::magenta}; + malformed.last ().foreground_ = QBrush {Qt::cyan}; + model.items (malformed); + + auto const& preset = DecodeHighlightingModel::high_contrast_color_preset (); + QVERIFY (model.apply_color_preset (preset)); + + auto const colors = colors_for (preset, malformed.first ().type_); + QVERIFY (colors); + auto const after = model.items (); + QCOMPARE (after.first ().foreground_, colors->foreground_); + QCOMPARE (after.first ().background_, colors->background_); + QCOMPARE (after.last ().foreground_, colors->foreground_); + QCOMPARE (after.last ().background_, colors->background_); + } + + void invalid_presets_do_not_modify_model () + { + DecodeHighlightingModel model; + auto custom = model.items (); + for (int row {0}; row < custom.size (); ++row) + { + custom[row].foreground_ = QBrush {QColor {row + 1, row + 2, row + 3}}; + custom[row].background_ = QBrush {QColor {row + 4, row + 5, row + 6}}; + } + model.items (custom); + auto const before = model.items (); + QSignalSpy changes {&model, &QAbstractItemModel::dataChanged}; + + auto incomplete = DecodeHighlightingModel::high_contrast_color_preset (); + incomplete.removeLast (); + QVERIFY (!model.apply_color_preset (incomplete)); + QVERIFY (model.items () == before); + + auto duplicate = DecodeHighlightingModel::default_color_preset (); + duplicate.last ().type_ = duplicate.first ().type_; + QVERIFY (!model.apply_color_preset (duplicate)); + QVERIFY (model.items () == before); + QCOMPARE (changes.size (), 0); + } + + void empty_models_reject_presets () + { + DecodeHighlightingModel model; + model.items ({}); + QSignalSpy changes {&model, &QAbstractItemModel::dataChanged}; + + QVERIFY (!model.apply_color_preset (DecodeHighlightingModel::default_color_preset ())); + QVERIFY (model.items ().isEmpty ()); + QCOMPARE (changes.size (), 0); + } + + void preset_colors_round_trip_through_settings () + { + qRegisterMetaTypeStreamOperators<DecodeHighlightingModel::HighlightInfo> ("HighlightInfo"); + qRegisterMetaTypeStreamOperators<HighlightItems> ("HighlightItems"); + + DecodeHighlightingModel model; + auto customized = model.items (); + customized.append (customized.takeFirst ()); + for (int row {0}; row < customized.size (); ++row) + { + customized[row].enabled_ = 0 == row % 2; + } + model.items (customized); + QVERIFY (model.apply_color_preset (DecodeHighlightingModel::solarized_color_preset ())); + + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto const filename = directory.filePath ("wsjtx.ini"); + { + QSettings settings {filename, QSettings::IniFormat}; + settings.setValue ("DecodeHighlighting", QVariant::fromValue (model.items ())); + settings.sync (); + QCOMPARE (settings.status (), QSettings::NoError); + } + + QSettings settings {filename, QSettings::IniFormat}; + auto const restored = settings.value ("DecodeHighlighting").value<HighlightItems> (); + QVERIFY (restored == model.items ()); + } +}; + +QTEST_APPLESS_MAIN (TestDecodeHighlightingModel); + +#include "test_decode_highlighting_model.moc" diff --git a/tests/unit/common/test_frequency_list.cpp b/tests/unit/common/test_frequency_list.cpp new file mode 100644 index 00000000..92933cfc --- /dev/null +++ b/tests/unit/common/test_frequency_list.cpp @@ -0,0 +1,294 @@ +#include <QtTest> + +#include <algorithm> + +#include <QJsonArray> +#include <QTemporaryFile> +#include <QTranslator> + +#include "models/Bands.hpp" +#include "models/FrequencyList.hpp" + +namespace +{ + using WorkingFrequencies = FrequencyList_v2_101; + + class LocaleGuard + { + public: + ~LocaleGuard () { QLocale::setDefault (original_); } + private: + QLocale original_; + }; + + class RegionTranslator : public QTranslator + { + public: + bool isEmpty () const override { return false; } + QString translate (char const * context, char const * source, + char const * = nullptr, int = -1) const override + { + if (QString::fromLatin1 (context) == "IARURegions") + return "Translated " + QString::fromLatin1 (source); + return {}; + } + }; + + QList<Radio::Frequency> visible_frequencies (WorkingFrequencies const& model) + { + QList<Radio::Frequency> result; + for (auto const& item : model) result.append (item.frequency_); + std::sort (result.begin (), result.end ()); + return result; + } + + Radio::Frequency selected_frequency (WorkingFrequencies const& model, int row) + { + if (row < 0 || row >= model.rowCount ()) return 0; + return model.frequency_list ({model.index (row, 0)}).value (0).frequency_; + } +} + +class TestFrequencyList : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void json_round_trip_data (); + void json_round_trip (); + void legacy_locale_frequencies_data (); + void legacy_locale_frequencies (); + void invalid_documents_data (); + void invalid_documents (); + void invalid_entries_are_isolated (); + void mode_names_are_normalized (); + void eligibility_filters (); + void selection_uses_eligible_frequencies (); +}; + +void TestFrequencyList::json_round_trip_data () +{ + QTest::addColumn<QString> ("locale_name"); + QTest::addColumn<bool> ("translated"); + QTest::newRow ("C") << QStringLiteral ("C") << false; + QTest::newRow ("decimal-comma") << QStringLiteral ("de_DE") << false; + QTest::newRow ("translated-regions") << QStringLiteral ("C") << true; +} + +void TestFrequencyList::json_round_trip () +{ + QFETCH (QString, locale_name); + QFETCH (bool, translated); + LocaleGuard restore_locale; + QLocale::setDefault (QLocale {locale_name}); + RegionTranslator translator; + if (translated) QVERIFY (QCoreApplication::installTranslator (&translator)); + + Bands bands; + WorkingFrequencies model {&bands}; + WorkingFrequencies::FrequencyItems const expected { + {1000001, Modes::FreqCal, IARURegions::R1, "Reference", "Test source", + QDateTime::fromString ("2026-01-01T12:34:56Z", Qt::ISODate), + QDateTime::fromString ("2026-12-31T12:34:56Z", Qt::ISODate), true}, + {14074000, Modes::FT8, IARURegions::ALL, {}, {}, {}, {}, false}, + {7078000, Modes::ALL, IARURegions::R2, {}, {}, {}, {}, false} + }; + QTemporaryFile file; + QVERIFY (file.open ()); + model.to_json_file (&file, "test", "101", expected); + QVERIFY (file.seek (0)); + auto const document = QJsonDocument::fromJson (file.readAll ()); + QCOMPARE (document.object ()["frequencies"].toArray ()[0].toObject ()["frequency"].toString (), + QStringLiteral ("1.000001")); + QVERIFY (file.seek (0)); + auto const actual = WorkingFrequencies::from_json_file (&file); + QCOMPARE (actual.size (), expected.size ()); + for (int i = 0; i < expected.size (); ++i) QCOMPARE (actual[i], expected[i]); +} + +void TestFrequencyList::legacy_locale_frequencies_data () +{ + QTest::addColumn<QString> ("frequency_text"); + QTest::addColumn<Radio::Frequency> ("frequency_hz"); + QTest::newRow ("German decimal comma") << QStringLiteral ("14,074000") << Radio::Frequency {14074000}; + QTest::newRow ("German grouping") << QStringLiteral ("1.296,000000") << Radio::Frequency {1296000000}; + QTest::newRow ("French narrow-space grouping") << QStringLiteral ("1\u202f296,000000") + << Radio::Frequency {1296000000}; + QTest::newRow ("French older grouping") << QStringLiteral ("1\u00a0296,000000") + << Radio::Frequency {1296000000}; + QTest::newRow ("Russian grouping") << QLocale {"ru_RU"}.toString (1296., 'f', 6) + << Radio::Frequency {1296000000}; + QTest::newRow ("Swiss apostrophe grouping") << QStringLiteral ("1\u2019296.000000") + << Radio::Frequency {1296000000}; + QTest::newRow ("Swiss older grouping") << QStringLiteral ("1'296.000000") + << Radio::Frequency {1296000000}; +} + +void TestFrequencyList::legacy_locale_frequencies () +{ + QFETCH (QString, frequency_text); + QFETCH (Radio::Frequency, frequency_hz); + LocaleGuard restore_locale; + QLocale::setDefault (QLocale::c ()); + QVERIFY (frequency_text != QLocale::c ().toString (frequency_hz / 1e6, 'f', 6)); + QJsonArray entries {QJsonObject {{"frequency", frequency_text}, {"mode", "FT8"}, + {"region", "Region 1"}}}; + QTemporaryFile file; + QVERIFY (file.open ()); + auto const contents = QJsonDocument {QJsonObject {{"frequencies", entries}}}.toJson (); + QCOMPARE (file.write (contents), qint64 (contents.size ())); + QVERIFY (file.seek (0)); + WorkingFrequencies::ImportReport report; + auto const actual = WorkingFrequencies::from_json_file (&file, &report); + QCOMPARE (report.entries, 1); + QCOMPARE (report.imported, 1); + QCOMPARE (report.skipped (), 0); + QCOMPARE (actual.size (), 1); + QCOMPARE (actual.front ().frequency_, frequency_hz); +} + +void TestFrequencyList::invalid_documents_data () +{ + QTest::addColumn<QByteArray> ("contents"); + QTest::newRow ("malformed") << QByteArray {"{"}; + QTest::newRow ("missing-frequencies") << QByteArray {"{\"wsjtx_file\":\"qrg\"}"}; + QTest::newRow ("empty-frequencies") << QByteArray {"{\"frequencies\":[]}"}; +} + +void TestFrequencyList::invalid_documents () +{ + QFETCH (QByteArray, contents); + QTemporaryFile file; + QVERIFY (file.open ()); + QCOMPARE (file.write (contents), qint64 (contents.size ())); + QVERIFY (file.seek (0)); + QVERIFY_EXCEPTION_THROWN (WorkingFrequencies::from_json_file (&file), ReadFileException); +} + +void TestFrequencyList::invalid_entries_are_isolated () +{ + QJsonObject const valid {{"frequency", "14.074000"}, {"mode", "FT8"}, + {"region", "Region 1"}}; + QJsonArray entries; + for (auto const& frequency : {"invalid", "-1", "18446744073709.551616", "0", "14,074"}) + { + auto invalid = valid; + invalid["frequency"] = frequency; + entries.append (invalid); + } + for (auto const& field : {"mode", "region"}) + { + auto invalid = valid; + invalid[field] = "Unknown"; + entries.append (invalid); + } + entries.insert (2, valid); + auto unknown_mode = valid; + unknown_mode["mode"] = "FT2"; + entries.append (unknown_mode); + auto invalid_dates = valid; + invalid_dates["start_time"] = "2026-12-31T00:00:00Z"; + invalid_dates["end_time"] = "2026-01-01T00:00:00Z"; + entries.append (invalid_dates); + auto malformed_date = valid; + malformed_date["start_time"] = "not a date"; + entries.append (malformed_date); + QTemporaryFile file; + QVERIFY (file.open ()); + auto const contents = QJsonDocument {QJsonObject {{"frequencies", entries}}}.toJson (); + QCOMPARE (file.write (contents), qint64 (contents.size ())); + QVERIFY (file.seek (0)); + WorkingFrequencies::ImportReport report; + auto const actual = WorkingFrequencies::from_json_file (&file, &report); + QCOMPARE (actual.size (), 1); + QCOMPARE (actual.front ().frequency_, Radio::Frequency {14074000}); + QCOMPARE (actual.front ().mode_, Modes::FT8); + QCOMPARE (actual.front ().region_, IARURegions::R1); + QCOMPARE (report.entries, entries.size ()); + QCOMPARE (report.imported, 1); + QCOMPARE (report.invalid_frequency, 5); + QCOMPARE (report.invalid_region, 1); + QCOMPARE (report.unknown_modes.value ("Unknown"), 1); + QCOMPARE (report.unknown_modes.value ("FT2"), 1); + QCOMPARE (report.invalid_item, 2); + QCOMPARE (report.skipped (), 10); +} + +void TestFrequencyList::mode_names_are_normalized () +{ + QJsonArray entries; + for (auto const& mode : {"ft8", " FT8 ", "", "All"}) + { + QJsonObject entry {{"frequency", "14.074000"}, {"region", "Region 1"}}; + entry["mode"] = mode; + entries.append (entry); + } + entries.append (QJsonObject {{"frequency", "7.074000"}, {"region", "Region 1"}}); + QTemporaryFile file; + QVERIFY (file.open ()); + auto const contents = QJsonDocument {QJsonObject {{"frequencies", entries}}}.toJson (); + QCOMPARE (file.write (contents), qint64 (contents.size ())); + QVERIFY (file.seek (0)); + WorkingFrequencies::ImportReport report; + auto const actual = WorkingFrequencies::from_json_file (&file, &report); + QCOMPARE (report.imported, entries.size ()); + QCOMPARE (report.skipped (), 0); + QCOMPARE (actual[0].mode_, Modes::FT8); + QCOMPARE (actual[1].mode_, Modes::FT8); + QCOMPARE (actual[2].mode_, Modes::ALL); + QCOMPARE (actual[3].mode_, Modes::ALL); + QCOMPARE (actual[4].mode_, Modes::ALL); +} + +void TestFrequencyList::eligibility_filters () +{ + Bands bands; + WorkingFrequencies model {&bands}; + auto const now = QDateTime::currentDateTimeUtc (); + model.frequency_list ({ + {14074000, Modes::FT8, IARURegions::R1, {}, {}, now.addDays (-1), now.addDays (1), false}, + {7074000, Modes::FT8, IARURegions::ALL, {}, {}, {}, {}, false}, + {10136000, Modes::ALL, IARURegions::R1, {}, {}, {}, {}, false}, + {50313000, Modes::FT8, IARURegions::R2, {}, {}, {}, {}, false}, + {14080000, Modes::FT4, IARURegions::R1, {}, {}, {}, {}, false}, + {10000000, Modes::FreqCal, IARURegions::ALL, {}, {}, {}, {}, false}, + {3573000, Modes::FT8, IARURegions::R1, {}, {}, {}, now.addDays (-1), false}, + {1840000, Modes::FT8, IARURegions::R1, {}, {}, now.addDays (1), {}, false} + }); + model.filter (IARURegions::R1, Modes::FT8, true); + QCOMPARE (visible_frequencies (model), (QList<Radio::Frequency> {7074000, 10136000, 14074000})); + model.filter (IARURegions::R1, Modes::FT8, false); + QCOMPARE (visible_frequencies (model), (QList<Radio::Frequency> {1840000, 3573000, 7074000, 10136000, 14074000})); + model.filter (IARURegions::R1, Modes::FreqCal, true); + QCOMPARE (visible_frequencies (model), (QList<Radio::Frequency> {10000000})); + model.filter (IARURegions::ALL, Modes::ALL, false); + QCOMPARE (model.rowCount (), 8); +} + +void TestFrequencyList::selection_uses_eligible_frequencies () +{ + Bands bands; + WorkingFrequencies model {&bands}; + WorkingFrequencies::Item const preferred {14074000, Modes::FT8, IARURegions::ALL, + {}, {}, {}, {}, true}; + model.frequency_list ({ + preferred, + {14080000, Modes::FT8, IARURegions::R1, {}, {}, {}, {}, false}, + {14090000, Modes::FT8, IARURegions::R1, {}, {}, {}, {}, false}, + {14081000, Modes::FT8, IARURegions::R2, {}, {}, {}, {}, true}, + {7074000, Modes::FT8, IARURegions::R2, {}, {}, {}, {}, true} + }); + model.filter (IARURegions::R1, Modes::FT8, false); + QCOMPARE (selected_frequency (model, model.best_working_frequency (Radio::Frequency {14081000})), + preferred.frequency_); + QCOMPARE (selected_frequency (model, model.best_working_frequency (QString {"20m"})), + preferred.frequency_); + QVERIFY (model.remove (preferred)); + QCOMPARE (selected_frequency (model, model.best_working_frequency (Radio::Frequency {14081000})), + Radio::Frequency {14080000}); + QCOMPARE (model.best_working_frequency (Radio::Frequency {7074000}), -1); + QCOMPARE (model.best_working_frequency (QString {"40m"}), -1); +} + +QTEST_GUILESS_MAIN (TestFrequencyList) +#include "test_frequency_list.moc" diff --git a/tests/unit/common/test_frequency_suggestions.cpp b/tests/unit/common/test_frequency_suggestions.cpp new file mode 100644 index 00000000..fdd8f0ed --- /dev/null +++ b/tests/unit/common/test_frequency_suggestions.cpp @@ -0,0 +1,200 @@ +#include <QtTest> +#include <QAccessible> +#include <QCheckBox> +#include <QScrollArea> +#include <QStyle> +#include <QStyleOptionButton> + +#include "models/Bands.hpp" +#include "models/FrequencySuggestions.hpp" +#include "widgets/SuggestedFrequenciesDialog.hpp" + +namespace +{ + using Item = FrequencyList_v2_101::Item; + using Items = FrequencyList_v2_101::FrequencyItems; + + Item frequency (Radio::Frequency dial, Modes::Mode mode = Modes::FT8, + IARURegions::Region region = IARURegions::ALL, + QString description = {}, bool preferred = false) + { + return {dial, mode, region, description, {}, {}, {}, preferred}; + } +} + +class TestFrequencySuggestions final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void matchesOperatingIdentity () + { + auto const proposed = frequency (14090000, Modes::FT8, IARURegions::R2); + auto const customized = frequency (14090000, Modes::FT8, IARURegions::ALL, + "My DX frequency", true); + QVERIFY (FrequencySuggestions::is_present (proposed, Items {customized})); + QVERIFY (!FrequencySuggestions::is_present ( + frequency (14091000, Modes::FT8, IARURegions::R2), Items {customized})); + QVERIFY (!FrequencySuggestions::is_present ( + frequency (14090000, Modes::JTTY, IARURegions::R2), Items {customized})); + QVERIFY (!FrequencySuggestions::is_present ( + frequency (14090000, Modes::FT8, IARURegions::ALL), + Items {frequency (14090000, Modes::FT8, IARURegions::R2)})); + QVERIFY (FrequencySuggestions::is_present ( + proposed, Items {frequency (14090000, Modes::ALL)})); + } + + void preservesCustomRowsAndPreferences () + { + Bands bands; + auto const custom = frequency (14074000, Modes::FT8, IARURegions::ALL, + "Personal calling spot", true); + Items working {custom}; + Items selected {frequency (14074000, Modes::FT8, IARURegions::ALL), + frequency (14090000, Modes::FT8, IARURegions::ALL, {}, true), + frequency (14090000, Modes::FT8, IARURegions::ALL, {}, true)}; + + auto additions = FrequencySuggestions::prepare_additions (selected, working, bands); + QCOMPARE (additions.size (), 1); + QCOMPARE (additions.first ().frequency_, Radio::Frequency {14090000}); + QVERIFY (!additions.first ().preferred_); + QCOMPARE (working.first ().description_, QStringLiteral ("Personal calling spot")); + QVERIFY (working.first ().preferred_); + } + + void noticeDoesNotAcknowledgeTemporaryReset () + { + Items previous_catalog {frequency (14074000)}; + Items catalog {frequency (14074000), frequency (14090000)}; + Items saved {frequency (14074000)}; + FrequencySuggestions::NoticeState notice; + QVERIFY (notice.acknowledge_present_catalog (previous_catalog, saved)); + QCOMPARE (notice.visibility (catalog, saved), + FrequencySuggestions::NoticeState::Visibility::New); + + auto temporary = catalog; + QCOMPARE (notice.visibility (catalog, temporary), + FrequencySuggestions::NoticeState::Visibility::Hidden); + notice.cancel (); + QCOMPARE (notice.visibility (catalog, saved), + FrequencySuggestions::NoticeState::Visibility::New); + QCOMPARE (notice.seen_keys ().size (), 1); + } + + void noticeAcknowledgesOnlyCommittedSelections () + { + Items catalog {frequency (14074000), frequency (14090000), frequency (14091000)}; + Items working {frequency (14074000)}; + FrequencySuggestions::NoticeState notice; + QCOMPARE (notice.visibility (catalog, working), + FrequencySuggestions::NoticeState::Visibility::Available); + QVERIFY (!notice.commit (catalog, working)); + notice.selected_additions (Items {frequency (14090000)}); + notice.cancel (); + QVERIFY (!notice.commit (catalog, working)); + QCOMPARE (notice.visibility (catalog, working), + FrequencySuggestions::NoticeState::Visibility::Available); + + notice.selected_additions (Items {frequency (14090000)}); + Items partial {frequency (14074000), frequency (14090000)}; + QVERIFY (notice.commit (catalog, partial)); + QCOMPARE (notice.visibility (catalog, partial), + FrequencySuggestions::NoticeState::Visibility::Hidden); + QCOMPARE (notice.seen_keys ().size (), 3); + } + + void noticeDoesNotAcknowledgeRemovedSelection () + { + Items catalog {frequency (14074000), frequency (14090000)}; + Items saved {frequency (14074000)}; + FrequencySuggestions::NoticeState notice; + notice.selected_additions (Items {frequency (14090000)}); + QVERIFY (!notice.commit (catalog, saved)); + QCOMPARE (notice.visibility (catalog, saved), + FrequencySuggestions::NoticeState::Visibility::Available); + } + + void dismissPersistsIndependentlyOfSettingsCancel () + { + Items catalog {frequency (14074000), frequency (14090000)}; + Items working {frequency (14074000)}; + FrequencySuggestions::NoticeState notice; + notice.dismiss (catalog); + notice.cancel (); + QCOMPARE (notice.visibility (catalog, working), + FrequencySuggestions::NoticeState::Visibility::Hidden); + catalog.append (frequency (14091000)); + QCOMPARE (notice.visibility (catalog, working), + FrequencySuggestions::NoticeState::Visibility::New); + } + + void chooserAddsOnlyCheckedRows () + { + Bands bands; + Items catalog {frequency (14074000), frequency (14090000)}; + Items working {frequency (14074000, Modes::FT8, IARURegions::ALL, + "My row")}; + SuggestedFrequenciesDialog dialog {catalog, working, bands, {}}; + auto * list = dialog.findChild<QScrollArea *> (QStringLiteral ("suggested_frequencies_list")); + QVERIFY (list); + auto checkboxes = list->findChildren<QCheckBox *> (); + QCOMPARE (checkboxes.size (), 1); + auto * checkbox = checkboxes.first (); + QVERIFY (dialog.selected_items ().isEmpty ()); + + dialog.show (); + checkbox->setFocus (); + QTest::keyClick (checkbox, Qt::Key_Space); + QCOMPARE (dialog.selected_items ().size (), 1); + QCOMPARE (dialog.selected_items ().first ().frequency_, Radio::Frequency {14090000}); + QCOMPARE (working.size (), 1); + + auto * accessible = QAccessible::queryAccessibleInterface (checkbox); + QVERIFY (accessible); + QCOMPARE (accessible->role (), QAccessible::CheckBox); + auto * action = accessible->actionInterface (); + QVERIFY (action); + QVERIFY (action->actionNames ().contains (QAccessibleActionInterface::toggleAction ())); + action->doAction (QAccessibleActionInterface::toggleAction ()); + QVERIFY (dialog.selected_items ().isEmpty ()); + action->doAction (QAccessibleActionInterface::toggleAction ()); + QCOMPARE (dialog.selected_items ().size (), 1); + QStyleOptionButton option; + option.initFrom (checkbox); + auto const indicator = checkbox->style ()->subElementRect ( + QStyle::SE_CheckBoxIndicator, &option, checkbox); + QVERIFY (indicator.isValid ()); + QTest::mouseClick (checkbox, Qt::LeftButton, Qt::NoModifier, indicator.center ()); + QVERIFY (dialog.selected_items ().isEmpty ()); + QTest::mouseClick (checkbox, Qt::LeftButton, Qt::NoModifier, indicator.center ()); + QCOMPARE (dialog.selected_items ().size (), 1); + + QTest::keyClick (checkbox, Qt::Key_Tab); + QVERIFY (dialog.focusWidget ()); + QCOMPARE (dialog.focusWidget ()->property ("text").toString (), QStringLiteral ("Cancel")); + QTest::keyClick (dialog.focusWidget (), Qt::Key_Tab); + QVERIFY (dialog.focusWidget ()); + QCOMPARE (dialog.focusWidget ()->property ("text").toString (), QStringLiteral ("Add selected (1)")); + QTest::keyClick (dialog.focusWidget (), Qt::Key_Backtab); + QVERIFY (dialog.focusWidget ()); + QCOMPARE (dialog.focusWidget ()->property ("text").toString (), QStringLiteral ("Cancel")); + checkbox->setFocus (); + QTest::keyClick (checkbox, Qt::Key_Backtab); + QVERIFY (dialog.focusWidget ()); + QCOMPARE (dialog.focusWidget ()->property ("text").toString (), + QStringLiteral ("Show selected only")); + + auto * selected_only = dialog.focusWidget (); + QTest::mouseClick (selected_only, Qt::LeftButton); + checkboxes = list->findChildren<QCheckBox *> (); + QCOMPARE (checkboxes.size (), 1); + checkboxes.first ()->setChecked (false); + QCoreApplication::processEvents (); + QVERIFY (!selected_only->property ("checked").toBool ()); + QVERIFY (dialog.selected_items ().isEmpty ()); + QCOMPARE (list->findChildren<QCheckBox *> ().size (), 1); + } +}; + +QTEST_MAIN (TestFrequencySuggestions) +#include "test_frequency_suggestions.moc" diff --git a/tests/unit/common/test_log_window_deletion.cpp b/tests/unit/common/test_log_window_deletion.cpp new file mode 100644 index 00000000..27854a27 --- /dev/null +++ b/tests/unit/common/test_log_window_deletion.cpp @@ -0,0 +1,202 @@ +#include <QtTest> + +#include <memory> +#include <QAbstractButton> +#include <QAction> +#include <QDir> +#include <QItemSelectionModel> +#include <QMessageBox> +#include <QNetworkAccessManager> +#include <QSettings> +#include <QSqlDatabase> +#include <QSqlQuery> +#include <QSqlRecord> +#include <QSqlTableModel> +#include <QStandardPaths> +#include <QTableView> +#include <QTemporaryDir> +#include <QTimer> + +#include "Configuration.hpp" +#include "MetaDataRegistry.hpp" +#include "widgets/AbstractLogWindow.hpp" +#include "widgets/itoneAndicw.h" + +int volatile itone[MAX_NUM_SYMBOLS] {}; +float gran () { return 0; } + +namespace +{ + class LogWindow final : public AbstractLogWindow + { + public: + LogWindow (QSettings * settings, Configuration const * configuration) + : AbstractLogWindow {"log", settings, configuration} {} + + int changes {}; + + private: + void log_model_changed (int) override { ++changes; } + }; +} + +class TestLogWindowDeletion final : public QObject +{ + Q_OBJECT + + QTemporaryDir directory_; + QNetworkAccessManager network_; + std::unique_ptr<QSettings> settings_; + std::unique_ptr<Configuration> configuration_; + QSqlDatabase database_; + std::unique_ptr<QSqlTableModel> model_; + std::unique_ptr<LogWindow> window_; + QTableView * view_ {}; + + void select_ids (std::initializer_list<int> ids) + { + while (model_->canFetchMore (QModelIndex {})) model_->fetchMore (QModelIndex {}); + auto selection = view_->selectionModel (); + selection->clearSelection (); + for (int id : ids) + { + for (int row = 0; row < view_->model ()->rowCount (); ++row) + { + auto index = view_->model ()->index (row, 0); + if (index.data (Qt::EditRole).toInt () == id) + selection->select (index, QItemSelectionModel::Select | QItemSelectionModel::Rows); + } + } + QCOMPARE (selection->selectedRows ().size (), static_cast<int> (ids.size ())); + } + + bool append_contact () + { + model_->setEditStrategy (QSqlTableModel::OnManualSubmit); + auto record = model_->record (); + record.setValue ("id", 601); + record.setValue ("call", "NEW"); + record.setValue ("band", "20m"); + record.setValue ("datetime", "000601"); + bool const result = model_->insertRecord (-1, record) && model_->submitAll (); + model_->setEditStrategy (QSqlTableModel::OnFieldChange); + return result; + } + + bool contains_id (int id) + { + QSqlQuery query {database_}; + query.prepare ("SELECT id FROM contacts WHERE id = ?"); + query.addBindValue (id); + return query.exec () && query.next (); + } + + template<typename DuringConfirmation> + void delete_selected (QMessageBox::StandardButton answer, DuringConfirmation during_confirmation) + { + QTimer::singleShot (0, this, [=] { + auto box = qobject_cast<QMessageBox *> (QApplication::activeModalWidget ()); + Q_ASSERT (box); + during_confirmation (); + box->button (answer)->click (); + }); + view_->actions ().first ()->trigger (); + } + +private slots: + void initTestCase () + { + register_types (); + QStandardPaths::setTestModeEnabled (true); + QCoreApplication::setApplicationName ("test_log_window_deletion"); + QVERIFY (directory_.isValid ()); + settings_.reset (new QSettings {directory_.filePath ("settings.ini"), QSettings::IniFormat}); + configuration_.reset (new Configuration {&network_, QDir {directory_.path ()}, settings_.get (), nullptr}); + } + + void init () + { + database_ = QSqlDatabase::addDatabase ("QSQLITE", "log-window-deletion"); + database_.setDatabaseName (":memory:"); + QVERIFY (database_.open ()); + QSqlQuery query {database_}; + QVERIFY (query.exec ("CREATE TABLE contacts (id INTEGER PRIMARY KEY, call TEXT, band TEXT, datetime TEXT)")); + QVERIFY (database_.transaction ()); + query.prepare ("INSERT INTO contacts VALUES (?, ?, '20m', ?)"); + for (int id = 1; id <= 600; ++id) + { + query.bindValue (0, id); + query.bindValue (1, QString {"CALL%1"}.arg (id)); + query.bindValue (2, QString {"%1"}.arg (id, 6, 10, QChar {'0'})); + QVERIFY (query.exec ()); + } + QVERIFY (database_.commit ()); + model_.reset (new QSqlTableModel {nullptr, database_}); + model_->setTable ("contacts"); + model_->setEditStrategy (QSqlTableModel::OnFieldChange); + QVERIFY (model_->select ()); + QVERIFY (model_->rowCount () < 600); + window_.reset (new LogWindow {settings_.get (), configuration_.get ()}); + view_ = new QTableView {window_.get ()}; + view_->setModel (model_.get ()); + window_->set_log_view (view_); + } + + void cleanup () + { + // Finish fetching before draining auto-scroll callbacks, which can otherwise fetch more rows. + while (model_->canFetchMore (QModelIndex {})) model_->fetchMore (QModelIndex {}); + QCoreApplication::processEvents (); + window_.reset (); + model_.reset (); + database_.close (); + database_ = QSqlDatabase {}; + QSqlDatabase::removeDatabase ("log-window-deletion"); + } + + void confirmed_ids_survive_refresh () + { + select_ids ({550, 600}); + bool inserted = false; + int fetched_after_refresh = 600; + delete_selected (QMessageBox::Yes, [&] { + inserted = append_contact (); + fetched_after_refresh = model_->rowCount (); + }); + QVERIFY (inserted); + QVERIFY (fetched_after_refresh < 550); + QVERIFY (!contains_id (550)); + QVERIFY (!contains_id (600)); + QVERIFY (contains_id (601)); + QVERIFY (contains_id (42)); + QCOMPARE (window_->changes, 1); + } + + void cancel_after_refresh_preserves_contacts () + { + select_ids ({550, 600}); + bool inserted = false; + delete_selected (QMessageBox::No, [&] { inserted = append_contact (); }); + QVERIFY (inserted); + QVERIFY (contains_id (550)); + QVERIFY (contains_id (600)); + QVERIFY (contains_id (601)); + QCOMPARE (window_->changes, 0); + } + + void nonadjacent_ids_survive_sort_change () + { + select_ids ({12, 80, 599}); + delete_selected (QMessageBox::Yes, [&] { model_->sort (3, Qt::DescendingOrder); }); + QVERIFY (!contains_id (12)); + QVERIFY (!contains_id (80)); + QVERIFY (!contains_id (599)); + QVERIFY (contains_id (13)); + QVERIFY (contains_id (79)); + QVERIFY (contains_id (600)); + QCOMPARE (window_->changes, 1); + } +}; + +QTEST_MAIN (TestLogWindowDeletion) +#include "test_log_window_deletion.moc" diff --git a/tests/unit/common/test_qt_helpers.cpp b/tests/unit/common/test_qt_helpers.cpp index b56627c0..a0d4ce5b 100644 --- a/tests/unit/common/test_qt_helpers.cpp +++ b/tests/unit/common/test_qt_helpers.cpp @@ -6,6 +6,7 @@ #include <QFont> #include <QTemporaryDir> +#include <algorithm> #include <limits> #include "qt_helpers.hpp" @@ -18,6 +19,38 @@ class TestQtHelpers public: private: + Q_SLOT void serial_port_order_data () + { + QTest::addColumn<QStringList> ("expected"); + QTest::newRow ("COM-zero") << QStringList {"COM0", "COM1", "COM2", "COM10"}; + QTest::newRow ("Unix-prefixes") << QStringList { + "ttyACM0", "ttyACM2", "ttyACM10", "ttyUSB0", "ttyUSB2", "ttyUSB10"}; + QTest::newRow ("macOS-names") << QStringList { + "cu.Bluetooth-Incoming-Port", "cu.usbserial-2", "cu.usbserial-10"}; + QTest::newRow ("leading-zeroes") << QStringList { + "COM0", "COM00", "COM0002", "COM02", "COM2", "COM10"}; + QTest::newRow ("large-suffixes") << QStringList { + "ttyUSB2", "ttyUSB10", "ttyUSB2147483648", "ttyUSB99999999999999999999", + "ttyUSB100000000000000000000"}; + QTest::newRow ("mixed-names") << QStringList { + "", "COM", "COM0", "COM2", "COM10", "COM2A", "COM2A2", "COM2A10", + "COMA", "com0", "ttyUSB", "ttyUSB0"}; + } + + Q_SLOT void serial_port_order () + { + QFETCH (QStringList, expected); + auto actual = expected; + std::reverse (actual.begin (), actual.end ()); + std::sort (actual.begin (), actual.end (), serial_port_name_less); + QCOMPARE (actual, expected); + + // Check every pair so mixed prefixes and numeric ties have a consistent order. + for (int i = 0; i < expected.size (); ++i) + for (int j = 0; j < expected.size (); ++j) + QCOMPARE (serial_port_name_less (expected.at (i), expected.at (j)), i < j); + } + Q_SLOT void round_15s_date_time_up () { QDateTime dt {QDate {2020, 8, 6}, QTime {14, 15, 22, 500}}; diff --git a/tests/unit/common/test_radio_callsign.cpp b/tests/unit/common/test_radio_callsign.cpp new file mode 100644 index 00000000..c19cfc1e --- /dev/null +++ b/tests/unit/common/test_radio_callsign.cpp @@ -0,0 +1,128 @@ +#include <QtTest> + +#include "Radio.hpp" + +class TestRadioCallsign final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void identity_data (); + void identity (); + void classification_data (); + void classification (); + void standard_data (); + void standard (); + void decodedGrid_data (); + void decodedGrid (); +}; + +void TestRadioCallsign::identity_data () +{ + QTest::addColumn<QString> ("callsign"); + QTest::addColumn<QString> ("base"); + QTest::addColumn<QString> ("prefix"); + + QTest::newRow ("ordinary") << QString {"K1ABC"} << QString {"K1ABC"} << QString {"K1ABC"}; + QTest::newRow ("portable prefix") << QString {"EA8/K1ABC"} << QString {"K1ABC"} << QString {"EA8"}; + QTest::newRow ("portable suffix") << QString {"K1ABC/EA8"} << QString {"K1ABC"} << QString {"EA8"}; + QTest::newRow ("equal length") << QString {"EA8/K1A"} << QString {"K1A"} << QString {"EA8"}; +} + +void TestRadioCallsign::identity () +{ + QFETCH (QString, callsign); + QFETCH (QString, base); + QFETCH (QString, prefix); + + for (auto const& suffix : {QString {}, QString {"/P"}, QString {"/QRP"}, QString {"/P/QRP"}}) + { + auto const input = callsign + suffix; + QCOMPARE (Radio::base_callsign (input), base); + QCOMPARE (Radio::effective_prefix (input), prefix); + QCOMPARE (Radio::base_callsign (input.toLower ()), base); + QCOMPARE (Radio::effective_prefix (input.toLower ()), prefix); + } +} + +void TestRadioCallsign::classification_data () +{ + QTest::addColumn<QString> ("callsign"); + QTest::addColumn<bool> ("valid"); + QTest::addColumn<bool> ("compound"); + QTest::addColumn<bool> ("nonstandard"); + + QTest::newRow ("standard") << QString {"K1ABC"} << true << false << false; + QTest::newRow ("compound") << QString {"K1ABC/P"} << true << true << true; + QTest::newRow ("long prefix") << QString {"3DA0XYZ"} << true << false << true; + QTest::newRow ("invalid alphabet") << QString {"---"} << false << false << false; + QTest::newRow ("empty") << QString {} << false << false << false; +} + +void TestRadioCallsign::classification () +{ + QFETCH (QString, callsign); + QFETCH (bool, valid); + QFETCH (bool, compound); + QFETCH (bool, nonstandard); + + QCOMPARE (Radio::is_callsign (callsign), valid); + QCOMPARE (Radio::is_compound_callsign (callsign), compound); + QCOMPARE (Radio::is_77bit_nonstandard_callsign (callsign), nonstandard); +} + +void TestRadioCallsign::standard_data () +{ + QTest::addColumn<QString> ("callsign"); + QTest::addColumn<bool> ("standard"); + QTest::newRow ("ordinary") << QString {"K1ABC"} << true; + QTest::newRow ("case and whitespace") << QString {" k1abc "} << true; + QTest::newRow ("portable") << QString {"K1ABC/P"} << true; + QTest::newRow ("rover") << QString {"K1ABC/r"} << true; + QTest::newRow ("digit prefix") << QString {"3D2ABC"} << true; + QTest::newRow ("letter digit prefix") << QString {"A12ABC"} << true; + QTest::newRow ("no suffix letters") << QString {"K1"} << true; + QTest::newRow ("no prefix") << QString {"1ABC"} << true; + QTest::newRow ("single digit") << QString {"1"} << true; + QTest::newRow ("compound prefix") << QString {"EA8/K1ABC"} << false; + QTest::newRow ("unsupported suffix") << QString {"K1ABC/QRP"} << false; + QTest::newRow ("long prefix") << QString {"3DA0XYZ"} << false; + QTest::newRow ("long suffix") << QString {"K1ABCD"} << false; + QTest::newRow ("internal whitespace") << QString {"K1 ABC"} << false; + QTest::newRow ("empty") << QString {} << false; +} + +void TestRadioCallsign::standard () +{ + QFETCH (QString, callsign); + QFETCH (bool, standard); + QCOMPARE (Radio::is_standard_callsign (callsign), standard); +} + +void TestRadioCallsign::decodedGrid_data () +{ + QTest::addColumn<QString> ("grid"); + QTest::addColumn<bool> ("valid"); + QTest::newRow ("four characters") << QString {"FN42"} << true; + QTest::newRow ("six characters mixed case") << QString {"fn42aB"} << true; + QTest::newRow ("range limits") << QString {"RR99XX"} << true; + QTest::newRow ("acknowledgement") << QString {"RR73"} << false; + QTest::newRow ("acknowledgement case") << QString {"rR73"} << false; + QTest::newRow ("acknowledgement prefix") << QString {"RR73AA"} << false; + QTest::newRow ("field range") << QString {"SS42"} << false; + QTest::newRow ("subsquare range") << QString {"FN42YY"} << false; + QTest::newRow ("leading space") << QString {" FN42"} << false; + QTest::newRow ("trailing space") << QString {"FN42 "} << false; + QTest::newRow ("empty") << QString {} << false; +} + +void TestRadioCallsign::decodedGrid () +{ + QFETCH (QString, grid); + QFETCH (bool, valid); + QCOMPARE (grid.contains (QRegularExpression {Radio::decoded_grid_pattern ()}), valid); +} + +QTEST_GUILESS_MAIN (TestRadioCallsign) + +#include "test_radio_callsign.moc" |
